commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae61346af8a813b6c0ecbb9f232f235ada982356 | main.py | main.py | import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
| import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
| Send date to process in message | Send date to process in message
| Python | mit | projectweekend/song-feed-queue-builder | import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
- def playlists_to_process():
+ def playlists_to_process(target_date):
accounts = Table('accounts')
- target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
+ date_to_process = date.isoformat(date.today())
q = playlists_queue()
- for playlist in playlists_to_process():
+ for playlist in playlists_to_process(date_to_process):
- body = json.dumps(dict(playlist.items()))
+ data = dict(playlist.items())
+ body = json.dumps({
+ 'spotify_username': data['spotify_username'],
+ 'date_to_process': date_to_process
+ })
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
| Send date to process in message | ## Code Before:
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
## Instruction:
Send date to process in message
## Code After:
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
| import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
- def playlists_to_process():
+ def playlists_to_process(target_date):
? +++++++++++
accounts = Table('accounts')
- target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
+ date_to_process = date.isoformat(date.today())
q = playlists_queue()
- for playlist in playlists_to_process():
+ for playlist in playlists_to_process(date_to_process):
? +++++++++++++++
- body = json.dumps(dict(playlist.items()))
? -- ^ ----------- -
+ data = dict(playlist.items())
? ^^^
+ body = json.dumps({
+ 'spotify_username': data['spotify_username'],
+ 'date_to_process': date_to_process
+ })
q.write(q.new_message(body=body))
if __name__ == '__main__':
main() |
e861def07da1f0dea7f5273d06e7dc674a79025f | adventure/urls.py | adventure/urls.py | from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
url(r'^(?P<path>.*)/$', views.index),
]
| from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
# NOTE: this currently matches URLs without a . in them, so .js files and broken images will still 404.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
url(r'^(?P<path>[^\.]*)/$', views.index),
]
| Update Django catch-all URL path to not catch URLs with a . in them. | Update Django catch-all URL path to not catch URLs with a . in them.
This makes missing JS files 404 properly instead of returning the HTML 404 page which confuses the parser.
| Python | mit | kdechant/eamon,kdechant/eamon,kdechant/eamon,kdechant/eamon | from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
+ # NOTE: this currently matches URLs without a . in them, so .js files and broken images will still 404.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
- url(r'^(?P<path>.*)/$', views.index),
+ url(r'^(?P<path>[^\.]*)/$', views.index),
]
| Update Django catch-all URL path to not catch URLs with a . in them. | ## Code Before:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
url(r'^(?P<path>.*)/$', views.index),
]
## Instruction:
Update Django catch-all URL path to not catch URLs with a . in them.
## Code After:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
# NOTE: this currently matches URLs without a . in them, so .js files and broken images will still 404.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
url(r'^(?P<path>[^\.]*)/$', views.index),
]
| from django.conf.urls import url, include
from rest_framework import routers
from . import views
from .views import PlayerViewSet, AdventureViewSet, RoomViewSet, ArtifactViewSet, EffectViewSet, MonsterViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'players', PlayerViewSet)
router.register(r'adventures', AdventureViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/rooms$', RoomViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/artifacts$', ArtifactViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/effects$', EffectViewSet)
router.register(r'adventures/(?P<adventure_id>[\w-]+)/monsters$', MonsterViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^$', views.index, name='index'),
url(r'^adventure/(?P<adventure_id>[\w-]+)/$', views.adventure, name='adventure'),
# this route is a catch-all for compatibility with the Angular routes. It must be last in the list.
+ # NOTE: this currently matches URLs without a . in them, so .js files and broken images will still 404.
# NOTE: non-existent URLs won't 404 with this in place. They will be sent into the Angular app.
- url(r'^(?P<path>.*)/$', views.index),
+ url(r'^(?P<path>[^\.]*)/$', views.index),
? +++ +
] |
5ad869909e95fa8e5e0b6a489d361c42006023a5 | openstack/__init__.py | openstack/__init__.py |
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
|
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
| Use project name to retrieve version info | Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b
| Python | apache-2.0 | openstack/python-openstacksdk,dudymas/python-openstacksdk,dudymas/python-openstacksdk,mtougeron/python-openstacksdk,mtougeron/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk |
import pbr.version
__version__ = pbr.version.VersionInfo(
- 'openstack').version_string()
+ 'python-openstacksdk').version_string()
| Use project name to retrieve version info | ## Code Before:
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
## Instruction:
Use project name to retrieve version info
## Code After:
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
import pbr.version
__version__ = pbr.version.VersionInfo(
- 'openstack').version_string()
+ 'python-openstacksdk').version_string()
? +++++++ +++
|
e435592d64dbd4f75a7cc9d1ac8bb17ab4177a2b | erpnext/patches/v4_2/default_website_style.py | erpnext/patches/v4_2/default_website_style.py | import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save()
| import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
frappe.reload_doc('website', 'doctype', 'style_settings')
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save()
| Fix default website style patch (reload doc) | [minor] Fix default website style patch (reload doc) | Python | agpl-3.0 | gangadharkadam/saloon_erp,hatwar/buyback-erpnext,gangadharkadam/v6_erp,indictranstech/Das_Erpnext,gangadharkadam/vlinkerp,shft117/SteckerApp,sheafferusa/erpnext,mahabuber/erpnext,hernad/erpnext,suyashphadtare/gd-erp,gangadharkadam/letzerp,indictranstech/internal-erpnext,indictranstech/buyback-erp,4commerce-technologies-AG/erpnext,indictranstech/buyback-erp,shitolepriya/test-erp,rohitwaghchaure/New_Theme_Erp,indictranstech/trufil-erpnext,gangadharkadam/v5_erp,mahabuber/erpnext,indictranstech/Das_Erpnext,suyashphadtare/vestasi-erp-jan-end,gangadhar-kadam/verve_test_erp,SPKian/Testing2,mbauskar/omnitech-demo-erpnext,gsnbng/erpnext,hernad/erpnext,sheafferusa/erpnext,mbauskar/phrerp,indictranstech/trufil-erpnext,mbauskar/omnitech-demo-erpnext,Tejal011089/huntercamp_erpnext,netfirms/erpnext,MartinEnder/erpnext-de,gangadhar-kadam/latestchurcherp,hatwar/Das_erpnext,indictranstech/fbd_erpnext,gangadharkadam/saloon_erp,hanselke/erpnext-1,njmube/erpnext,Tejal011089/trufil-erpnext,fuhongliang/erpnext,gangadhar-kadam/helpdesk-erpnext,SPKian/Testing2,pombredanne/erpnext,sagar30051991/ozsmart-erp,gangadharkadam/verveerp,gangadharkadam/v4_erp,gangadhar-kadam/verve_test_erp,mbauskar/phrerp,indictranstech/focal-erpnext,rohitwaghchaure/GenieManager-erpnext,rohitwaghchaure/New_Theme_Erp,mbauskar/Das_Erpnext,mbauskar/helpdesk-erpnext,suyashphadtare/sajil-erp,gangadhar-kadam/verve_test_erp,susuchina/ERPNEXT,gangadharkadam/verveerp,ShashaQin/erpnext,netfirms/erpnext,njmube/erpnext,SPKian/Testing,mbauskar/Das_Erpnext,mbauskar/sapphire-erpnext,gangadhar-kadam/verve_erp,suyashphadtare/vestasi-erp-1,gangadharkadam/vlinkerp,Tejal011089/paypal_erpnext,indictranstech/reciphergroup-erpnext,treejames/erpnext,rohitwaghchaure/erpnext_smart,gangadharkadam/v4_erp,tmimori/erpnext,suyashphadtare/vestasi-erp-final,mahabuber/erpnext,indictranstech/osmosis-erpnext,hatwar/focal-erpnext,hatwar/buyback-erpnext,treejames/erpnext,suyashphadtare/vestasi-update-erp,gangadharkadam/contributionerp,geekroot/erpnext,shitolepriya/test-erp,Tejal011089/trufil-erpnext,ThiagoGarciaAlves/erpnext,rohitwaghchaure/erpnext_smart,hernad/erpnext,ThiagoGarciaAlves/erpnext,rohitwaghchaure/digitales_erpnext,rohitwaghchaure/erpnext-receipher,BhupeshGupta/erpnext,gangadhar-kadam/helpdesk-erpnext,anandpdoshi/erpnext,meisterkleister/erpnext,suyashphadtare/gd-erp,mbauskar/omnitech-erpnext,susuchina/ERPNEXT,pombredanne/erpnext,Tejal011089/fbd_erpnext,gangadhar-kadam/verve_test_erp,Tejal011089/trufil-erpnext,indictranstech/erpnext,gsnbng/erpnext,indictranstech/trufil-erpnext,indictranstech/vestasi-erpnext,Suninus/erpnext,mbauskar/alec_frappe5_erpnext,dieface/erpnext,indictranstech/focal-erpnext,aruizramon/alec_erpnext,gangadharkadam/saloon_erp_install,sagar30051991/ozsmart-erp,indictranstech/vestasi-erpnext,mbauskar/alec_frappe5_erpnext,indictranstech/biggift-erpnext,gmarke/erpnext,gangadhar-kadam/latestchurcherp,gangadhar-kadam/verve-erp,ShashaQin/erpnext,suyashphadtare/gd-erp,suyashphadtare/sajil-final-erp,geekroot/erpnext,Drooids/erpnext,geekroot/erpnext,gangadharkadam/saloon_erp_install,indictranstech/focal-erpnext,suyashphadtare/sajil-erp,gangadharkadam/verveerp,saurabh6790/test-erp,hanselke/erpnext-1,hatwar/Das_erpnext,gangadharkadam/letzerp,gangadhar-kadam/helpdesk-erpnext,indictranstech/Das_Erpnext,mbauskar/Das_Erpnext,mbauskar/helpdesk-erpnext,Tejal011089/digitales_erpnext,anandpdoshi/erpnext,indictranstech/osmosis-erpnext,gmarke/erpnext,gangadharkadam/v4_erp,MartinEnder/erpnext-de,mbauskar/omnitech-erpnext,Tejal011089/fbd_erpnext,saurabh6790/test-erp,indictranstech/buyback-erp,mbauskar/phrerp,indictranstech/phrerp,indictranstech/trufil-erpnext,Suninus/erpnext,gsnbng/erpnext,rohitwaghchaure/digitales_erpnext,Drooids/erpnext,fuhongliang/erpnext,sheafferusa/erpnext,gangadharkadam/saloon_erp,mbauskar/sapphire-erpnext,Tejal011089/huntercamp_erpnext,indictranstech/internal-erpnext,mbauskar/sapphire-erpnext,indictranstech/fbd_erpnext,hanselke/erpnext-1,sheafferusa/erpnext,gangadharkadam/v6_erp,MartinEnder/erpnext-de,4commerce-technologies-AG/erpnext,indictranstech/biggift-erpnext,mbauskar/helpdesk-erpnext,anandpdoshi/erpnext,gangadharkadam/vlinkerp,indictranstech/reciphergroup-erpnext,gangadhar-kadam/verve-erp,mbauskar/helpdesk-erpnext,geekroot/erpnext,gangadharkadam/v5_erp,Tejal011089/digitales_erpnext,indictranstech/tele-erpnext,ThiagoGarciaAlves/erpnext,suyashphadtare/vestasi-erp-final,Tejal011089/huntercamp_erpnext,indictranstech/reciphergroup-erpnext,suyashphadtare/vestasi-erp-jan-end,indictranstech/biggift-erpnext,rohitwaghchaure/GenieManager-erpnext,mbauskar/omnitech-erpnext,suyashphadtare/vestasi-erp-final,indictranstech/vestasi-erpnext,saurabh6790/test-erp,treejames/erpnext,pawaranand/phrerp,gangadhar-kadam/verve_erp,mbauskar/sapphire-erpnext,gangadharkadam/letzerp,aruizramon/alec_erpnext,suyashphadtare/vestasi-update-erp,gangadharkadam/contributionerp,fuhongliang/erpnext,netfirms/erpnext,indictranstech/osmosis-erpnext,SPKian/Testing,meisterkleister/erpnext,gangadhar-kadam/verve_live_erp,tmimori/erpnext,hatwar/focal-erpnext,rohitwaghchaure/GenieManager-erpnext,indictranstech/tele-erpnext,gangadharkadam/saloon_erp_install,indictranstech/fbd_erpnext,pawaranand/phrerp,gangadharkadam/v6_erp,suyashphadtare/sajil-final-erp,indictranstech/buyback-erp,treejames/erpnext,suyashphadtare/test,mbauskar/alec_frappe5_erpnext,suyashphadtare/vestasi-erp-jan-end,SPKian/Testing,tmimori/erpnext,gangadharkadam/v4_erp,suyashphadtare/vestasi-erp-1,indictranstech/phrerp,suyashphadtare/sajil-final-erp,netfirms/erpnext,gmarke/erpnext,BhupeshGupta/erpnext,indictranstech/tele-erpnext,Tejal011089/osmosis_erpnext,hatwar/focal-erpnext,Tejal011089/digitales_erpnext,suyashphadtare/vestasi-erp-jan-end,MartinEnder/erpnext-de,Suninus/erpnext,indictranstech/Das_Erpnext,Tejal011089/osmosis_erpnext,rohitwaghchaure/GenieManager-erpnext,gangadhar-kadam/verve_live_erp,rohitwaghchaure/erpnext-receipher,Tejal011089/digitales_erpnext,shitolepriya/test-erp,shft117/SteckerApp,indictranstech/osmosis-erpnext,Tejal011089/fbd_erpnext,gangadhar-kadam/verve_live_erp,hatwar/buyback-erpnext,shft117/SteckerApp,tmimori/erpnext,dieface/erpnext,mbauskar/alec_frappe5_erpnext,gangadharkadam/v5_erp,indictranstech/phrerp,gangadhar-kadam/verve_erp,indictranstech/internal-erpnext,hatwar/buyback-erpnext,gangadharkadam/verveerp,njmube/erpnext,rohitwaghchaure/erpnext-receipher,Aptitudetech/ERPNext,aruizramon/alec_erpnext,gsnbng/erpnext,susuchina/ERPNEXT,gangadharkadam/v5_erp,hanselke/erpnext-1,rohitwaghchaure/digitales_erpnext,rohitwaghchaure/digitales_erpnext,Drooids/erpnext,susuchina/ERPNEXT,njmube/erpnext,mbauskar/omnitech-demo-erpnext,gangadharkadam/v6_erp,dieface/erpnext,gangadharkadam/contributionerp,ShashaQin/erpnext,saurabh6790/test-erp,suyashphadtare/vestasi-erp-1,SPKian/Testing,suyashphadtare/test,rohitwaghchaure/New_Theme_Erp,hernad/erpnext,rohitwaghchaure/New_Theme_Erp,meisterkleister/erpnext,hatwar/Das_erpnext,4commerce-technologies-AG/erpnext,Tejal011089/osmosis_erpnext,mahabuber/erpnext,suyashphadtare/vestasi-update-erp,pombredanne/erpnext,Tejal011089/trufil-erpnext,gangadharkadam/saloon_erp_install,SPKian/Testing2,mbauskar/Das_Erpnext,indictranstech/reciphergroup-erpnext,ThiagoGarciaAlves/erpnext,gangadharkadam/contributionerp,suyashphadtare/gd-erp,shitolepriya/test-erp,gangadhar-kadam/verve_erp,gangadhar-kadam/helpdesk-erpnext,Tejal011089/fbd_erpnext,pombredanne/erpnext,dieface/erpnext,hatwar/focal-erpnext,ShashaQin/erpnext,indictranstech/vestasi-erpnext,gangadhar-kadam/latestchurcherp,gangadhar-kadam/verve-erp,gangadhar-kadam/latestchurcherp,indictranstech/biggift-erpnext,fuhongliang/erpnext,suyashphadtare/sajil-erp,shft117/SteckerApp,indictranstech/erpnext,mbauskar/phrerp,BhupeshGupta/erpnext,indictranstech/tele-erpnext,SPKian/Testing2,aruizramon/alec_erpnext,indictranstech/fbd_erpnext,rohitwaghchaure/erpnext_smart,hatwar/Das_erpnext,pawaranand/phrerp,pawaranand/phrerp,Tejal011089/osmosis_erpnext,sagar30051991/ozsmart-erp,anandpdoshi/erpnext,suyashphadtare/test,indictranstech/phrerp,indictranstech/erpnext,Tejal011089/paypal_erpnext,indictranstech/internal-erpnext,gangadharkadam/saloon_erp,gmarke/erpnext,Tejal011089/paypal_erpnext,sagar30051991/ozsmart-erp,BhupeshGupta/erpnext,Drooids/erpnext,Suninus/erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_live_erp,meisterkleister/erpnext,mbauskar/omnitech-erpnext,gangadharkadam/letzerp,mbauskar/omnitech-demo-erpnext,rohitwaghchaure/erpnext-receipher,indictranstech/focal-erpnext,Tejal011089/paypal_erpnext,Tejal011089/huntercamp_erpnext,indictranstech/erpnext | import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
+ frappe.reload_doc('website', 'doctype', 'style_settings')
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save()
| Fix default website style patch (reload doc) | ## Code Before:
import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save()
## Instruction:
Fix default website style patch (reload doc)
## Code After:
import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
frappe.reload_doc('website', 'doctype', 'style_settings')
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save()
| import frappe
from frappe.templates.pages.style_settings import default_properties
def execute():
+ frappe.reload_doc('website', 'doctype', 'style_settings')
style_settings = frappe.get_doc("Style Settings", "Style Settings")
if not style_settings.apply_style:
style_settings.update(default_properties)
style_settings.apply_style = 1
style_settings.save() |
da6f284cf1ffa1397c32167e1e23189ea29e5b2f | IPython/html/widgets/widget_container.py | IPython/html/widgets/widget_container.py |
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, **kwargs):
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
|
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, children = None, **kwargs):
kwargs['children'] = children
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
| Make Container widgets take children as the first positional argument | Make Container widgets take children as the first positional argument
This makes creating containers less cumbersome: Container([list, of, children]), rather than Container(children=[list, of, children])
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
- def __init__(self, **kwargs):
+ def __init__(self, children = None, **kwargs):
+ kwargs['children'] = children
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
| Make Container widgets take children as the first positional argument | ## Code Before:
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, **kwargs):
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
## Instruction:
Make Container widgets take children as the first positional argument
## Code After:
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, children = None, **kwargs):
kwargs['children'] = children
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
|
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
- def __init__(self, **kwargs):
+ def __init__(self, children = None, **kwargs):
? +++++++++++++++++
+ kwargs['children'] = children
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True) |
8c819a1cb9df54c00b7246a07e2ba832b763876d | stream_django/templatetags/activity_tags.py | stream_django/templatetags/activity_tags.py | from django import template
from django.template import Context, loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
context = Context(context)
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity)
| from django import template
from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity)
| Use dict as a context object for Django 1.11 compatibility | Use dict as a context object for Django 1.11 compatibility
Django’s template rendering in 1.11 needs a dictionary as the context
instead of the object Context, otherwise the following error is raised:
context must be a dict rather than Context.
| Python | bsd-3-clause | GetStream/stream-django,GetStream/stream-django | from django import template
- from django.template import Context, loader
+ from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
- context = Context(context)
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity)
| Use dict as a context object for Django 1.11 compatibility | ## Code Before:
from django import template
from django.template import Context, loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
context = Context(context)
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity)
## Instruction:
Use dict as a context object for Django 1.11 compatibility
## Code After:
from django import template
from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity)
| from django import template
- from django.template import Context, loader
? ---------
+ from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriched_data(activity, policy):
message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))
if policy == IGNORE:
pass
elif policy == FAIL:
raise MissingDataException(message)
elif policy == LOG:
logger.warn(message)
else:
raise TypeError('%s is not a valid missing_data_policy' % policy)
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
if hasattr(activity, 'enriched') and not activity.enriched:
handle_not_enriched_data(activity, missing_data_policy)
return ''
if template_prefix != '':
template_prefix = '%s_' % template_prefix
if 'activities' in activity:
template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
else:
template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])
tmpl = loader.get_template(template_name)
context['activity'] = activity
- context = Context(context)
return tmpl.render(context)
register.simple_tag(takes_context=True)(render_activity) |
04557bbff362ae3b89e7dd98a1fb11e0aaeba50e | common/djangoapps/student/migrations/0010_auto_20170207_0458.py | common/djangoapps/student/migrations/0010_auto_20170207_0458.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
migrations.RunSQL(
# Do nothing:
"select 1",
"select 1"
)
]
| from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
# Nothing to do.
]
| Make this no-op migration be a true no-op. | Make this no-op migration be a true no-op.
| Python | agpl-3.0 | philanthropy-u/edx-platform,lduarte1991/edx-platform,eduNEXT/edx-platform,msegado/edx-platform,cpennington/edx-platform,hastexo/edx-platform,a-parhom/edx-platform,ESOedX/edx-platform,angelapper/edx-platform,gymnasium/edx-platform,eduNEXT/edunext-platform,pepeportela/edx-platform,ESOedX/edx-platform,pepeportela/edx-platform,miptliot/edx-platform,BehavioralInsightsTeam/edx-platform,appsembler/edx-platform,msegado/edx-platform,appsembler/edx-platform,eduNEXT/edx-platform,TeachAtTUM/edx-platform,gymnasium/edx-platform,Lektorium-LLC/edx-platform,miptliot/edx-platform,edx/edx-platform,procangroup/edx-platform,mitocw/edx-platform,romain-li/edx-platform,miptliot/edx-platform,CredoReference/edx-platform,Lektorium-LLC/edx-platform,cpennington/edx-platform,proversity-org/edx-platform,fintech-circle/edx-platform,jolyonb/edx-platform,ahmedaljazzar/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,stvstnfrd/edx-platform,BehavioralInsightsTeam/edx-platform,gsehub/edx-platform,edx-solutions/edx-platform,teltek/edx-platform,cpennington/edx-platform,pepeportela/edx-platform,BehavioralInsightsTeam/edx-platform,arbrandes/edx-platform,raccoongang/edx-platform,stvstnfrd/edx-platform,ahmedaljazzar/edx-platform,hastexo/edx-platform,arbrandes/edx-platform,ESOedX/edx-platform,CredoReference/edx-platform,eduNEXT/edunext-platform,mitocw/edx-platform,stvstnfrd/edx-platform,fintech-circle/edx-platform,mitocw/edx-platform,pabloborrego93/edx-platform,gsehub/edx-platform,kmoocdev2/edx-platform,angelapper/edx-platform,jolyonb/edx-platform,gymnasium/edx-platform,eduNEXT/edx-platform,gsehub/edx-platform,msegado/edx-platform,teltek/edx-platform,TeachAtTUM/edx-platform,appsembler/edx-platform,pepeportela/edx-platform,Edraak/edraak-platform,pabloborrego93/edx-platform,a-parhom/edx-platform,fintech-circle/edx-platform,pabloborrego93/edx-platform,appsembler/edx-platform,lduarte1991/edx-platform,jolyonb/edx-platform,eduNEXT/edunext-platform,edx-solutions/edx-platform,teltek/edx-platform,proversity-org/edx-platform,proversity-org/edx-platform,edx-solutions/edx-platform,eduNEXT/edx-platform,Lektorium-LLC/edx-platform,edx/edx-platform,kmoocdev2/edx-platform,gsehub/edx-platform,lduarte1991/edx-platform,miptliot/edx-platform,procangroup/edx-platform,CredoReference/edx-platform,teltek/edx-platform,procangroup/edx-platform,philanthropy-u/edx-platform,arbrandes/edx-platform,EDUlib/edx-platform,Edraak/edraak-platform,Edraak/edraak-platform,jolyonb/edx-platform,raccoongang/edx-platform,gymnasium/edx-platform,fintech-circle/edx-platform,raccoongang/edx-platform,pabloborrego93/edx-platform,Stanford-Online/edx-platform,stvstnfrd/edx-platform,edx/edx-platform,kmoocdev2/edx-platform,proversity-org/edx-platform,CredoReference/edx-platform,ahmedaljazzar/edx-platform,lduarte1991/edx-platform,romain-li/edx-platform,philanthropy-u/edx-platform,ahmedaljazzar/edx-platform,kmoocdev2/edx-platform,romain-li/edx-platform,Edraak/edraak-platform,EDUlib/edx-platform,romain-li/edx-platform,cpennington/edx-platform,eduNEXT/edunext-platform,ESOedX/edx-platform,edx/edx-platform,Stanford-Online/edx-platform,romain-li/edx-platform,philanthropy-u/edx-platform,angelapper/edx-platform,edx-solutions/edx-platform,Lektorium-LLC/edx-platform,hastexo/edx-platform,hastexo/edx-platform,a-parhom/edx-platform,procangroup/edx-platform,BehavioralInsightsTeam/edx-platform,mitocw/edx-platform,kmoocdev2/edx-platform,msegado/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,TeachAtTUM/edx-platform,msegado/edx-platform,TeachAtTUM/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,raccoongang/edx-platform,a-parhom/edx-platform | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
+ # Nothing to do.
- migrations.RunSQL(
- # Do nothing:
- "select 1",
- "select 1"
- )
]
| Make this no-op migration be a true no-op. | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
migrations.RunSQL(
# Do nothing:
"select 1",
"select 1"
)
]
## Instruction:
Make this no-op migration be a true no-op.
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
# Nothing to do.
]
| from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20170111_0422'),
]
# This migration was to add a constraint that we lost in the Django
# 1.4->1.8 upgrade. But since the constraint used to be created, production
# would already have the constraint even before running the migration, and
# running the migration would fail. We needed to make the migration
# idempotent. Instead of reverting this migration while we did that, we
# edited it to be a SQL no-op, so that people who had already applied it
# wouldn't end up with a ghost migration.
# It had been:
#
# migrations.RunSQL(
# "create unique index email on auth_user (email);",
# "drop index email on auth_user;"
# )
operations = [
+ # Nothing to do.
- migrations.RunSQL(
- # Do nothing:
- "select 1",
- "select 1"
- )
] |
e6e6918b54d691803c48f217f0074d5bcdd9df50 | endpoint/csp.py | endpoint/csp.py |
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
util.mail.send("ksi-admin@fi.muni.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
|
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
util.mail.send("me@apophis.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
| Send CSP reports right to apophis. | Send CSP reports right to apophis.
| Python | mit | fi-ksi/web-backend,fi-ksi/web-backend |
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
- util.mail.send("ksi-admin@fi.muni.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
+ util.mail.send("me@apophis.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
| Send CSP reports right to apophis. | ## Code Before:
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
util.mail.send("ksi-admin@fi.muni.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
## Instruction:
Send CSP reports right to apophis.
## Code After:
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
util.mail.send("me@apophis.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
|
import falcon, util, json, sys, traceback
# Content-security policy reports of frontend
# Every CSP report is forwarded to ksi-admin@fi.muni.cz.
# This is testing solution, if a lot of spam occurs, some intelligence should
# be added to this endpoint.
class CSP(object):
def on_post(self, req, resp):
data = json.loads(req.stream.read())
text = "<p>" + util.config.ksi_web() + \
"<br><pre>" + json.dumps(data, indent=4) + "</pre></p>" + \
util.mail.easteregg()
try:
- util.mail.send("ksi-admin@fi.muni.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
? ^ ---------------
+ util.mail.send("me@apophis.cz", "[KSI-WEB] CSP report", text.decode('utf-8'), )
? ^^^^^^^^^
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr)
req.context['result'] = {}
resp.status = falcon.HTTP_200
|
a673bc6b3b9daf27404e4d330819bebc25a73608 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| import os
import testinfra.utils.ansible_runner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_basic_login(host):
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
driver.get(url + "/gettingstarted")
element = wait.until(EC.title_is(('Graylog - Sign in')))
#login
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
element = wait.until(EC.title_is(('Graylog - Getting started')))
driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| Add Selenium test for basic logic. | Add Selenium test for basic logic.
| Python | apache-2.0 | Graylog2/graylog-ansible-role | import os
import testinfra.utils.ansible_runner
+ from selenium import webdriver
+ from selenium.webdriver.common.keys import Keys
+ from selenium.webdriver.support.ui import WebDriverWait
+ from selenium.webdriver.support import expected_conditions as EC
+ import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
+
+ def test_basic_login(host):
+ driver = webdriver.Chrome()
+ wait = WebDriverWait(driver, 10)
+
+ url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
+
+ driver.get(url + "/gettingstarted")
+
+ element = wait.until(EC.title_is(('Graylog - Sign in')))
+
+ #login
+ uid_field = driver.find_element_by_name("username")
+ uid_field.clear()
+ uid_field.send_keys("admin")
+ password_field = driver.find_element_by_name("password")
+ password_field.clear()
+ password_field.send_keys("admin")
+ password_field.send_keys(Keys.RETURN)
+
+ element = wait.until(EC.title_is(('Graylog - Getting started')))
+
+ driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| Add Selenium test for basic logic. | ## Code Before:
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
## Instruction:
Add Selenium test for basic logic.
## Code After:
import os
import testinfra.utils.ansible_runner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_basic_login(host):
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
driver.get(url + "/gettingstarted")
element = wait.until(EC.title_is(('Graylog - Sign in')))
#login
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
element = wait.until(EC.title_is(('Graylog - Getting started')))
driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| import os
import testinfra.utils.ansible_runner
+ from selenium import webdriver
+ from selenium.webdriver.common.keys import Keys
+ from selenium.webdriver.support.ui import WebDriverWait
+ from selenium.webdriver.support import expected_conditions as EC
+ import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
+
+ def test_basic_login(host):
+ driver = webdriver.Chrome()
+ wait = WebDriverWait(driver, 10)
+
+ url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
+
+ driver.get(url + "/gettingstarted")
+
+ element = wait.until(EC.title_is(('Graylog - Sign in')))
+
+ #login
+ uid_field = driver.find_element_by_name("username")
+ uid_field.clear()
+ uid_field.send_keys("admin")
+ password_field = driver.find_element_by_name("password")
+ password_field.clear()
+ password_field.send_keys("admin")
+ password_field.send_keys(Keys.RETURN)
+
+ element = wait.until(EC.title_is(('Graylog - Getting started')))
+
+ driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True |
e6210531dac1d7efd5fd4d343dcac74a0b74515e | request_profiler/settings.py | request_profiler/settings.py | from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
GLOBAL_EXCLUDE_FUNC = getattr(settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC', lambda r: True)
| from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
GLOBAL_EXCLUDE_FUNC = getattr(
settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC',
lambda r: not (hasattr(r, 'user') and r.user.is_staff)
)
| Update GLOBAL_EXCLUDE_FUNC default to exclude admins | Update GLOBAL_EXCLUDE_FUNC default to exclude admins
| Python | mit | yunojuno/django-request-profiler,yunojuno/django-request-profiler,sigshen/django-request-profiler,sigshen/django-request-profiler | from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
- GLOBAL_EXCLUDE_FUNC = getattr(settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC', lambda r: True)
+ GLOBAL_EXCLUDE_FUNC = getattr(
+ settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC',
+ lambda r: not (hasattr(r, 'user') and r.user.is_staff)
+ )
| Update GLOBAL_EXCLUDE_FUNC default to exclude admins | ## Code Before:
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
GLOBAL_EXCLUDE_FUNC = getattr(settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC', lambda r: True)
## Instruction:
Update GLOBAL_EXCLUDE_FUNC default to exclude admins
## Code After:
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
GLOBAL_EXCLUDE_FUNC = getattr(
settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC',
lambda r: not (hasattr(r, 'user') and r.user.is_staff)
)
| from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_TIMEOUT = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_TIMEOUT', 10) # noqa
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
- GLOBAL_EXCLUDE_FUNC = getattr(settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC', lambda r: True)
+ GLOBAL_EXCLUDE_FUNC = getattr(
+ settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC',
+ lambda r: not (hasattr(r, 'user') and r.user.is_staff)
+ ) |
c3cb6a294fe83557d86d9415f8cdf8efb4f7e59f | elevator/message.py | elevator/message.py | import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return [unicode(d) for d in datas]
| import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return datas
| Fix : response datas list should not be unicoded | Fix : response datas list should not be unicoded
| Python | mit | oleiade/Elevator | import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
- return [unicode(d) for d in datas]
+ return datas
- | Fix : response datas list should not be unicoded | ## Code Before:
import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return [unicode(d) for d in datas]
## Instruction:
Fix : response datas list should not be unicoded
## Code After:
import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
return datas
| import msgpack
import logging
class MessageFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Request(object):
"""Handler objects for frontend->backend objects messages"""
def __init__(self, raw_message, compressed=False):
errors_logger = logging.getLogger("errors_logger")
message = msgpack.unpackb(raw_message)
try:
self.db_uid = message.pop('DB_UID')
self.command = message.pop('COMMAND')
self.data = message.pop('ARGS')
except KeyError:
errors_logger.exception("Invalid request message : %s" %
message)
raise MessageFormatError("Invalid request message")
class Response(tuple):
"""Handler objects for frontend->backend objects messages"""
def __new__(cls, id, *args, **kwargs):
response = {
'STATUS': kwargs.pop('status', 0),
'DATAS': kwargs.pop('datas', [])
}
response['DATAS'] = cls._format_datas(response['DATAS'])
msg = [id, msgpack.packb(response)]
return tuple.__new__(cls, msg)
@classmethod
def _format_datas(cls, datas):
if datas and not isinstance(datas, (tuple, list)):
datas = [datas]
+ return datas
- return [unicode(d) for d in datas]
- |
c1a1c976642fa1d8f17f89732f6c4fe5bd76d0de | devito/dimension.py | devito/dimension.py | import cgen
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
| import cgen
import numpy as np
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
@property
def dtype(self):
"""The data type of the iteration variable"""
return np.int32
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
| Add dtype of iteration variable | Dimension: Add dtype of iteration variable
| Python | mit | opesci/devito,opesci/devito | import cgen
+
+ import numpy as np
from sympy import Symbol
+
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
+ @property
+ def dtype(self):
+ """The data type of the iteration variable"""
+ return np.int32
+
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
| Add dtype of iteration variable | ## Code Before:
import cgen
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
## Instruction:
Add dtype of iteration variable
## Code After:
import cgen
import numpy as np
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
@property
def dtype(self):
"""The data type of the iteration variable"""
return np.int32
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')
| import cgen
+
+ import numpy as np
from sympy import Symbol
+
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag indicating whether to
buffer variables when iterating this dimension.
"""
def __new__(cls, name, **kwargs):
newobj = Symbol.__new__(cls, name)
newobj.size = kwargs.get('size', None)
newobj.buffered = kwargs.get('buffered', None)
newobj._count = 0
return newobj
def __str__(self):
return self.name
def get_varname(self):
"""Generates a new variables name based on an internal counter"""
name = "%s%d" % (self.name, self._count)
self._count += 1
return name
@property
def ccode(self):
"""C-level variable name of this dimension"""
return "%s_size" % self.name if self.size is None else "%d" % self.size
@property
def decl(self):
"""Variable declaration for C-level kernel headers"""
return cgen.Value("const int", self.ccode)
+ @property
+ def dtype(self):
+ """The data type of the iteration variable"""
+ return np.int32
+
# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p') |
9f1d4788c5f3751b978da97434b5f6c2e22105b5 | django_inbound_email/__init__.py | django_inbound_email/__init__.py | """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = (
"A Django app to make it easy to receive inbound emails from "
"a hosted transactional email service (e.g. SendGrid, Postmark, "
"Mandrill, etc.)."
)
| """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = 'A Django app for receiving inbound emails.'
| Update package description so it displays correctly on PyPI. | Update package description so it displays correctly on PyPI.
The description was wrapping, so it appeared with a single '(' character
on PyPI. I've updated it so that it's now all on a single line.
| Python | mit | yunojuno/django-inbound-email | """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
+ __description__ = 'A Django app for receiving inbound emails.'
- __description__ = (
- "A Django app to make it easy to receive inbound emails from "
- "a hosted transactional email service (e.g. SendGrid, Postmark, "
- "Mandrill, etc.)."
- )
| Update package description so it displays correctly on PyPI. | ## Code Before:
"""An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = (
"A Django app to make it easy to receive inbound emails from "
"a hosted transactional email service (e.g. SendGrid, Postmark, "
"Mandrill, etc.)."
)
## Instruction:
Update package description so it displays correctly on PyPI.
## Code After:
"""An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = 'A Django app for receiving inbound emails.'
| """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
+ __description__ = 'A Django app for receiving inbound emails.'
- __description__ = (
- "A Django app to make it easy to receive inbound emails from "
- "a hosted transactional email service (e.g. SendGrid, Postmark, "
- "Mandrill, etc.)."
- ) |
abd3542113baf801d76c740a2435c69fcda86b42 | src/DecodeTest.py | src/DecodeTest.py | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
if __name__ == '__main__':
unittest.main() | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
"""
"""
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
def test_decoder_decode_send(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost", "msg":"hello queue a"})
msg = "SEND\naccept-version:1.2\nhost:localhost\n\nhello queue a\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
if __name__ == '__main__':
unittest.main() | Send and Connect frame tests | Send and Connect frame tests
| Python | mit | phan91/STOMP_agilis | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
+ """
+ """
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
+ def test_decoder_decode_send(self):
+ testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost", "msg":"hello queue a"})
+ msg = "SEND\naccept-version:1.2\nhost:localhost\n\nhello queue a\x00"
+ self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
+
+
if __name__ == '__main__':
unittest.main() | Send and Connect frame tests | ## Code Before:
import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
if __name__ == '__main__':
unittest.main()
## Instruction:
Send and Connect frame tests
## Code After:
import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
"""
"""
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
def test_decoder_decode_send(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost", "msg":"hello queue a"})
msg = "SEND\naccept-version:1.2\nhost:localhost\n\nhello queue a\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
if __name__ == '__main__':
unittest.main() | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
+ """
+ """
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_invalid_frame_class(self):
command = '---'
self.assertRaises(Exception, self.decoder.get_frame_class, command)
def test_decoder_decode_connect(self):
testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost"})
msg = "CONNECT\naccept-version:1.2\nhost:localhost\n\n\x00"
self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
+ def test_decoder_decode_send(self):
+ testFrame = Frames.CONNECT(**{"accept-version":"1.2", "host":"localhost", "msg":"hello queue a"})
+ msg = "SEND\naccept-version:1.2\nhost:localhost\n\nhello queue a\x00"
+ self.assertEquals(self.decoder.decode(msg).__dict__, testFrame.__dict__)
+
+
if __name__ == '__main__':
unittest.main() |
b103c02815a7819e9cb4f1cc0061202cfcfd0fa6 | bidb/api/views.py | bidb/api/views.py | from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
return HttpResponseBadRequest("{}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
| from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
return HttpResponseBadRequest("Rejecting submission: {}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
| Make it clearer that we are rejecting the submission. | Make it clearer that we are rejecting the submission.
| Python | agpl-3.0 | lamby/buildinfo.debian.net,lamby/buildinfo.debian.net | from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
- return HttpResponseBadRequest("{}\n".format(exc))
+ return HttpResponseBadRequest("Rejecting submission: {}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
| Make it clearer that we are rejecting the submission. | ## Code Before:
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
return HttpResponseBadRequest("{}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
## Instruction:
Make it clearer that we are rejecting the submission.
## Code After:
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
return HttpResponseBadRequest("Rejecting submission: {}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
| from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
- return HttpResponseBadRequest("{}\n".format(exc))
+ return HttpResponseBadRequest("Rejecting submission: {}\n".format(exc))
? ++++++++++++++++++++++
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200) |
9db8a4c37cb226f1606b711493ebec16573f3d46 | polyaxon/libs/spec_validation.py | polyaxon/libs/spec_validation.py | from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
from polyaxon_schemas.polyaxonfile.specification import GroupSpecification
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
if spec.is_local:
raise ValidationError('Received specification content for a local environment run.')
return spec
| from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
from polyaxon_schemas.polyaxonfile.specification import GroupSpecification, Specification
def validate_run_type(spec):
if spec.is_local:
raise ValidationError('Received specification content for a local environment run.')
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
validate_run_type(spec)
return spec
def validate_tensorboard_spec_content(content):
try:
spec = Specification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid tensorboard specification content.')
validate_run_type(spec)
return spec
| Add tensorboard serializer * Add validation * Add tests | Add tensorboard serializer
* Add validation
* Add tests
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
- from polyaxon_schemas.polyaxonfile.specification import GroupSpecification
+ from polyaxon_schemas.polyaxonfile.specification import GroupSpecification, Specification
+
+
+ def validate_run_type(spec):
+ if spec.is_local:
+ raise ValidationError('Received specification content for a local environment run.')
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
+ validate_run_type(spec)
- if spec.is_local:
- raise ValidationError('Received specification content for a local environment run.')
return spec
+
+ def validate_tensorboard_spec_content(content):
+ try:
+ spec = Specification.read(content)
+ except (PolyaxonfileError, PolyaxonConfigurationError):
+ raise ValidationError('Received non valid tensorboard specification content.')
+
+ validate_run_type(spec)
+
+ return spec
+ | Add tensorboard serializer * Add validation * Add tests | ## Code Before:
from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
from polyaxon_schemas.polyaxonfile.specification import GroupSpecification
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
if spec.is_local:
raise ValidationError('Received specification content for a local environment run.')
return spec
## Instruction:
Add tensorboard serializer * Add validation * Add tests
## Code After:
from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
from polyaxon_schemas.polyaxonfile.specification import GroupSpecification, Specification
def validate_run_type(spec):
if spec.is_local:
raise ValidationError('Received specification content for a local environment run.')
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
validate_run_type(spec)
return spec
def validate_tensorboard_spec_content(content):
try:
spec = Specification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid tensorboard specification content.')
validate_run_type(spec)
return spec
| from __future__ import absolute_import, division, print_function
from django.core.exceptions import ValidationError
from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError
- from polyaxon_schemas.polyaxonfile.specification import GroupSpecification
+ from polyaxon_schemas.polyaxonfile.specification import GroupSpecification, Specification
? +++++++++++++++
+
+
+ def validate_run_type(spec):
+ if spec.is_local:
+ raise ValidationError('Received specification content for a local environment run.')
def validate_spec_content(content):
try:
spec = GroupSpecification.read(content)
except (PolyaxonfileError, PolyaxonConfigurationError):
raise ValidationError('Received non valid specification content.')
+ validate_run_type(spec)
- if spec.is_local:
- raise ValidationError('Received specification content for a local environment run.')
return spec
+
+
+ def validate_tensorboard_spec_content(content):
+ try:
+ spec = Specification.read(content)
+ except (PolyaxonfileError, PolyaxonConfigurationError):
+ raise ValidationError('Received non valid tensorboard specification content.')
+
+ validate_run_type(spec)
+
+ return spec |
c45fc698da9783b561cca69363ec4998622e9ac0 | mint/rest/db/capsulemgr.py | mint/rest/db/capsulemgr.py |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sqlite:///%s/database.sqlite" %
capsuleDataDir)
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
|
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.driver
dbConnectString = self.db.db.db.database
cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
| Use the mint database for capsule data | Use the mint database for capsule data
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
- cfg.configLine("store sqlite:///%s/database.sqlite" %
- capsuleDataDir)
+ dbDriver = self.db.db.driver
+ dbConnectString = self.db.db.db.database
+ cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
| Use the mint database for capsule data | ## Code Before:
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sqlite:///%s/database.sqlite" %
capsuleDataDir)
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
## Instruction:
Use the mint database for capsule data
## Code After:
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.driver
dbConnectString = self.db.db.db.database
cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
|
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
- cfg.configLine("store sqlite:///%s/database.sqlite" %
- capsuleDataDir)
+ dbDriver = self.db.db.driver
+ dbConnectString = self.db.db.db.database
+ cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg) |
589e2df8c9af8ce8102904c9cfebbf87ee2df744 | ckanext/orgdashboards/tests/helpers.py | ckanext/orgdashboards/tests/helpers.py | from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data | ''' Helper methods for tests '''
import string
import random
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
''' Create random id which is a combination of letters and numbers '''
return ''.join(random.choice(chars) for _ in range(size)) | Add function for generating random id | Add function for generating random id
| Python | agpl-3.0 | ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards | + ''' Helper methods for tests '''
+
+ import string
+ import random
+
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
+
+ def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
+ ''' Create random id which is a combination of letters and numbers '''
+
+ return ''.join(random.choice(chars) for _ in range(size)) | Add function for generating random id | ## Code Before:
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
## Instruction:
Add function for generating random id
## Code After:
''' Helper methods for tests '''
import string
import random
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
''' Create random id which is a combination of letters and numbers '''
return ''.join(random.choice(chars) for _ in range(size)) | + ''' Helper methods for tests '''
+
+ import string
+ import random
+
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
+
+ def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
+ ''' Create random id which is a combination of letters and numbers '''
+
+ return ''.join(random.choice(chars) for _ in range(size)) |
ac3c0e93adf35015d7f6cfc8c6cf2e6ec45cdeae | server/canonicalization/relationship_mapper.py | server/canonicalization/relationship_mapper.py | """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
@repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| Add LRU for relationship mapper. | [master] Add LRU for relationship mapper.
| Python | mit | hotpxl/canonicalization-server,hotpxl/canonicalization-server | """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
+ import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
+ @repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| Add LRU for relationship mapper. | ## Code Before:
"""Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
## Instruction:
Add LRU for relationship mapper.
## Code After:
"""Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
@repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
+ import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
+ @repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None |
c5671ab2e5115ce9c022a97a088300dc408e2aa4 | opendc/util/path_parser.py | opendc/util/path_parser.py | import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP call to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.split('/')
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
print endpoint_part, part
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None
| import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP endpoint path to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.strip('/').split('/')
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None
| Make path parser robust to trailing / | Make path parser robust to trailing /
| Python | mit | atlarge-research/opendc-web-server,atlarge-research/opendc-web-server | import json
import sys
import re
def parse(version, endpoint_path):
- """Map an HTTP call to an API path"""
+ """Map an HTTP endpoint path to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
- endpoint_path_parts = endpoint_path.split('/')
+ endpoint_path_parts = endpoint_path.strip('/').split('/')
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
- print endpoint_part, part
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None
| Make path parser robust to trailing / | ## Code Before:
import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP call to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.split('/')
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
print endpoint_part, part
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None
## Instruction:
Make path parser robust to trailing /
## Code After:
import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP endpoint path to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.strip('/').split('/')
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None
| import json
import sys
import re
def parse(version, endpoint_path):
- """Map an HTTP call to an API path"""
? ^ ^^
+ """Map an HTTP endpoint path to an API path"""
? ^^^^^^^^^^ ^^
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
- endpoint_path_parts = endpoint_path.split('/')
+ endpoint_path_parts = endpoint_path.strip('/').split('/')
? +++++++++++
paths_parts = [x.split('/') for x in paths if len(x.split('/')) == len(endpoint_path_parts)]
for path_parts in paths_parts:
found = True
for (endpoint_part, part) in zip(endpoint_path_parts, path_parts):
- print endpoint_part, part
if not part.startswith('{') and endpoint_part != part:
found = False
break
if found:
sys.stdout.flush()
return '{}/{}'.format(version, '/'.join(path_parts))
return None |
326e7ba1378b691ad6323c2559686f0c4d97b45f | flowgen/core.py | flowgen/core.py | from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
| from __future__ import print_function
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
| Update py27 compatibility in print function | Update py27 compatibility in print function
| Python | mit | ad-m/flowgen | + from __future__ import print_function
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
| Update py27 compatibility in print function | ## Code Before:
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
## Instruction:
Update py27 compatibility in print function
## Code After:
from __future__ import print_function
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
| + from __future__ import print_function
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name)) |
5fba86c9f9b0d647dc8f821a97a7cc2dbb76deeb | basis_set_exchange/tests/test_aux_sanity.py | basis_set_exchange/tests/test_aux_sanity.py |
import pytest
from .common_testvars import bs_names, bs_metadata
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
r = this_metadata['role']
if r == 'orbital' or r == 'guess':
return
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
for ak, av in aux.items():
if av == basis_name:
assert ak == r
found = True
assert found
|
import pytest
from .common_testvars import bs_names, bs_metadata
from ..misc import transform_basis_name
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
role = this_metadata['role']
if role == 'orbital' or role == 'guess':
return
# All possible names for this auxiliary set
# We only have to match one
all_aux_names = this_metadata["other_names"] + [basis_name]
all_aux_names = [transform_basis_name(x) for x in all_aux_names]
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
for aux_role, aux_name in aux.items():
if aux_name in all_aux_names:
assert aux_role == role
found = True
assert found
| Fix test: Auxiliaries can have multiple names | Fix test: Auxiliaries can have multiple names
| Python | bsd-3-clause | MOLSSI-BSE/basis_set_exchange |
import pytest
from .common_testvars import bs_names, bs_metadata
+ from ..misc import transform_basis_name
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
- r = this_metadata['role']
+ role = this_metadata['role']
- if r == 'orbital' or r == 'guess':
+ if role == 'orbital' or role == 'guess':
return
+
+ # All possible names for this auxiliary set
+ # We only have to match one
+ all_aux_names = this_metadata["other_names"] + [basis_name]
+ all_aux_names = [transform_basis_name(x) for x in all_aux_names]
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
- for ak, av in aux.items():
+ for aux_role, aux_name in aux.items():
- if av == basis_name:
+ if aux_name in all_aux_names:
- assert ak == r
+ assert aux_role == role
found = True
assert found
| Fix test: Auxiliaries can have multiple names | ## Code Before:
import pytest
from .common_testvars import bs_names, bs_metadata
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
r = this_metadata['role']
if r == 'orbital' or r == 'guess':
return
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
for ak, av in aux.items():
if av == basis_name:
assert ak == r
found = True
assert found
## Instruction:
Fix test: Auxiliaries can have multiple names
## Code After:
import pytest
from .common_testvars import bs_names, bs_metadata
from ..misc import transform_basis_name
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
role = this_metadata['role']
if role == 'orbital' or role == 'guess':
return
# All possible names for this auxiliary set
# We only have to match one
all_aux_names = this_metadata["other_names"] + [basis_name]
all_aux_names = [transform_basis_name(x) for x in all_aux_names]
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
for aux_role, aux_name in aux.items():
if aux_name in all_aux_names:
assert aux_role == role
found = True
assert found
|
import pytest
from .common_testvars import bs_names, bs_metadata
+ from ..misc import transform_basis_name
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_sanity(basis_name):
"""For all basis sets, check that
1. All aux basis sets exist
2. That the role of the aux basis set matches the role in
the orbital basis
"""
this_metadata = bs_metadata[basis_name]
for role, aux in this_metadata['auxiliaries'].items():
assert aux in bs_metadata
aux_metadata = bs_metadata[aux]
assert role == aux_metadata['role']
@pytest.mark.parametrize('basis_name', bs_names)
def test_aux_reverse(basis_name):
"""Make sure all aux basis sets are paired with at least one orbital basis set
"""
this_metadata = bs_metadata[basis_name]
- r = this_metadata['role']
+ role = this_metadata['role']
? +++
- if r == 'orbital' or r == 'guess':
+ if role == 'orbital' or role == 'guess':
? +++ +++
return
+
+ # All possible names for this auxiliary set
+ # We only have to match one
+ all_aux_names = this_metadata["other_names"] + [basis_name]
+ all_aux_names = [transform_basis_name(x) for x in all_aux_names]
# Find where this basis set is listed as an auxiliary
found = False
for k, v in bs_metadata.items():
aux = v['auxiliaries']
- for ak, av in aux.items():
? ^ ^
+ for aux_role, aux_name in aux.items():
? ^^^^^^^ ^^^^^^^
- if av == basis_name:
+ if aux_name in all_aux_names:
- assert ak == r
? ^
+ assert aux_role == role
? ^^^^^^^ +++
found = True
assert found |
09851ff2903db29703616da0fbc9ec003955712a | zerver/lib/markdown/preprocessor_priorities.py | zerver/lib/markdown/preprocessor_priorities.py | PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
"help_relative_links": 475,
"setting": 450,
"fenced_code_block": 25,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
}
| PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
# "include_wrapper": 500,
"help_relative_links": 475,
"setting": 450,
# "normalize_whitespace": 30,
"fenced_code_block": 25,
# "html_block": 20,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
}
| Document built-in preprocessor priorities for convenience. | markdown: Document built-in preprocessor priorities for convenience.
Fixes #19810
| Python | apache-2.0 | eeshangarg/zulip,rht/zulip,rht/zulip,kou/zulip,eeshangarg/zulip,rht/zulip,eeshangarg/zulip,zulip/zulip,rht/zulip,andersk/zulip,kou/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip,andersk/zulip,kou/zulip,andersk/zulip,rht/zulip,rht/zulip,zulip/zulip,kou/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,andersk/zulip,kou/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,zulip/zulip | PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
+ # "include_wrapper": 500,
"help_relative_links": 475,
"setting": 450,
+ # "normalize_whitespace": 30,
"fenced_code_block": 25,
+ # "html_block": 20,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
}
| Document built-in preprocessor priorities for convenience. | ## Code Before:
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
"help_relative_links": 475,
"setting": 450,
"fenced_code_block": 25,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
}
## Instruction:
Document built-in preprocessor priorities for convenience.
## Code After:
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
# "include_wrapper": 500,
"help_relative_links": 475,
"setting": 450,
# "normalize_whitespace": 30,
"fenced_code_block": 25,
# "html_block": 20,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
}
| PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531,
"generate_api_description": 530,
"generate_code_example": 525,
"generate_return_values": 510,
"generate_api_arguments": 505,
"include": 500,
+ # "include_wrapper": 500,
"help_relative_links": 475,
"setting": 450,
+ # "normalize_whitespace": 30,
"fenced_code_block": 25,
+ # "html_block": 20,
"tabbed_sections": -500,
"nested_code_blocks": -500,
"emoticon_translations": -505,
} |
bcc79588e5e49c928210d6830fbe1a7386fcf5bb | apps/search/tasks.py | apps/search/tasks.py | import logging
from django.conf import settings
from django.db.models.signals import pre_delete
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls
| import logging
import warnings
from django.conf import settings
from django.db.models.signals import pre_delete
# ignore a deprecation warning from elasticutils until the fix is released
# refs https://github.com/mozilla/elasticutils/pull/160
warnings.filterwarnings("ignore",
category=DeprecationWarning,
module='celery.decorators')
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls
| Stop a deprecation warning that is thrown in elasticutils. | Stop a deprecation warning that is thrown in elasticutils.
This is not going to be needed once https://github.com/mozilla/elasticutils/pull/160
has been released.
| Python | mpl-2.0 | jezdez/kuma,whip112/Whip112,FrankBian/kuma,YOTOV-LIMITED/kuma,SphinxKnight/kuma,jgmize/kuma,RanadeepPolavarapu/kuma,ollie314/kuma,nhenezi/kuma,FrankBian/kuma,surajssd/kuma,YOTOV-LIMITED/kuma,yfdyh000/kuma,cindyyu/kuma,SphinxKnight/kuma,openjck/kuma,MenZil/kuma,RanadeepPolavarapu/kuma,yfdyh000/kuma,whip112/Whip112,carnell69/kuma,YOTOV-LIMITED/kuma,ollie314/kuma,RanadeepPolavarapu/kuma,SphinxKnight/kuma,surajssd/kuma,safwanrahman/kuma,utkbansal/kuma,groovecoder/kuma,chirilo/kuma,openjck/kuma,cindyyu/kuma,ronakkhunt/kuma,safwanrahman/kuma,robhudson/kuma,Elchi3/kuma,Elchi3/kuma,biswajitsahu/kuma,robhudson/kuma,yfdyh000/kuma,robhudson/kuma,biswajitsahu/kuma,hoosteeno/kuma,chirilo/kuma,groovecoder/kuma,scrollback/kuma,ronakkhunt/kuma,Elchi3/kuma,davehunt/kuma,ollie314/kuma,jwhitlock/kuma,tximikel/kuma,Elchi3/kuma,carnell69/kuma,hoosteeno/kuma,utkbansal/kuma,davehunt/kuma,anaran/kuma,mastizada/kuma,carnell69/kuma,bluemini/kuma,jwhitlock/kuma,SphinxKnight/kuma,scrollback/kuma,jgmize/kuma,chirilo/kuma,cindyyu/kuma,biswajitsahu/kuma,mozilla/kuma,a2sheppy/kuma,a2sheppy/kuma,nhenezi/kuma,MenZil/kuma,ollie314/kuma,tximikel/kuma,davidyezsetz/kuma,a2sheppy/kuma,surajssd/kuma,davehunt/kuma,yfdyh000/kuma,biswajitsahu/kuma,darkwing/kuma,RanadeepPolavarapu/kuma,tximikel/kuma,jezdez/kuma,bluemini/kuma,whip112/Whip112,surajssd/kuma,nhenezi/kuma,mozilla/kuma,openjck/kuma,nhenezi/kuma,davidyezsetz/kuma,darkwing/kuma,carnell69/kuma,scrollback/kuma,MenZil/kuma,MenZil/kuma,jgmize/kuma,varunkamra/kuma,darkwing/kuma,hoosteeno/kuma,cindyyu/kuma,groovecoder/kuma,YOTOV-LIMITED/kuma,darkwing/kuma,openjck/kuma,groovecoder/kuma,robhudson/kuma,openjck/kuma,ollie314/kuma,utkbansal/kuma,davehunt/kuma,escattone/kuma,groovecoder/kuma,bluemini/kuma,ronakkhunt/kuma,ollie314/kuma,jgmize/kuma,surajssd/kuma,a2sheppy/kuma,hoosteeno/kuma,jezdez/kuma,YOTOV-LIMITED/kuma,jwhitlock/kuma,utkbansal/kuma,a2sheppy/kuma,cindyyu/kuma,varunkamra/kuma,jwhitlock/kuma,jezdez/kuma,varunkamra/kuma,carnell69/kuma,carnell69/kuma,mozilla/kuma,biswajitsahu/kuma,anaran/kuma,yfdyh000/kuma,YOTOV-LIMITED/kuma,escattone/kuma,scrollback/kuma,varunkamra/kuma,utkbansal/kuma,RanadeepPolavarapu/kuma,MenZil/kuma,SphinxKnight/kuma,nhenezi/kuma,davehunt/kuma,whip112/Whip112,hoosteeno/kuma,chirilo/kuma,biswajitsahu/kuma,mastizada/kuma,safwanrahman/kuma,davidyezsetz/kuma,anaran/kuma,Elchi3/kuma,bluemini/kuma,whip112/Whip112,FrankBian/kuma,utkbansal/kuma,varunkamra/kuma,safwanrahman/kuma,ronakkhunt/kuma,tximikel/kuma,ronakkhunt/kuma,davehunt/kuma,tximikel/kuma,anaran/kuma,chirilo/kuma,darkwing/kuma,openjck/kuma,FrankBian/kuma,mastizada/kuma,anaran/kuma,varunkamra/kuma,groovecoder/kuma,davidyezsetz/kuma,SphinxKnight/kuma,bluemini/kuma,anaran/kuma,ronakkhunt/kuma,robhudson/kuma,MenZil/kuma,jezdez/kuma,bluemini/kuma,mozilla/kuma,chirilo/kuma,yfdyh000/kuma,scrollback/kuma,cindyyu/kuma,jgmize/kuma,safwanrahman/kuma,safwanrahman/kuma,whip112/Whip112,darkwing/kuma,jwhitlock/kuma,FrankBian/kuma,jgmize/kuma,davidyezsetz/kuma,RanadeepPolavarapu/kuma,hoosteeno/kuma,mastizada/kuma,surajssd/kuma,mozilla/kuma,escattone/kuma,robhudson/kuma,tximikel/kuma,jezdez/kuma | import logging
+ import warnings
from django.conf import settings
from django.db.models.signals import pre_delete
+
+ # ignore a deprecation warning from elasticutils until the fix is released
+ # refs https://github.com/mozilla/elasticutils/pull/160
+ warnings.filterwarnings("ignore",
+ category=DeprecationWarning,
+ module='celery.decorators')
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls
| Stop a deprecation warning that is thrown in elasticutils. | ## Code Before:
import logging
from django.conf import settings
from django.db.models.signals import pre_delete
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls
## Instruction:
Stop a deprecation warning that is thrown in elasticutils.
## Code After:
import logging
import warnings
from django.conf import settings
from django.db.models.signals import pre_delete
# ignore a deprecation warning from elasticutils until the fix is released
# refs https://github.com/mozilla/elasticutils/pull/160
warnings.filterwarnings("ignore",
category=DeprecationWarning,
module='celery.decorators')
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls
| import logging
+ import warnings
from django.conf import settings
from django.db.models.signals import pre_delete
+
+ # ignore a deprecation warning from elasticutils until the fix is released
+ # refs https://github.com/mozilla/elasticutils/pull/160
+ warnings.filterwarnings("ignore",
+ category=DeprecationWarning,
+ module='celery.decorators')
from elasticutils.contrib.django.tasks import index_objects, unindex_objects
from wiki.signals import render_done
def render_done_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
try:
index_objects.delay(instance.get_mapping_type(), [instance.id])
except:
logging.error('Search indexing task failed',
exc_info=True)
def pre_delete_handler(**kwargs):
if not settings.ES_LIVE_INDEX or 'instance' not in kwargs:
return
instance = kwargs['instance']
unindex_objects.delay(instance.get_mapping_type(), [instance.id])
def register_live_index(model_cls):
"""Register a model and index for auto indexing."""
uid = str(model_cls) + 'live_indexing'
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
# Enable this to be used as decorator.
return model_cls |
dc60ed6efdd4eb9a78e29623acee7505f2d864e6 | Lib/test/test_fork1.py | Lib/test/test_fork1.py |
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(4):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(4)
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
pid = os.getpid()
for key in alive.keys():
if alive[key] == pid:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
|
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| Use a constant to specify the number of child threads to create. | Use a constant to specify the number of child threads to create.
Instead of assuming that the number process ids of the threads is the
same as the process id of the controlling process, use a copy of the
dictionary and check for changes in the process ids of the threads
from the thread's process ids in the parent process. This makes the
test make more sense on systems which assign a new pid to each thread
(i.e., Linux).
This doesn't fix the other problems evident with this test on Linux.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
+
+ NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
- for i in range(4):
+ for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
- assert a == range(4)
+ assert a == range(NUM_THREADS)
+
+ prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
- pid = os.getpid()
for key in alive.keys():
- if alive[key] == pid:
+ if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| Use a constant to specify the number of child threads to create. | ## Code Before:
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(4):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(4)
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
pid = os.getpid()
for key in alive.keys():
if alive[key] == pid:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
## Instruction:
Use a constant to specify the number of child threads to create.
## Code After:
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
|
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
+
+ NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
- for i in range(4):
? ^
+ for i in range(NUM_THREADS):
? ^^^^^^^^^^^
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
- assert a == range(4)
? ^
+ assert a == range(NUM_THREADS)
? ^^^^^^^^^^^
+
+ prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
- pid = os.getpid()
for key in alive.keys():
- if alive[key] == pid:
? ^ ^
+ if alive[key] != prefork_lives[key]:
? ^ ++++++++ ^^^^^^^^
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main() |
a3a5d2d6b76a4e903fea232b746b2df8b208ec9e | km3pipe/tests/test_plot.py | km3pipe/tests/test_plot.py |
import numpy as np
from km3pipe.testing import TestCase
from km3pipe.plot import bincenters
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
|
import numpy as np
from km3pipe.testing import TestCase, patch
from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
class TestMeshStuff(TestCase):
def test_meshgrid(self):
xx, yy = meshgrid(-1, 1, 0.8)
assert np.allclose([[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6]], xx)
assert np.allclose([[-1.0, -1.0, -1.0],
[-0.2, -0.2, -0.2],
[0.6, 0.6, 0.6]], yy)
def test_meshgrid_with_y_specs(self):
xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8)
assert np.allclose([[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6]], xx)
assert np.allclose([[-10, -10, -10],
[-2, -2, -2],
[6, 6, 6]], yy)
class TestDiag(TestCase):
def test_call(self):
diag()
| Add tests for plot functions | Add tests for plot functions
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe |
import numpy as np
- from km3pipe.testing import TestCase
+ from km3pipe.testing import TestCase, patch
- from km3pipe.plot import bincenters
+ from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
+
+ class TestMeshStuff(TestCase):
+ def test_meshgrid(self):
+ xx, yy = meshgrid(-1, 1, 0.8)
+ assert np.allclose([[-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6]], xx)
+ assert np.allclose([[-1.0, -1.0, -1.0],
+ [-0.2, -0.2, -0.2],
+ [0.6, 0.6, 0.6]], yy)
+
+ def test_meshgrid_with_y_specs(self):
+ xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8)
+ assert np.allclose([[-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6]], xx)
+ assert np.allclose([[-10, -10, -10],
+ [-2, -2, -2],
+ [6, 6, 6]], yy)
+
+
+ class TestDiag(TestCase):
+ def test_call(self):
+ diag()
+ | Add tests for plot functions | ## Code Before:
import numpy as np
from km3pipe.testing import TestCase
from km3pipe.plot import bincenters
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
## Instruction:
Add tests for plot functions
## Code After:
import numpy as np
from km3pipe.testing import TestCase, patch
from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
class TestMeshStuff(TestCase):
def test_meshgrid(self):
xx, yy = meshgrid(-1, 1, 0.8)
assert np.allclose([[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6]], xx)
assert np.allclose([[-1.0, -1.0, -1.0],
[-0.2, -0.2, -0.2],
[0.6, 0.6, 0.6]], yy)
def test_meshgrid_with_y_specs(self):
xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8)
assert np.allclose([[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6],
[-1.0, -0.2, 0.6]], xx)
assert np.allclose([[-10, -10, -10],
[-2, -2, -2],
[6, 6, 6]], yy)
class TestDiag(TestCase):
def test_call(self):
diag()
|
import numpy as np
- from km3pipe.testing import TestCase
+ from km3pipe.testing import TestCase, patch
? +++++++
- from km3pipe.plot import bincenters
+ from km3pipe.plot import bincenters, meshgrid, automeshgrid, diag
__author__ = "Moritz Lotze"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Moritz Lotze"
__email__ = "mlotze@km3net.de"
__status__ = "Development"
class TestBins(TestCase):
def test_binlims(self):
bins = np.linspace(0, 20, 21)
assert bincenters(bins).shape[0] == bins.shape[0] - 1
+
+
+ class TestMeshStuff(TestCase):
+ def test_meshgrid(self):
+ xx, yy = meshgrid(-1, 1, 0.8)
+ assert np.allclose([[-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6]], xx)
+ assert np.allclose([[-1.0, -1.0, -1.0],
+ [-0.2, -0.2, -0.2],
+ [0.6, 0.6, 0.6]], yy)
+
+ def test_meshgrid_with_y_specs(self):
+ xx, yy = meshgrid(-1, 1, 0.8, -10, 10, 8)
+ assert np.allclose([[-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6],
+ [-1.0, -0.2, 0.6]], xx)
+ assert np.allclose([[-10, -10, -10],
+ [-2, -2, -2],
+ [6, 6, 6]], yy)
+
+
+ class TestDiag(TestCase):
+ def test_call(self):
+ diag() |
98f7c1080765e00954d0c38a98ab1bb3e207c059 | podcoder.py | podcoder.py |
from podpublish import configuration
from podpublish import encoder
from podpublish import uploader
def main():
config = configuration.Configuration('podcoder.ini')
encoder.audio_encode(config, 'mp3')
encoder.mp3_tag(config)
encoder.mp3_coverart(config)
encoder.audio_encode(config, 'ogg')
encoder.ogg_tag(config)
encoder.ogg_coverart(config)
encoder.png_header(config)
encoder.png_poster(config)
encoder.mkv_encode(config)
uploader.youtube_upload(config)
if __name__ == '__main__':
main()
|
from podpublish import configuration
from podpublish import encoder
def main():
config = configuration.Configuration('podcoder.ini')
if not config.mp3['skip']:
encoder.audio_encode(config, 'mp3')
encoder.mp3_tag(config)
encoder.mp3_coverart(config)
if not config.ogg['skip']:
encoder.audio_encode(config, 'ogg')
encoder.ogg_tag(config)
encoder.ogg_coverart(config)
if not config.youtube['skip']:
encoder.png_header(config)
encoder.png_poster(config)
encoder.mkv_encode(config)
if __name__ == '__main__':
main()
| Determine what to encode based in skip options. | Determine what to encode based in skip options.
| Python | lgpl-2.1 | rikai/podpublish |
from podpublish import configuration
from podpublish import encoder
- from podpublish import uploader
def main():
config = configuration.Configuration('podcoder.ini')
+ if not config.mp3['skip']:
- encoder.audio_encode(config, 'mp3')
+ encoder.audio_encode(config, 'mp3')
- encoder.mp3_tag(config)
+ encoder.mp3_tag(config)
- encoder.mp3_coverart(config)
+ encoder.mp3_coverart(config)
+
+ if not config.ogg['skip']:
- encoder.audio_encode(config, 'ogg')
+ encoder.audio_encode(config, 'ogg')
- encoder.ogg_tag(config)
+ encoder.ogg_tag(config)
- encoder.ogg_coverart(config)
+ encoder.ogg_coverart(config)
+
+ if not config.youtube['skip']:
- encoder.png_header(config)
+ encoder.png_header(config)
- encoder.png_poster(config)
+ encoder.png_poster(config)
- encoder.mkv_encode(config)
+ encoder.mkv_encode(config)
- uploader.youtube_upload(config)
if __name__ == '__main__':
main()
| Determine what to encode based in skip options. | ## Code Before:
from podpublish import configuration
from podpublish import encoder
from podpublish import uploader
def main():
config = configuration.Configuration('podcoder.ini')
encoder.audio_encode(config, 'mp3')
encoder.mp3_tag(config)
encoder.mp3_coverart(config)
encoder.audio_encode(config, 'ogg')
encoder.ogg_tag(config)
encoder.ogg_coverart(config)
encoder.png_header(config)
encoder.png_poster(config)
encoder.mkv_encode(config)
uploader.youtube_upload(config)
if __name__ == '__main__':
main()
## Instruction:
Determine what to encode based in skip options.
## Code After:
from podpublish import configuration
from podpublish import encoder
def main():
config = configuration.Configuration('podcoder.ini')
if not config.mp3['skip']:
encoder.audio_encode(config, 'mp3')
encoder.mp3_tag(config)
encoder.mp3_coverart(config)
if not config.ogg['skip']:
encoder.audio_encode(config, 'ogg')
encoder.ogg_tag(config)
encoder.ogg_coverart(config)
if not config.youtube['skip']:
encoder.png_header(config)
encoder.png_poster(config)
encoder.mkv_encode(config)
if __name__ == '__main__':
main()
|
from podpublish import configuration
from podpublish import encoder
- from podpublish import uploader
def main():
config = configuration.Configuration('podcoder.ini')
+ if not config.mp3['skip']:
- encoder.audio_encode(config, 'mp3')
+ encoder.audio_encode(config, 'mp3')
? ++++
- encoder.mp3_tag(config)
+ encoder.mp3_tag(config)
? ++++
- encoder.mp3_coverart(config)
+ encoder.mp3_coverart(config)
? ++++
+
+ if not config.ogg['skip']:
- encoder.audio_encode(config, 'ogg')
+ encoder.audio_encode(config, 'ogg')
? ++++
- encoder.ogg_tag(config)
+ encoder.ogg_tag(config)
? ++++
- encoder.ogg_coverart(config)
+ encoder.ogg_coverart(config)
? ++++
+
+ if not config.youtube['skip']:
- encoder.png_header(config)
+ encoder.png_header(config)
? ++++
- encoder.png_poster(config)
+ encoder.png_poster(config)
? ++++
- encoder.mkv_encode(config)
+ encoder.mkv_encode(config)
? ++++
- uploader.youtube_upload(config)
if __name__ == '__main__':
main() |
eaec82bb0a4a11f683c34550bdc23b3c6b0c48d2 | examples/M1/M1_export.py | examples/M1/M1_export.py | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExport(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1') # create and export network to NeuroML 2 | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1',
connections=True,
stimulations=True) # create and export network to NeuroML 2 | Update script to export to nml2 of m1 | Update script to export to nml2 of m1
| Python | mit | Neurosim-lab/netpyne,thekerrlab/netpyne,Neurosim-lab/netpyne | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
- sim.createAndExport(netParams = M1.netParams,
+ sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
+ reference = 'M1',
+ connections=True,
- reference = 'M1') # create and export network to NeuroML 2
+ stimulations=True) # create and export network to NeuroML 2 | Update script to export to nml2 of m1 | ## Code Before:
import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExport(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1') # create and export network to NeuroML 2
## Instruction:
Update script to export to nml2 of m1
## Code After:
import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1',
connections=True,
stimulations=True) # create and export network to NeuroML 2 | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
- sim.createAndExport(netParams = M1.netParams,
+ sim.createAndExportNeuroML2(netParams = M1.netParams,
? ++++++++
simConfig = M1.simConfig,
+ reference = 'M1',
+ connections=True,
- reference = 'M1') # create and export network to NeuroML 2
? --------------
+ stimulations=True) # create and export network to NeuroML 2
? ++++++++++++++ +
|
2263ea4ec0322e09db92ae368aa219c4e34125d3 | src/foremast/__init__.py | src/foremast/__init__.py | """Tools for creating infrastructure and Spinnaker Applications."""
| """Tools for creating infrastructure and Spinnaker Applications."""
from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils,
consts, destroyer, exceptions, runner)
| Bring modules into package level | fix: Bring modules into package level
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | """Tools for creating infrastructure and Spinnaker Applications."""
+ from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils,
+ consts, destroyer, exceptions, runner)
| Bring modules into package level | ## Code Before:
"""Tools for creating infrastructure and Spinnaker Applications."""
## Instruction:
Bring modules into package level
## Code After:
"""Tools for creating infrastructure and Spinnaker Applications."""
from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils,
consts, destroyer, exceptions, runner)
| """Tools for creating infrastructure and Spinnaker Applications."""
+ from . import (app, configs, dns, elb, iam, pipeline, s3, securitygroup, utils,
+ consts, destroyer, exceptions, runner) |
a25d7cbe7a2fb583e08e642e846edd7d647f2013 | tests/test_engine_import.py | tests/test_engine_import.py | import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
'openfoam',
'kratos',
'jyulb']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine))
| import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
'openfoam_file_io',
'openfoam_internal',
'kratos',
'jyulb_fileio_isothermal',
'jyulb_internal_isothermal']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine))
| Fix engine extension names for jyulb and openfoam | Fix engine extension names for jyulb and openfoam
| Python | bsd-2-clause | simphony/simphony-framework | import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
- 'openfoam',
+ 'openfoam_file_io',
+ 'openfoam_internal',
'kratos',
- 'jyulb']
+ 'jyulb_fileio_isothermal',
+ 'jyulb_internal_isothermal']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine))
| Fix engine extension names for jyulb and openfoam | ## Code Before:
import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
'openfoam',
'kratos',
'jyulb']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine))
## Instruction:
Fix engine extension names for jyulb and openfoam
## Code After:
import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
'openfoam_file_io',
'openfoam_internal',
'kratos',
'jyulb_fileio_isothermal',
'jyulb_internal_isothermal']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine))
| import unittest
import os
from stevedore.extension import ExtensionManager
ENGINES = [
'lammps',
- 'openfoam',
+ 'openfoam_file_io',
? ++++++++
+ 'openfoam_internal',
'kratos',
- 'jyulb']
+ 'jyulb_fileio_isothermal',
+ 'jyulb_internal_isothermal']
if os.getenv("HAVE_NUMERRIN", "no") == "yes":
ENGINES.append("numerrin")
class TestEngineImport(unittest.TestCase):
def test_engine_import(self):
extension_manager = ExtensionManager(namespace='simphony.engine')
for engine in ENGINES:
if engine not in extension_manager:
self.fail("`{}` could not be imported".format(engine)) |
2c1ffd6abed12de8878ec60021ae16dc9c011975 | auth0/v2/authentication/link.py | auth0/v2/authentication/link.py | from .base import AuthenticationBase
class Link(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
)
| from .base import AuthenticationBase
class Link(AuthenticationBase):
"""Link accounts endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
"""Unlink an account.
"""
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
)
| Add docstrings in Link class | Add docstrings in Link class
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .base import AuthenticationBase
class Link(AuthenticationBase):
+ """Link accounts endpoints.
+
+ Args:
+ domain (str): Your auth0 domain (e.g: username.auth0.com)
+ """
+
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
+ """Unlink an account.
+ """
+
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
)
| Add docstrings in Link class | ## Code Before:
from .base import AuthenticationBase
class Link(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
)
## Instruction:
Add docstrings in Link class
## Code After:
from .base import AuthenticationBase
class Link(AuthenticationBase):
"""Link accounts endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
"""Unlink an account.
"""
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
)
| from .base import AuthenticationBase
class Link(AuthenticationBase):
+ """Link accounts endpoints.
+
+ Args:
+ domain (str): Your auth0 domain (e.g: username.auth0.com)
+ """
+
def __init__(self, domain):
self.domain = domain
def unlink(self, access_token, user_id):
+ """Unlink an account.
+ """
+
return self.post(
url='https://%s/unlink' % self.domain,
data={
'access_token': access_token,
'user_id': user_id,
},
headers={'Content-Type': 'application/json'}
) |
bb8f1d915785fbcbbd8ccd99436a63a449d26e88 | patterns.py | patterns.py | import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
]
| import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
(
# r"""
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
# """,
# r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
r'\b(\d{1,3}\.){3}\d{1,3}\b',
r'IP_ADDRESS_SUBSTITUTE',
),
(
r'js:\d+:\d+',
r'js:POSITION_SUBSTITUTE',
),
]
| Add js error position SUBSTITUTE | Add js error position SUBSTITUTE
| Python | mit | abcdw/direlog,abcdw/direlog | import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
+ (
+ # r"""
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
+ # """,
+ # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
+ r'\b(\d{1,3}\.){3}\d{1,3}\b',
+ r'IP_ADDRESS_SUBSTITUTE',
+ ),
+ (
+ r'js:\d+:\d+',
+ r'js:POSITION_SUBSTITUTE',
+ ),
]
| Add js error position SUBSTITUTE | ## Code Before:
import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
]
## Instruction:
Add js error position SUBSTITUTE
## Code After:
import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
(
# r"""
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
# (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
# """,
# r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
r'\b(\d{1,3}\.){3}\d{1,3}\b',
r'IP_ADDRESS_SUBSTITUTE',
),
(
r'js:\d+:\d+',
r'js:POSITION_SUBSTITUTE',
),
]
| import re
pre_patterns = [
(
r'(\d{16}-[-\w]*\b)',
r'REQUEST_ID_SUBSTITUTE',
),
(
# r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}',
r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}',
# r'[0-9A-F-]{36}',
# r'ACE088EB-ECA6-4348-905A-041EF10DBD53',
r'UUID_SUBSTITUTE',
),
+ (
+ # r"""
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
+ # (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
+ # """,
+ # r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
+ r'\b(\d{1,3}\.){3}\d{1,3}\b',
+ r'IP_ADDRESS_SUBSTITUTE',
+ ),
+ (
+ r'js:\d+:\d+',
+ r'js:POSITION_SUBSTITUTE',
+ ),
] |
e7865a22eb2e7433f3c36cd571aae3ac65436423 | signage/models.py | signage/models.py | from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).distinct()
| from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).order_by('weight').distinct()
| Order displayed slides by weight | Order displayed slides by weight
| Python | bsd-3-clause | jbittel/django-signage,jbittel/django-signage,jbittel/django-signage | from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
- return Slide.objects.filter(tags__name__in=self.tags.names()).distinct()
+ return Slide.objects.filter(tags__name__in=self.tags.names()).order_by('weight').distinct()
| Order displayed slides by weight | ## Code Before:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).distinct()
## Instruction:
Order displayed slides by weight
## Code After:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).order_by('weight').distinct()
| from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
"""
"""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
- return Slide.objects.filter(tags__name__in=self.tags.names()).distinct()
+ return Slide.objects.filter(tags__name__in=self.tags.names()).order_by('weight').distinct()
? +++++++++++++++++++
|
bc92988baee2186fe5b746751fb5d2e3ec6cb8d9 | statzlogger.py | statzlogger.py | import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def emit(self, record):
pass
class Collection(StatzHandler):
def __init__(self, level=logging.NOTSET):
StatzHandler.__init__(self, level)
self.indices = {}
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass
| import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level)
self.indices = {}
def emit(self, record):
pass
class Collection(StatzHandler):
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass
| Index creation should apply across the board. | Index creation should apply across the board.
| Python | isc | whilp/statzlogger | import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
+ def __init__(self, level=logging.NOTSET):
+ logging.Handler.__init__(self, level)
+ self.indices = {}
+
def emit(self, record):
pass
class Collection(StatzHandler):
-
- def __init__(self, level=logging.NOTSET):
- StatzHandler.__init__(self, level)
- self.indices = {}
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass
| Index creation should apply across the board. | ## Code Before:
import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def emit(self, record):
pass
class Collection(StatzHandler):
def __init__(self, level=logging.NOTSET):
StatzHandler.__init__(self, level)
self.indices = {}
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass
## Instruction:
Index creation should apply across the board.
## Code After:
import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
logging.Handler.__init__(self, level)
self.indices = {}
def emit(self, record):
pass
class Collection(StatzHandler):
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass
| import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
+ def __init__(self, level=logging.NOTSET):
+ logging.Handler.__init__(self, level)
+ self.indices = {}
+
def emit(self, record):
pass
class Collection(StatzHandler):
-
- def __init__(self, level=logging.NOTSET):
- StatzHandler.__init__(self, level)
- self.indices = {}
def emit(self, record):
indices = getattr(record, "indices", [])
indices.append(getattr(record, "index", None))
for index in indices:
self.indices.setdefault(index, []).append(record)
class Sum(StatzHandler):
pass
class Top(StatzHandler):
pass |
a154611449f1f5a485ac0e12a9feb9e28e342331 | server/pypi/packages/grpcio/test/__init__.py | server/pypi/packages/grpcio/test/__init__.py | from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
self.server.add_insecure_port('[::]:50051')
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0)
| from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
self.port = self.server.add_insecure_port('localhost:0')
self.assertTrue(self.port)
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
channel = grpc.insecure_channel('localhost:{}'.format(self.port))
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0)
| Fix hardcoded port number in grpcio test | Fix hardcoded port number in grpcio test
| Python | mit | chaquo/chaquopy,chaquo/chaquopy,chaquo/chaquopy,chaquo/chaquopy,chaquo/chaquopy | from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
- self.server.add_insecure_port('[::]:50051')
+ self.port = self.server.add_insecure_port('localhost:0')
+ self.assertTrue(self.port)
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
- channel = grpc.insecure_channel('localhost:50051')
+ channel = grpc.insecure_channel('localhost:{}'.format(self.port))
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0)
| Fix hardcoded port number in grpcio test | ## Code Before:
from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
self.server.add_insecure_port('[::]:50051')
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0)
## Instruction:
Fix hardcoded port number in grpcio test
## Code After:
from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
self.port = self.server.add_insecure_port('localhost:0')
self.assertTrue(self.port)
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
channel = grpc.insecure_channel('localhost:{}'.format(self.port))
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0)
| from __future__ import absolute_import, division, print_function
import unittest
# Adapted from https://github.com/grpc/grpc/blob/master/examples/python/helloworld.
class TestGrpcio(unittest.TestCase):
def setUp(self):
from concurrent import futures
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), self.server)
- self.server.add_insecure_port('[::]:50051')
+ self.port = self.server.add_insecure_port('localhost:0')
+ self.assertTrue(self.port)
self.server.start()
def test_greeter(self):
import grpc
from . import helloworld_pb2, helloworld_pb2_grpc
- channel = grpc.insecure_channel('localhost:50051')
? ^^^^^
+ channel = grpc.insecure_channel('localhost:{}'.format(self.port))
? ^^ +++++++++++++++++ +
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='world'))
self.assertEqual("Hello, world!", response.message)
def tearDown(self):
self.server.stop(0) |
38de795103748ca757a03a62da8ef3d89b0bf682 | GoProController/models.py | GoProController/models.py | from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
value = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command
| from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
value = models.CharField(blank=True, max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command
| Fix bug that prevent commands with no values from being added | Fix bug that prevent commands with no values from being added
| Python | apache-2.0 | Nzaga/GoProController,joshvillbrandt/GoProController,Nzaga/GoProController,joshvillbrandt/GoProController | from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
- value = models.CharField(max_length=255)
+ value = models.CharField(blank=True, max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command
| Fix bug that prevent commands with no values from being added | ## Code Before:
from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
value = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command
## Instruction:
Fix bug that prevent commands with no values from being added
## Code After:
from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
value = models.CharField(blank=True, max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command
| from django.db import models
class Camera(models.Model):
ssid = models.CharField(max_length=255)
password = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_attempt = models.DateTimeField(auto_now=True)
last_update = models.DateTimeField(null=True, blank=True)
image_last_update = models.DateTimeField(null=True, blank=True)
image = models.TextField(blank=True)
summary = models.TextField(blank=True)
status = models.TextField(blank=True)
connection_attempts = models.IntegerField(default=0)
connection_failures = models.IntegerField(default=0)
def __unicode__(self):
return self.ssid
class Command(models.Model):
camera = models.ForeignKey(Camera)
command = models.CharField(max_length=255)
- value = models.CharField(max_length=255)
+ value = models.CharField(blank=True, max_length=255)
? ++++++++++++
date_added = models.DateTimeField(auto_now_add=True)
time_completed = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return self.camera.__unicode__() + ' > ' + self.command |
448f1201a36de8ef41dadbb63cbea874dd7d5878 | wechatpy/utils.py | wechatpy/utils.py | from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
tmpstr = six.binary_type(tmpstr)
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature
| from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
tmpstr = six.text_type(tmpstr).encode('utf-8')
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature
| Fix test error on Python 3 | Fix test error on Python 3
| Python | mit | cloverstd/wechatpy,wechatpy/wechatpy,EaseCloud/wechatpy,mruse/wechatpy,cysnake4713/wechatpy,cysnake4713/wechatpy,zhaoqz/wechatpy,navcat/wechatpy,zaihui/wechatpy,Luckyseal/wechatpy,messense/wechatpy,chenjiancan/wechatpy,chenjiancan/wechatpy,Luckyseal/wechatpy,tdautc19841202/wechatpy,navcat/wechatpy,Dufy/wechatpy,jxtech/wechatpy,Luckyseal/wechatpy,tdautc19841202/wechatpy,hunter007/wechatpy,mruse/wechatpy,EaseCloud/wechatpy,tdautc19841202/wechatpy,hunter007/wechatpy,cloverstd/wechatpy,Dufy/wechatpy,zaihui/wechatpy,zhaoqz/wechatpy,cysnake4713/wechatpy | from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
- tmpstr = six.binary_type(tmpstr)
+ tmpstr = six.text_type(tmpstr).encode('utf-8')
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature
| Fix test error on Python 3 | ## Code Before:
from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
tmpstr = six.binary_type(tmpstr)
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature
## Instruction:
Fix test error on Python 3
## Code After:
from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
tmpstr = six.text_type(tmpstr).encode('utf-8')
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature
| from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature, timestamp, nonce):
tmparr = [token, timestamp, nonce]
tmparr.sort()
tmpstr = ''.join(tmparr)
- tmpstr = six.binary_type(tmpstr)
+ tmpstr = six.text_type(tmpstr).encode('utf-8')
digest = hashlib.sha1(tmpstr).hexdigest()
return digest == signature |
8ba05402376dc2d368bae226f929b9a0b448a3c5 | localized_fields/admin.py | localized_fields/admin.py | from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| Fix using LocalizedFieldsAdminMixin with inlines | Fix using LocalizedFieldsAdminMixin with inlines
| Python | mit | SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields | - from django.contrib.admin import ModelAdmin
-
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
- class LocalizedFieldsAdminMixin(ModelAdmin):
+ class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| Fix using LocalizedFieldsAdminMixin with inlines | ## Code Before:
from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
## Instruction:
Fix using LocalizedFieldsAdminMixin with inlines
## Code After:
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| - from django.contrib.admin import ModelAdmin
-
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
- class LocalizedFieldsAdminMixin(ModelAdmin):
? ------------
+ class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides |
b50aee7a23c44b98b3cd6fee607cc5978a57c927 | contrail_provisioning/config/templates/contrail_sudoers.py | contrail_provisioning/config/templates/contrail_sudoers.py | import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART
""")
| import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
Cmnd_Alias IFMAPRESTART = /usr/sbin/service ifmap restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART,IFMAPRESTART
""")
| Allow contrail user to restart ifmap without password closes-jira-bug: JCB-218958 | Allow contrail user to restart ifmap without password
closes-jira-bug: JCB-218958
Change-Id: Id95001cf5ab455650b5b900b9b5f7bb33ccef8e3
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning | import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
+ Cmnd_Alias IFMAPRESTART = /usr/sbin/service ifmap restart
- contrail ALL = (root) NOPASSWD:CONFIGRESTART
+ contrail ALL = (root) NOPASSWD:CONFIGRESTART,IFMAPRESTART
""")
| Allow contrail user to restart ifmap without password closes-jira-bug: JCB-218958 | ## Code Before:
import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART
""")
## Instruction:
Allow contrail user to restart ifmap without password closes-jira-bug: JCB-218958
## Code After:
import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
Cmnd_Alias IFMAPRESTART = /usr/sbin/service ifmap restart
contrail ALL = (root) NOPASSWD:CONFIGRESTART,IFMAPRESTART
""")
| import string
template = string.Template("""
Defaults:contrail !requiretty
Cmnd_Alias CONFIGRESTART = /usr/sbin/service supervisor-config restart
+ Cmnd_Alias IFMAPRESTART = /usr/sbin/service ifmap restart
- contrail ALL = (root) NOPASSWD:CONFIGRESTART
? ^
+ contrail ALL = (root) NOPASSWD:CONFIGRESTART,IFMAPRESTART
? ^^^^^^^^^^^^^
""") |
72de9e47015e2018ca13c6d4681a79e53c2d5475 | brabeion/models.py | brabeion/models.py | from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
awarded_at = models.DateTimeField(default=datetime.now)
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level)
| from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
awarded_at = models.DateTimeField(default=timezone.now)
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level)
| Use timezone-aware dates with BadgeAward if desired | Use timezone-aware dates with BadgeAward if desired
| Python | bsd-3-clause | kinsights/brabeion | from datetime import datetime
+ from django.contrib.auth.models import User
from django.db import models
+ from django.utils import timezone
-
- from django.contrib.auth.models import User
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
- awarded_at = models.DateTimeField(default=datetime.now)
+ awarded_at = models.DateTimeField(default=timezone.now)
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level)
| Use timezone-aware dates with BadgeAward if desired | ## Code Before:
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
awarded_at = models.DateTimeField(default=datetime.now)
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level)
## Instruction:
Use timezone-aware dates with BadgeAward if desired
## Code After:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
awarded_at = models.DateTimeField(default=timezone.now)
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level)
| from datetime import datetime
+ from django.contrib.auth.models import User
from django.db import models
+ from django.utils import timezone
-
- from django.contrib.auth.models import User
class BadgeAward(models.Model):
user = models.ForeignKey(User, related_name="badges_earned")
- awarded_at = models.DateTimeField(default=datetime.now)
? ----
+ awarded_at = models.DateTimeField(default=timezone.now)
? ++++
slug = models.CharField(max_length=255)
level = models.IntegerField()
def __getattr__(self, attr):
return getattr(self._badge, attr)
@property
def badge(self):
return self
@property
def _badge(self):
from brabeion import badges
return badges._registry[self.slug]
@property
def name(self):
return self._badge.levels[self.level].name
@property
def description(self):
return self._badge.levels[self.level].description
@property
def progress(self):
return self._badge.progress(self.user, self.level) |
2df886059a9edd8d75fdb255fc185c2f96a02c29 | user/signals.py | user/signals.py | import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
# MAke user organizer if fits regex
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
if not REGEX_PATTERN or not created:
return None
if re.match(REGEX_PATTERN, instance.email):
instance.is_organizer = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send()
| import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
DEV_EMAILS = getattr(settings, 'HACKATHON_DEV_EMAILS', None)
# Make user organizer or admin if fits regex
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
if not created:
return None
if REGEX_PATTERN and re.match(REGEX_PATTERN, instance.email):
instance.is_organizer = True
instance.save()
if DEV_EMAILS and instance.email in DEV_EMAILS:
instance.is_admin = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send()
| Make developers an admin on registration | Make developers an admin on registration
| Python | mit | hackupc/backend,hackupc/backend,hackupc/backend,hackupc/backend | import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
+ DEV_EMAILS = getattr(settings, 'HACKATHON_DEV_EMAILS', None)
- # MAke user organizer if fits regex
+ # Make user organizer or admin if fits regex
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
- if not REGEX_PATTERN or not created:
+ if not created:
return None
+
- if re.match(REGEX_PATTERN, instance.email):
+ if REGEX_PATTERN and re.match(REGEX_PATTERN, instance.email):
instance.is_organizer = True
+ instance.save()
+
+ if DEV_EMAILS and instance.email in DEV_EMAILS:
+ instance.is_admin = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send()
| Make developers an admin on registration | ## Code Before:
import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
# MAke user organizer if fits regex
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
if not REGEX_PATTERN or not created:
return None
if re.match(REGEX_PATTERN, instance.email):
instance.is_organizer = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send()
## Instruction:
Make developers an admin on registration
## Code After:
import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
DEV_EMAILS = getattr(settings, 'HACKATHON_DEV_EMAILS', None)
# Make user organizer or admin if fits regex
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
if not created:
return None
if REGEX_PATTERN and re.match(REGEX_PATTERN, instance.email):
instance.is_organizer = True
instance.save()
if DEV_EMAILS and instance.email in DEV_EMAILS:
instance.is_admin = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send()
| import re
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from user import tokens
from user.models import User
REGEX_PATTERN = getattr(settings, 'REGEX_HACKATHON_ORGANIZER_EMAIL', None)
+ DEV_EMAILS = getattr(settings, 'HACKATHON_DEV_EMAILS', None)
- # MAke user organizer if fits regex
? ^
+ # Make user organizer or admin if fits regex
? ^ +++++++++
@receiver(post_save, sender=User)
def user_organizer(sender, instance, created, *args, **kwargs):
- if not REGEX_PATTERN or not created:
+ if not created:
return None
+
- if re.match(REGEX_PATTERN, instance.email):
+ if REGEX_PATTERN and re.match(REGEX_PATTERN, instance.email):
? ++++++++++++++++++
instance.is_organizer = True
+ instance.save()
+
+ if DEV_EMAILS and instance.email in DEV_EMAILS:
+ instance.is_admin = True
instance.save()
# Send user verification
@receiver(post_save, sender=User)
def user_verify_email(sender, instance, created, *args, **kwargs):
if created and not instance.email_verified:
msg = tokens.generate_verify_email(instance)
msg.send() |
275cec3a846093769eaddda87b753a7e5c224f59 | odbc2csv.py | odbc2csv.py | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file)
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file, lineterminator='\n')
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| Use just newline for file terminator. | Use just newline for file terminator. | Python | isc | wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
- writer = csv.writer(file)
+ writer = csv.writer(file, lineterminator='\n')
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| Use just newline for file terminator. | ## Code Before:
import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file)
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
## Instruction:
Use just newline for file terminator.
## Code After:
import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
writer = csv.writer(file, lineterminator='\n')
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close()
| import pypyodbc
import csv
conn = pypyodbc.connect("DSN=HOSS_DB")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
print(table)
cur.execute("select * from {}".format(table))
column_names = []
for d in cur.description:
column_names.append(d[0])
# file = open("{}.csv".format(table), "w", encoding="ISO-8859-1")
file = open("{}.csv".format(table), "w", encoding="utf-8")
- writer = csv.writer(file)
+ writer = csv.writer(file, lineterminator='\n')
writer.writerow(column_names)
for row in cur.fetchall():
writer.writerow(row)
file.close() |
c498bb6ac7a80ac2668fef22fa6600de6fc9af89 | dakota/plugins/base.py | dakota/plugins/base.py | """An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
def setup(self):
"""Configure component inputs."""
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
def load(self):
"""Read data from a component output file."""
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
def write(self):
"""Write a Dakota results file."""
pass
| """An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
def setup(self, config):
"""Configure component inputs.
Sets attributes using information from the run configuration
file. The Dakota parsing utility ``dprepro`` reads parameters
from Dakota to create a new input file from a template.
Parameters
----------
config : dict
Stores configuration settings for a Dakota experiment.
"""
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
def load(self, output_file):
"""Read data from a component output file.
Parameters
----------
output_file : str
The path to a component output file.
Returns
-------
array_like
A numpy array, or None on an error.
"""
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
def write(self, params_file, results_file):
"""Write a Dakota results file.
Parameters
----------
params_file : str
A Dakota parameters file.
results_file : str
A Dakota results file.
"""
pass
| Update argument lists for abstract methods | Update argument lists for abstract methods
| Python | mit | csdms/dakota,csdms/dakota | """An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
- def setup(self):
+ def setup(self, config):
- """Configure component inputs."""
+ """Configure component inputs.
+
+ Sets attributes using information from the run configuration
+ file. The Dakota parsing utility ``dprepro`` reads parameters
+ from Dakota to create a new input file from a template.
+
+ Parameters
+ ----------
+ config : dict
+ Stores configuration settings for a Dakota experiment.
+
+ """
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
- def load(self):
+ def load(self, output_file):
- """Read data from a component output file."""
+ """Read data from a component output file.
+
+ Parameters
+ ----------
+ output_file : str
+ The path to a component output file.
+
+ Returns
+ -------
+ array_like
+ A numpy array, or None on an error.
+
+ """
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
- def write(self):
+ def write(self, params_file, results_file):
- """Write a Dakota results file."""
+ """Write a Dakota results file.
+
+ Parameters
+ ----------
+ params_file : str
+ A Dakota parameters file.
+ results_file : str
+ A Dakota results file.
+
+ """
pass
| Update argument lists for abstract methods | ## Code Before:
"""An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
def setup(self):
"""Configure component inputs."""
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
def load(self):
"""Read data from a component output file."""
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
def write(self):
"""Write a Dakota results file."""
pass
## Instruction:
Update argument lists for abstract methods
## Code After:
"""An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
def setup(self, config):
"""Configure component inputs.
Sets attributes using information from the run configuration
file. The Dakota parsing utility ``dprepro`` reads parameters
from Dakota to create a new input file from a template.
Parameters
----------
config : dict
Stores configuration settings for a Dakota experiment.
"""
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
def load(self, output_file):
"""Read data from a component output file.
Parameters
----------
output_file : str
The path to a component output file.
Returns
-------
array_like
A numpy array, or None on an error.
"""
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
def write(self, params_file, results_file):
"""Write a Dakota results file.
Parameters
----------
params_file : str
A Dakota parameters file.
results_file : str
A Dakota results file.
"""
pass
| """An abstract base class for all Dakota component plugins."""
from abc import ABCMeta, abstractmethod
class PluginBase(object):
"""Describe features common to all Dakota plugins."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
"""Define default attributes."""
pass
@abstractmethod
- def setup(self):
+ def setup(self, config):
? ++++++++
- """Configure component inputs."""
? ---
+ """Configure component inputs.
+
+ Sets attributes using information from the run configuration
+ file. The Dakota parsing utility ``dprepro`` reads parameters
+ from Dakota to create a new input file from a template.
+
+ Parameters
+ ----------
+ config : dict
+ Stores configuration settings for a Dakota experiment.
+
+ """
pass
@abstractmethod
def call(self):
"""Call the component through the shell."""
pass
@abstractmethod
- def load(self):
+ def load(self, output_file):
- """Read data from a component output file."""
? ---
+ """Read data from a component output file.
+
+ Parameters
+ ----------
+ output_file : str
+ The path to a component output file.
+
+ Returns
+ -------
+ array_like
+ A numpy array, or None on an error.
+
+ """
pass
@abstractmethod
def calculate(self):
"""Calculate Dakota response functions."""
pass
@abstractmethod
- def write(self):
+ def write(self, params_file, results_file):
- """Write a Dakota results file."""
? ---
+ """Write a Dakota results file.
+
+ Parameters
+ ----------
+ params_file : str
+ A Dakota parameters file.
+ results_file : str
+ A Dakota results file.
+
+ """
pass |
fb9ca96431a4f72135245705359eb1f6d340a536 | moksha/api/hub/__init__.py | moksha/api/hub/__init__.py |
from consumer import *
from hub import *
|
from consumer import *
from hub import *
from moksha.hub.reactor import reactor
from moksha.hub.hub import MokshaHub
| Make the MokshaHub and reactor available in the moksha.api.hub module | Make the MokshaHub and reactor available in the moksha.api.hub module
| Python | apache-2.0 | lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha |
from consumer import *
from hub import *
+ from moksha.hub.reactor import reactor
+ from moksha.hub.hub import MokshaHub
+ | Make the MokshaHub and reactor available in the moksha.api.hub module | ## Code Before:
from consumer import *
from hub import *
## Instruction:
Make the MokshaHub and reactor available in the moksha.api.hub module
## Code After:
from consumer import *
from hub import *
from moksha.hub.reactor import reactor
from moksha.hub.hub import MokshaHub
|
from consumer import *
from hub import *
+
+ from moksha.hub.reactor import reactor
+ from moksha.hub.hub import MokshaHub |
0dda4e65d4c15e3654cb77298e008d6f2d1f179b | numpy/_array_api/_dtypes.py | numpy/_array_api/_dtypes.py | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
| import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| Use tuples for internal type lists in the array API | Use tuples for internal type lists in the array API
These are easier for type checkers to handle.
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
- _all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
+ _all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
- float32, float64, bool]
+ float32, float64, bool)
- _boolean_dtypes = [bool]
+ _boolean_dtypes = (bool)
- _floating_dtypes = [float32, float64]
+ _floating_dtypes = (float32, float64)
- _integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
+ _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
- _integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
+ _integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
- _numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
+ _numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| Use tuples for internal type lists in the array API | ## Code Before:
import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
## Instruction:
Use tuples for internal type lists in the array API
## Code After:
import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
- _all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
? ^
+ _all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
? ^
- float32, float64, bool]
? ^
+ float32, float64, bool)
? ^
- _boolean_dtypes = [bool]
? ^ ^
+ _boolean_dtypes = (bool)
? ^ ^
- _floating_dtypes = [float32, float64]
? ^ ^
+ _floating_dtypes = (float32, float64)
? ^ ^
- _integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
? ^ ^
+ _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
? ^ ^
- _integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
? ^ ^
+ _integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
? ^ ^
- _numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
? ^ ^
+ _numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
? ^ ^
|
87844a776c2d409bdf7eaa99da06d07d77d7098e | tests/test_gingerit.py | tests/test_gingerit.py | import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories."
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday"
),
(
"Edwards was sick yesterday.",
"Edwards was sick yesterday."
),
(
"",
""
)
])
def test_gingerit(text, expected):
parser = GingerIt()
assert parser.parse(text)["result"] == expected
| import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected,corrections", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories.",
[
{'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},
{'start': 13, 'definition': u'a plant cultivated for its blooms or blossoms', 'correct': u'flowers',
'text': 'fliwers'},
{'start': 4, 'definition': None, 'correct': u'smell', 'text': 'smelt'}
]
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday",
[
{'start': 16, 'definition': u'affected by an impairment of normal physical or mental function',
'correct': u'sick', 'text': 'sck'},
{'start': 8, 'definition': None, 'correct': u'was', 'text': 'will be'}
]
),
(
"Edwards was sick yesterday.",
"Edwards was sick yesterday.",
[]
),
(
"",
"",
[]
)
])
def test_gingerit(text, expected, corrections):
output = GingerIt().parse(text)
assert output["result"] == expected
assert output["corrections"] == corrections
| Extend test to cover corrections output | Extend test to cover corrections output
| Python | mit | Azd325/gingerit | import pytest
from gingerit.gingerit import GingerIt
- @pytest.mark.parametrize("text,expected", [
+ @pytest.mark.parametrize("text,expected,corrections", [
(
"The smelt of fliwers bring back memories.",
- "The smell of flowers brings back memories."
+ "The smell of flowers brings back memories.",
+ [
+ {'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},
+ {'start': 13, 'definition': u'a plant cultivated for its blooms or blossoms', 'correct': u'flowers',
+ 'text': 'fliwers'},
+ {'start': 4, 'definition': None, 'correct': u'smell', 'text': 'smelt'}
+ ]
),
(
"Edwards will be sck yesterday",
- "Edwards was sick yesterday"
+ "Edwards was sick yesterday",
+ [
+ {'start': 16, 'definition': u'affected by an impairment of normal physical or mental function',
+ 'correct': u'sick', 'text': 'sck'},
+ {'start': 8, 'definition': None, 'correct': u'was', 'text': 'will be'}
+ ]
),
(
"Edwards was sick yesterday.",
- "Edwards was sick yesterday."
+ "Edwards was sick yesterday.",
+ []
),
(
"",
- ""
+ "",
+ []
)
])
- def test_gingerit(text, expected):
+ def test_gingerit(text, expected, corrections):
+ output = GingerIt().parse(text)
- parser = GingerIt()
- assert parser.parse(text)["result"] == expected
+ assert output["result"] == expected
+ assert output["corrections"] == corrections
+ | Extend test to cover corrections output | ## Code Before:
import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories."
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday"
),
(
"Edwards was sick yesterday.",
"Edwards was sick yesterday."
),
(
"",
""
)
])
def test_gingerit(text, expected):
parser = GingerIt()
assert parser.parse(text)["result"] == expected
## Instruction:
Extend test to cover corrections output
## Code After:
import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected,corrections", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories.",
[
{'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},
{'start': 13, 'definition': u'a plant cultivated for its blooms or blossoms', 'correct': u'flowers',
'text': 'fliwers'},
{'start': 4, 'definition': None, 'correct': u'smell', 'text': 'smelt'}
]
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday",
[
{'start': 16, 'definition': u'affected by an impairment of normal physical or mental function',
'correct': u'sick', 'text': 'sck'},
{'start': 8, 'definition': None, 'correct': u'was', 'text': 'will be'}
]
),
(
"Edwards was sick yesterday.",
"Edwards was sick yesterday.",
[]
),
(
"",
"",
[]
)
])
def test_gingerit(text, expected, corrections):
output = GingerIt().parse(text)
assert output["result"] == expected
assert output["corrections"] == corrections
| import pytest
from gingerit.gingerit import GingerIt
- @pytest.mark.parametrize("text,expected", [
+ @pytest.mark.parametrize("text,expected,corrections", [
? ++++++++++++
(
"The smelt of fliwers bring back memories.",
- "The smell of flowers brings back memories."
+ "The smell of flowers brings back memories.",
? +
+ [
+ {'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},
+ {'start': 13, 'definition': u'a plant cultivated for its blooms or blossoms', 'correct': u'flowers',
+ 'text': 'fliwers'},
+ {'start': 4, 'definition': None, 'correct': u'smell', 'text': 'smelt'}
+ ]
),
(
"Edwards will be sck yesterday",
- "Edwards was sick yesterday"
+ "Edwards was sick yesterday",
? +
+ [
+ {'start': 16, 'definition': u'affected by an impairment of normal physical or mental function',
+ 'correct': u'sick', 'text': 'sck'},
+ {'start': 8, 'definition': None, 'correct': u'was', 'text': 'will be'}
+ ]
),
(
"Edwards was sick yesterday.",
- "Edwards was sick yesterday."
+ "Edwards was sick yesterday.",
? +
+ []
),
(
"",
- ""
+ "",
? +
+ []
)
])
- def test_gingerit(text, expected):
+ def test_gingerit(text, expected, corrections):
? +++++++++++++
- parser = GingerIt()
+ output = GingerIt().parse(text)
+
- assert parser.parse(text)["result"] == expected
? ^^^^^^^^^^^^ ----
+ assert output["result"] == expected
? +++ ^
+ assert output["corrections"] == corrections |
87f44bb68af64f2654c68fb60bf93a34ac6095a6 | pylearn2/scripts/dbm/dbm_metrics.py | pylearn2/scripts/dbm/dbm_metrics.py | import argparse
if __name__ == '__main__':
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
choices=["ais"])
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
metric = args.metric
model_path = args.model_path
| import argparse
from pylearn2.utils import serial
def compute_ais(model):
pass
if __name__ == '__main__':
# Possible metrics
metrics = {'ais': compute_ais}
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
choices=metrics.keys())
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
metric = metrics[args.metric]
model = serial.load(args.model_path)
metric(model)
| Make the script recuperate the correct method | Make the script recuperate the correct method
| Python | bsd-3-clause | fyffyt/pylearn2,daemonmaker/pylearn2,se4u/pylearn2,hyqneuron/pylearn2-maxsom,abergeron/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,w1kke/pylearn2,matrogers/pylearn2,TNick/pylearn2,msingh172/pylearn2,shiquanwang/pylearn2,pkainz/pylearn2,fishcorn/pylearn2,chrish42/pylearn,kose-y/pylearn2,Refefer/pylearn2,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,nouiz/pylearn2,pombredanne/pylearn2,pombredanne/pylearn2,skearnes/pylearn2,CIFASIS/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,hyqneuron/pylearn2-maxsom,ddboline/pylearn2,bartvm/pylearn2,ashhher3/pylearn2,alexjc/pylearn2,aalmah/pylearn2,ddboline/pylearn2,TNick/pylearn2,hyqneuron/pylearn2-maxsom,fulmicoton/pylearn2,msingh172/pylearn2,lancezlin/pylearn2,hantek/pylearn2,JesseLivezey/pylearn2,theoryno3/pylearn2,aalmah/pylearn2,CIFASIS/pylearn2,mclaughlin6464/pylearn2,mclaughlin6464/pylearn2,ashhher3/pylearn2,lisa-lab/pylearn2,aalmah/pylearn2,junbochen/pylearn2,woozzu/pylearn2,JesseLivezey/pylearn2,goodfeli/pylearn2,hantek/pylearn2,cosmoharrigan/pylearn2,aalmah/pylearn2,fishcorn/pylearn2,CIFASIS/pylearn2,lunyang/pylearn2,woozzu/pylearn2,ashhher3/pylearn2,junbochen/pylearn2,pkainz/pylearn2,ashhher3/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,shiquanwang/pylearn2,lisa-lab/pylearn2,KennethPierce/pylearnk,cosmoharrigan/pylearn2,abergeron/pylearn2,mkraemer67/pylearn2,chrish42/pylearn,kastnerkyle/pylearn2,pkainz/pylearn2,lancezlin/pylearn2,sandeepkbhat/pylearn2,se4u/pylearn2,kastnerkyle/pylearn2,JesseLivezey/plankton,TNick/pylearn2,kastnerkyle/pylearn2,caidongyun/pylearn2,junbochen/pylearn2,ddboline/pylearn2,goodfeli/pylearn2,caidongyun/pylearn2,w1kke/pylearn2,abergeron/pylearn2,nouiz/pylearn2,jamessergeant/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,fulmicoton/pylearn2,lamblin/pylearn2,fishcorn/pylearn2,jeremyfix/pylearn2,JesseLivezey/plankton,jeremyfix/pylearn2,mkraemer67/pylearn2,nouiz/pylearn2,jamessergeant/pylearn2,JesseLivezey/plankton,theoryno3/pylearn2,JesseLivezey/pylearn2,fulmicoton/pylearn2,skearnes/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,mkraemer67/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,KennethPierce/pylearnk,lamblin/pylearn2,alexjc/pylearn2,Refefer/pylearn2,theoryno3/pylearn2,kose-y/pylearn2,shiquanwang/pylearn2,daemonmaker/pylearn2,hyqneuron/pylearn2-maxsom,Refefer/pylearn2,cosmoharrigan/pylearn2,jamessergeant/pylearn2,woozzu/pylearn2,lunyang/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lunyang/pylearn2,caidongyun/pylearn2,hantek/pylearn2,matrogers/pylearn2,chrish42/pylearn,bartvm/pylearn2,jeremyfix/pylearn2,theoryno3/pylearn2,fyffyt/pylearn2,goodfeli/pylearn2,KennethPierce/pylearnk,junbochen/pylearn2,bartvm/pylearn2,msingh172/pylearn2,pombredanne/pylearn2,sandeepkbhat/pylearn2,hantek/pylearn2,alexjc/pylearn2,mclaughlin6464/pylearn2,JesseLivezey/pylearn2,kose-y/pylearn2,matrogers/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,msingh172/pylearn2,mkraemer67/pylearn2,se4u/pylearn2,TNick/pylearn2,KennethPierce/pylearnk,w1kke/pylearn2,kose-y/pylearn2,CIFASIS/pylearn2,JesseLivezey/plankton,pombredanne/pylearn2,kastnerkyle/pylearn2,goodfeli/pylearn2,w1kke/pylearn2,lisa-lab/pylearn2,pkainz/pylearn2,jeremyfix/pylearn2,fyffyt/pylearn2,sandeepkbhat/pylearn2,se4u/pylearn2,lamblin/pylearn2,Refefer/pylearn2,sandeepkbhat/pylearn2,alexjc/pylearn2,nouiz/pylearn2,daemonmaker/pylearn2,matrogers/pylearn2 | import argparse
+ from pylearn2.utils import serial
+
+
+ def compute_ais(model):
+ pass
if __name__ == '__main__':
+ # Possible metrics
+ metrics = {'ais': compute_ais}
+
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
- choices=["ais"])
+ choices=metrics.keys())
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
- metric = args.metric
+ metric = metrics[args.metric]
- model_path = args.model_path
+ model = serial.load(args.model_path)
+ metric(model)
+ | Make the script recuperate the correct method | ## Code Before:
import argparse
if __name__ == '__main__':
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
choices=["ais"])
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
metric = args.metric
model_path = args.model_path
## Instruction:
Make the script recuperate the correct method
## Code After:
import argparse
from pylearn2.utils import serial
def compute_ais(model):
pass
if __name__ == '__main__':
# Possible metrics
metrics = {'ais': compute_ais}
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
choices=metrics.keys())
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
metric = metrics[args.metric]
model = serial.load(args.model_path)
metric(model)
| import argparse
+ from pylearn2.utils import serial
+
+
+ def compute_ais(model):
+ pass
if __name__ == '__main__':
+ # Possible metrics
+ metrics = {'ais': compute_ais}
+
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
- choices=["ais"])
? ^^^ ^^
+ choices=metrics.keys())
? ^^^^ + ^^^^^^ +
parser.add_argument("model_path", help="path to the pickled DBM model")
args = parser.parse_args()
- metric = args.metric
+ metric = metrics[args.metric]
? ++++++++ +
- model_path = args.model_path
? -----
+ model = serial.load(args.model_path)
? ++++++++++++ +
+
+ metric(model) |
5aca39cef15ea4381b30127b8ded31ec37ffd273 | script/notification/ifttt.py | script/notification/ifttt.py | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')})
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT')
| from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
r = requests.post(self.__url, data = {
'value1':self.__packpub_info['title'].encode('utf-8'),
'value2':self.__packpub_info['description'].encode('utf-8'),
'value3':self.__packpub_info['url_image']
})
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT')
| Add image to ifff request | Add image to ifff request
| Python | mit | niqdev/packtpub-crawler,niqdev/packtpub-crawler,niqdev/packtpub-crawler | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
- r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')})
+ r = requests.post(self.__url, data = {
+ 'value1':self.__packpub_info['title'].encode('utf-8'),
+ 'value2':self.__packpub_info['description'].encode('utf-8'),
+ 'value3':self.__packpub_info['url_image']
+ })
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT')
| Add image to ifff request | ## Code Before:
from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')})
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT')
## Instruction:
Add image to ifff request
## Code After:
from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
r = requests.post(self.__url, data = {
'value1':self.__packpub_info['title'].encode('utf-8'),
'value2':self.__packpub_info['description'].encode('utf-8'),
'value3':self.__packpub_info['url_image']
})
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT')
| from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.event_name'),
apiKey=config.get('ifttt', 'ifttt.key')
)
def send(self):
- r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')})
+ r = requests.post(self.__url, data = {
+ 'value1':self.__packpub_info['title'].encode('utf-8'),
+ 'value2':self.__packpub_info['description'].encode('utf-8'),
+ 'value3':self.__packpub_info['url_image']
+ })
log_success('[+] notification sent to IFTTT')
def sendError(self, exception, source):
title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source)
r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)})
log_success('[+] error notification sent to IFTTT') |
f8ea4266082fba1210be270d6ae7607717591978 | skimage/io/__init__.py | skimage/io/__init__.py |
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
info = [(p, plugin_info(p)) for p in available_plugins if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
wrap_len = 73
col_2_len = wrap_len - 1 - col_1_len
# Insert table header
info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len}))
info.insert(1, ('Plugin', {'description': 'Description'}))
info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len}))
info.append(('=' * col_1_len, {'description': '=' * col_2_len}))
for (name, meta_data) in info:
wrapped_descr = wrap(meta_data.get('description', ''),
col_2_len)
doc += "%s %s\n" % (name.ljust(col_1_len),
'\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__)
|
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
WRAP_LEN = 73
def _separator(char, lengths):
return [char * separator_length for separator_length in lengths]
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
info = [(p, plugin_info(p).get('description', 'no description'))
for p in available_plugins if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
col_2_len = WRAP_LEN - 1 - col_1_len
# Insert table header
info.insert(0, _separator('=', (col_1_len, col_2_len)))
info.insert(1, ('Plugin', 'Description'))
info.insert(2, _separator('-', (col_1_len, col_2_len)))
info.append(_separator('-', (col_1_len, col_2_len)))
for (name, plugin_description) in info:
wrapped_descr = wrap(plugin_description, col_2_len)
doc += "%s %s\n" % (name.ljust(col_1_len), '\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__)
| Refactor io doc building code | Refactor io doc building code
| Python | bsd-3-clause | youprofit/scikit-image,ofgulban/scikit-image,Hiyorimi/scikit-image,ofgulban/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,SamHames/scikit-image,bsipocz/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,dpshelio/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,emon10005/scikit-image,paalge/scikit-image,paalge/scikit-image,paalge/scikit-image,WarrenWeckesser/scikits-image,michaelaye/scikit-image,michaelpacer/scikit-image,ClinicalGraphics/scikit-image,emon10005/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,GaZ3ll3/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,keflavich/scikit-image,robintw/scikit-image,bennlich/scikit-image,newville/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,SamHames/scikit-image,ajaybhat/scikit-image,Hiyorimi/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,blink1073/scikit-image,keflavich/scikit-image,Britefury/scikit-image,chriscrosscutler/scikit-image,Midafi/scikit-image,rjeli/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,chintak/scikit-image,SamHames/scikit-image,chintak/scikit-image,jwiggins/scikit-image,Britefury/scikit-image,oew1v07/scikit-image,SamHames/scikit-image,warmspringwinds/scikit-image,michaelaye/scikit-image,pratapvardhan/scikit-image,rjeli/scikit-image,rjeli/scikit-image,dpshelio/scikit-image |
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
+ WRAP_LEN = 73
+
+
+ def _separator(char, lengths):
+ return [char * separator_length for separator_length in lengths]
+
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
+ info = [(p, plugin_info(p).get('description', 'no description'))
- info = [(p, plugin_info(p)) for p in available_plugins if not p == 'test']
+ for p in available_plugins if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
-
- wrap_len = 73
- col_2_len = wrap_len - 1 - col_1_len
+ col_2_len = WRAP_LEN - 1 - col_1_len
# Insert table header
- info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len}))
+ info.insert(0, _separator('=', (col_1_len, col_2_len)))
- info.insert(1, ('Plugin', {'description': 'Description'}))
+ info.insert(1, ('Plugin', 'Description'))
- info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len}))
- info.append(('=' * col_1_len, {'description': '=' * col_2_len}))
+ info.insert(2, _separator('-', (col_1_len, col_2_len)))
+ info.append(_separator('-', (col_1_len, col_2_len)))
+ for (name, plugin_description) in info:
+ wrapped_descr = wrap(plugin_description, col_2_len)
- for (name, meta_data) in info:
- wrapped_descr = wrap(meta_data.get('description', ''),
- col_2_len)
- doc += "%s %s\n" % (name.ljust(col_1_len),
+ doc += "%s %s\n" % (name.ljust(col_1_len), '\n'.join(wrapped_descr))
- '\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__)
| Refactor io doc building code | ## Code Before:
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
info = [(p, plugin_info(p)) for p in available_plugins if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
wrap_len = 73
col_2_len = wrap_len - 1 - col_1_len
# Insert table header
info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len}))
info.insert(1, ('Plugin', {'description': 'Description'}))
info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len}))
info.append(('=' * col_1_len, {'description': '=' * col_2_len}))
for (name, meta_data) in info:
wrapped_descr = wrap(meta_data.get('description', ''),
col_2_len)
doc += "%s %s\n" % (name.ljust(col_1_len),
'\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__)
## Instruction:
Refactor io doc building code
## Code After:
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
WRAP_LEN = 73
def _separator(char, lengths):
return [char * separator_length for separator_length in lengths]
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
info = [(p, plugin_info(p).get('description', 'no description'))
for p in available_plugins if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
col_2_len = WRAP_LEN - 1 - col_1_len
# Insert table header
info.insert(0, _separator('=', (col_1_len, col_2_len)))
info.insert(1, ('Plugin', 'Description'))
info.insert(2, _separator('-', (col_1_len, col_2_len)))
info.append(_separator('-', (col_1_len, col_2_len)))
for (name, plugin_description) in info:
wrapped_descr = wrap(plugin_description, col_2_len)
doc += "%s %s\n" % (name.ljust(col_1_len), '\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__)
|
from ._plugins import *
from .sift import *
from .collection import *
from ._io import *
from ._image_stack import *
from .video import *
reset_plugins()
+ WRAP_LEN = 73
+
+
+ def _separator(char, lengths):
+ return [char * separator_length for separator_length in lengths]
+
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
from textwrap import wrap
+ info = [(p, plugin_info(p).get('description', 'no description'))
- info = [(p, plugin_info(p)) for p in available_plugins if not p == 'test']
? ---- - ---- ^^^^^^^^^^^^^^^
+ for p in available_plugins if not p == 'test']
? ^^^^
col_1_len = max([len(n) for (n, _) in info])
-
- wrap_len = 73
- col_2_len = wrap_len - 1 - col_1_len
? ^^^^ ^^^
+ col_2_len = WRAP_LEN - 1 - col_1_len
? ^^^^ ^^^
# Insert table header
- info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len}))
+ info.insert(0, _separator('=', (col_1_len, col_2_len)))
- info.insert(1, ('Plugin', {'description': 'Description'}))
? ---------------- -
+ info.insert(1, ('Plugin', 'Description'))
- info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len}))
- info.append(('=' * col_1_len, {'description': '=' * col_2_len}))
+ info.insert(2, _separator('-', (col_1_len, col_2_len)))
+ info.append(_separator('-', (col_1_len, col_2_len)))
+ for (name, plugin_description) in info:
+ wrapped_descr = wrap(plugin_description, col_2_len)
- for (name, meta_data) in info:
- wrapped_descr = wrap(meta_data.get('description', ''),
- col_2_len)
- doc += "%s %s\n" % (name.ljust(col_1_len),
+ doc += "%s %s\n" % (name.ljust(col_1_len), '\n'.join(wrapped_descr))
? ++++++++++++++++++++++++++
- '\n'.join(wrapped_descr))
doc = doc.strip()
return doc
__doc__ = _update_doc(__doc__) |
2dec3e5810ef9ba532eaa735d0eac149c240aa2f | pyxrf/api.py | pyxrf/api.py |
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
make_hdf_stitched) # noqa: F401
from .model.load_data_from_db import make_hdf, export1d # noqa: F401
from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
# Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
# Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| Set flake8 to ignore F401 violations | Set flake8 to ignore F401 violations
| Python | bsd-3-clause | NSLS-II/PyXRF,NSLS-II-HXN/PyXRF,NSLS-II-HXN/PyXRF | + from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
+ combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
+ make_hdf_stitched) # noqa: F401
+ from .model.load_data_from_db import make_hdf, export1d # noqa: F401
+ from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
+
+ # Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
+ # Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| Set flake8 to ignore F401 violations | ## Code Before:
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
## Instruction:
Set flake8 to ignore F401 violations
## Code After:
from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
make_hdf_stitched) # noqa: F401
from .model.load_data_from_db import make_hdf, export1d # noqa: F401
from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
# Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
# Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| + from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
+ combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
+ make_hdf_stitched) # noqa: F401
+ from .model.load_data_from_db import make_hdf, export1d # noqa: F401
+ from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
+
+ # Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
+ # Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.') |
8b3c438b3f5fb9b2538a30182dd4f5d306aa098b | ankieta/contact/forms.py | ankieta/contact/forms.py | from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
| from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
| Fix contact form - send to recipient, not managers | Fix contact form - send to recipient, not managers
| Python | bsd-3-clause | watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl | from django import forms
- from django.core.mail import mail_managers
+ from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
+ from django.conf import settings
from .models import Contact
+ def my_mail_send(subject, recipient, message):
+ subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
+ from_email = settings.SERVER_EMAIL
+ return send_mail(subject, message, from_email, [recipient])
+
+
class ContactForm(forms.Form):
- personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
+ recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
- queryset=Contact.objects.all())
+ queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
- mail_managers(self.cleaned_data['topic'], self.get_text())
+ my_mail_send(subject=self.cleaned_data['topic'],
+ recipient=self.cleaned_data['recipient'].email,
+ message=self.get_text())
| Fix contact form - send to recipient, not managers | ## Code Before:
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
## Instruction:
Fix contact form - send to recipient, not managers
## Code After:
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
| from django import forms
- from django.core.mail import mail_managers
? ---------
+ from django.core.mail import send_mail
? +++++
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
+ from django.conf import settings
from .models import Contact
+ def my_mail_send(subject, recipient, message):
+ subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
+ from_email = settings.SERVER_EMAIL
+ return send_mail(subject, message, from_email, [recipient])
+
+
class ContactForm(forms.Form):
- personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
? --- ----
+ recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
? ++++ +
- queryset=Contact.objects.all())
+ queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
- mail_managers(self.cleaned_data['topic'], self.get_text())
+ my_mail_send(subject=self.cleaned_data['topic'],
+ recipient=self.cleaned_data['recipient'].email,
+ message=self.get_text()) |
879b15779c921445ca4412d5e63319408d8e32bf | python/islp/02statlearn-ex.py | python/islp/02statlearn-ex.py | import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
print(df)
| import matplotlib.pyplot as plt
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
df.rename(columns={'Unnamed: 0': 'Name'}, inplace=True)
df.set_index('Name', inplace=True)
print(df.describe())
fig = plt.figure()
gs = fig.add_gridspec(10, 10)
for r in range(10):
for c in range(10):
axes = fig.add_subplot(gs[r, c])
axes.xaxis.set_visible(False)
axes.yaxis.set_visible(False)
if r == c:
axes.annotate(df.columns.values[r], (0.5, 0.5),
xycoords='axes fraction', ha='center', va='center')
else:
df.plot.scatter(x=r, y=c, ax=axes)
plt.show()
| Add scatterplot matrix for college.csv. | Add scatterplot matrix for college.csv.
| Python | apache-2.0 | pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff | + import matplotlib.pyplot as plt
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
- print(df)
+ df.rename(columns={'Unnamed: 0': 'Name'}, inplace=True)
+ df.set_index('Name', inplace=True)
+ print(df.describe())
+ fig = plt.figure()
+ gs = fig.add_gridspec(10, 10)
+ for r in range(10):
+ for c in range(10):
+ axes = fig.add_subplot(gs[r, c])
+ axes.xaxis.set_visible(False)
+ axes.yaxis.set_visible(False)
+ if r == c:
+ axes.annotate(df.columns.values[r], (0.5, 0.5),
+ xycoords='axes fraction', ha='center', va='center')
+ else:
+ df.plot.scatter(x=r, y=c, ax=axes)
+ plt.show()
| Add scatterplot matrix for college.csv. | ## Code Before:
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
print(df)
## Instruction:
Add scatterplot matrix for college.csv.
## Code After:
import matplotlib.pyplot as plt
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
df.rename(columns={'Unnamed: 0': 'Name'}, inplace=True)
df.set_index('Name', inplace=True)
print(df.describe())
fig = plt.figure()
gs = fig.add_gridspec(10, 10)
for r in range(10):
for c in range(10):
axes = fig.add_subplot(gs[r, c])
axes.xaxis.set_visible(False)
axes.yaxis.set_visible(False)
if r == c:
axes.annotate(df.columns.values[r], (0.5, 0.5),
xycoords='axes fraction', ha='center', va='center')
else:
df.plot.scatter(x=r, y=c, ax=axes)
plt.show()
| + import matplotlib.pyplot as plt
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_values(by='dist')
print(df)
print('K=1 =>', df.head(1).Y.to_numpy()[0])
print('K=3 =>', df.head(3).groupby('Y').count().sort_values(by='dist', # arbitrary
ascending=False).index.values[0])
print('\nCollege.csv\n-----------')
df = pd.read_csv('College.csv')
- print(df)
+ df.rename(columns={'Unnamed: 0': 'Name'}, inplace=True)
+ df.set_index('Name', inplace=True)
+ print(df.describe())
+ fig = plt.figure()
+ gs = fig.add_gridspec(10, 10)
+ for r in range(10):
+ for c in range(10):
+ axes = fig.add_subplot(gs[r, c])
+ axes.xaxis.set_visible(False)
+ axes.yaxis.set_visible(False)
+ if r == c:
+ axes.annotate(df.columns.values[r], (0.5, 0.5),
+ xycoords='axes fraction', ha='center', va='center')
+ else:
+ df.plot.scatter(x=r, y=c, ax=axes)
+ plt.show() |
f7a601284d1654671fb87a006cb303bd792e14b4 | tracpro/polls/tests/test_utils.py | tracpro/polls/tests/test_utils.py | from __future__ import absolute_import, unicode_literals
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
| from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
class TestCategoryNaturalKey(TestCase):
def test_category_sort(self):
categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99']
categories.sort(key=utils.category_natural_key)
self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
| Add test for sorting with category natural key | Add test for sorting with category natural key
| Python | bsd-3-clause | xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro | from __future__ import absolute_import, unicode_literals
+
+ from django.test import TestCase
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
+
+ class TestCategoryNaturalKey(TestCase):
+
+ def test_category_sort(self):
+ categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99']
+ categories.sort(key=utils.category_natural_key)
+ self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
+ | Add test for sorting with category natural key | ## Code Before:
from __future__ import absolute_import, unicode_literals
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
## Instruction:
Add test for sorting with category natural key
## Code After:
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
class TestCategoryNaturalKey(TestCase):
def test_category_sort(self):
categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99']
categories.sort(key=utils.category_natural_key)
self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other'])
| from __future__ import absolute_import, unicode_literals
+
+ from django.test import TestCase
from tracpro.test.cases import TracProTest
from .. import utils
class TestExtractWords(TracProTest):
def test_extract_words(self):
self.assertEqual(
utils.extract_words("I think it's good", "eng"),
['think', 'good']) # I and it's are stop words
self.assertEqual(
utils.extract_words("I think it's good", "kin"),
['think', "it's", 'good']) # no stop words for kin
self.assertEqual(
utils.extract_words("قلم رصاص", "ara"),
['قلم', 'رصاص'])
+
+
+ class TestCategoryNaturalKey(TestCase):
+
+ def test_category_sort(self):
+ categories = ['11-20', '1-10', '<100', 'Other', '21-999', '21-99']
+ categories.sort(key=utils.category_natural_key)
+ self.assertEqual(categories, ['1-10', '11-20', '21-99', '21-999', '<100', 'Other']) |
5a8d7375b617bd5605bce5f09a4caedef170a85c | gbpservice/neutron/db/migration/cli.py | gbpservice/neutron/db/migration/cli.py |
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF()
CONF.command.func(config, CONF.command.name)
|
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF(project='neutron')
CONF.command.func(config, CONF.command.name)
| Set project when doing neutron DB migrations | Set project when doing neutron DB migrations
That way, the default configuration files/dirs from the neutron
projects are read when doing the DB migrations.
This is useful if eg. some configuration files are in
/etc/neutron/neutron.conf.d/ . Theses files will then be automatically
evaluated.
Change-Id: I4997a86c4df5fa45f7682d653a5e66b1ae184a62
| Python | apache-2.0 | noironetworks/group-based-policy,stackforge/group-based-policy,stackforge/group-based-policy,noironetworks/group-based-policy |
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
- CONF()
+ CONF(project='neutron')
CONF.command.func(config, CONF.command.name)
| Set project when doing neutron DB migrations | ## Code Before:
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF()
CONF.command.func(config, CONF.command.name)
## Instruction:
Set project when doing neutron DB migrations
## Code After:
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF(project='neutron')
CONF.command.func(config, CONF.command.name)
|
from neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
- CONF()
+ CONF(project='neutron')
CONF.command.func(config, CONF.command.name) |
151dbe6d319b27882e4df42a73c4fe6c6b77b90a | rm/trials/templatetags/share.py | rm/trials/templatetags/share.py | from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
return dict(
title=context['trial'].title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute)
| from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
title = ''
trial = context.get('trial')
if trial:
title = trial.title
return dict(
title=title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute)
| Move variable out of inline dict construction to debug production errors. | Move variable out of inline dict construction to debug production errors.
| Python | agpl-3.0 | openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me | from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
+ title = ''
+ trial = context.get('trial')
+ if trial:
+ title = trial.title
return dict(
- title=context['trial'].title,
+ title=title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute)
| Move variable out of inline dict construction to debug production errors. | ## Code Before:
from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
return dict(
title=context['trial'].title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute)
## Instruction:
Move variable out of inline dict construction to debug production errors.
## Code After:
from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
title = ''
trial = context.get('trial')
if trial:
title = trial.title
return dict(
title=title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute)
| from django.template import Library
register = Library()
def absolute(request):
return request.build_absolute_uri(request.path)
@register.inclusion_tag('share_this.html', takes_context=True)
def share_this(context):
"What, you can't copy a URL? Bah."
+ title = ''
+ trial = context.get('trial')
+ if trial:
+ title = trial.title
return dict(
- title=context['trial'].title,
+ title=title,
href=absolute(context['request']),
img=context['request'].build_absolute_uri('/static/img/randomisemelogo.png')
)
register.filter('absolute', absolute) |
de1ff8a480cc6d6e86bb179e6820ab9f21145679 | byceps/services/user/event_service.py | byceps/services/user/event_service.py |
from datetime import datetime
from typing import Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData
) -> UserEvent:
"""Assemble, but not persist, a user event."""
now = datetime.utcnow()
return UserEvent(now, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
|
from datetime import datetime
from typing import Optional, Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData,
occurred_at: Optional[datetime]=None) -> UserEvent:
"""Assemble, but not persist, a user event."""
if occurred_at is None:
occurred_at = datetime.utcnow()
return UserEvent(occurred_at, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
| Allow to provide a custom `occurred_at` value when building a user event | Allow to provide a custom `occurred_at` value when building a user event
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
from datetime import datetime
- from typing import Sequence
+ from typing import Optional, Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
- def _build_event(event_type: str, user_id: UserID, data: UserEventData
+ def _build_event(event_type: str, user_id: UserID, data: UserEventData,
- ) -> UserEvent:
+ occurred_at: Optional[datetime]=None) -> UserEvent:
"""Assemble, but not persist, a user event."""
+ if occurred_at is None:
- now = datetime.utcnow()
+ occurred_at = datetime.utcnow()
- return UserEvent(now, event_type, user_id, data)
+ return UserEvent(occurred_at, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
| Allow to provide a custom `occurred_at` value when building a user event | ## Code Before:
from datetime import datetime
from typing import Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData
) -> UserEvent:
"""Assemble, but not persist, a user event."""
now = datetime.utcnow()
return UserEvent(now, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
## Instruction:
Allow to provide a custom `occurred_at` value when building a user event
## Code After:
from datetime import datetime
from typing import Optional, Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData,
occurred_at: Optional[datetime]=None) -> UserEvent:
"""Assemble, but not persist, a user event."""
if occurred_at is None:
occurred_at = datetime.utcnow()
return UserEvent(occurred_at, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
|
from datetime import datetime
- from typing import Sequence
+ from typing import Optional, Sequence
? ++++++++++
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
- def _build_event(event_type: str, user_id: UserID, data: UserEventData
+ def _build_event(event_type: str, user_id: UserID, data: UserEventData,
? +
- ) -> UserEvent:
+ occurred_at: Optional[datetime]=None) -> UserEvent:
"""Assemble, but not persist, a user event."""
+ if occurred_at is None:
- now = datetime.utcnow()
? ^ ^
+ occurred_at = datetime.utcnow()
? ^^^^ ^^^^^^^^^^
- return UserEvent(now, event_type, user_id, data)
? - ^
+ return UserEvent(occurred_at, event_type, user_id, data)
? ^^^^^^^^^^
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all() |
091c125f42463b372f0c2c99124578eb8fe13150 | 2019/aoc2019/day08.py | 2019/aoc2019/day08.py | from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
| from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
| Fix day 8 to paint front-to-back | Fix day 8 to paint front-to-back
| Python | mit | bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode | from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
- layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
+ background.fill(2)
- for layer in reversed(layers):
- background[layer != 2] = layer[layer != 2]
+ for layer in parse_layers(25, 6, data):
+ mask = background == 2
+ background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
| Fix day 8 to paint front-to-back | ## Code Before:
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
## Instruction:
Fix day 8 to paint front-to-back
## Code After:
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
| from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
- layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
+ background.fill(2)
- for layer in reversed(layers):
- background[layer != 2] = layer[layer != 2]
+ for layer in parse_layers(25, 6, data):
+ mask = background == 2
+ background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25)) |
abff14b5804bf43bc2bffeac6418259580bdbae5 | makecard.py | makecard.py |
import svgwrite
def main():
print 'test'
if __name__ == '__main__':
main()
|
import sys
import svgwrite
def main():
drawing = svgwrite.Drawing(size=('1000', '1400'))
img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
drawing.add(img)
sys.stdout.write(drawing.tostring())
if __name__ == '__main__':
main()
| Include the first bullet svg | Include the first bullet svg
| Python | apache-2.0 | nanaze/xmascard |
+ import sys
import svgwrite
def main():
- print 'test'
+ drawing = svgwrite.Drawing(size=('1000', '1400'))
+
+ img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
+
+ drawing.add(img)
+
+ sys.stdout.write(drawing.tostring())
+
if __name__ == '__main__':
main()
| Include the first bullet svg | ## Code Before:
import svgwrite
def main():
print 'test'
if __name__ == '__main__':
main()
## Instruction:
Include the first bullet svg
## Code After:
import sys
import svgwrite
def main():
drawing = svgwrite.Drawing(size=('1000', '1400'))
img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
drawing.add(img)
sys.stdout.write(drawing.tostring())
if __name__ == '__main__':
main()
|
+ import sys
import svgwrite
def main():
- print 'test'
+ drawing = svgwrite.Drawing(size=('1000', '1400'))
+
+ img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
+
+ drawing.add(img)
+
+ sys.stdout.write(drawing.tostring())
+
if __name__ == '__main__':
main() |
0a9e3fb387c61f2c7cb32502f5c50eaa5b950169 | tests/test_process.py | tests/test_process.py |
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data)
assert e.value.exit_code != 0
|
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr.startswith('cat: {}'.format(data))
assert e.value.exit_code != 0
| Fix intermittent travis build error. | Fix intermittent travis build error.
| Python | mit | wamonite/packermate |
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
- assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data)
+ assert e.value.log_stderr.startswith('cat: {}'.format(data))
assert e.value.exit_code != 0
| Fix intermittent travis build error. | ## Code Before:
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data)
assert e.value.exit_code != 0
## Instruction:
Fix intermittent travis build error.
## Code After:
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr.startswith('cat: {}'.format(data))
assert e.value.exit_code != 0
|
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
- assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data)
+ assert e.value.log_stderr.startswith('cat: {}'.format(data))
assert e.value.exit_code != 0 |
5e6d52277e34c254bad6b386cf05f490baf6a6f2 | webapp-django/accounts/models.py | webapp-django/accounts/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
solvedChallenges=models.CharField(solved=[],max_length=256)
solvedQuestions=models.CharField(solved=[],max_length=256)
score = models.IntegerField(default=0)
def __str__(self):
return str(self.user.username)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
| from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from challenges.models import Challenge
from questionnaire.models import Question
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
solved_challenges = models.ManyToManyField(Challenge)
solved_questions = models.ManyToManyField(Question)
score = models.IntegerField(default=0, editable=False)
def __str__(self):
return str(self.user.username)
def calculate_score(self):
score = 0
for chal in self.solved_challenges.all():
score = score + chal.score
for ques in self.solved_questions.all():
score = score + ques.score
return score
def save(self, *args, **kwargs):
'''On save, update score '''
self.score = self.calculate_score()
return super(UserProfile, self).save(*args, **kwargs)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
| Update accounts model with scoring system | Update accounts model with scoring system
| Python | mit | super1337/Super1337-CTF,super1337/Super1337-CTF,super1337/Super1337-CTF | from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
+ from challenges.models import Challenge
+ from questionnaire.models import Question
+
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
- solvedChallenges=models.CharField(solved=[],max_length=256)
- solvedQuestions=models.CharField(solved=[],max_length=256)
- score = models.IntegerField(default=0)
+ solved_challenges = models.ManyToManyField(Challenge)
+ solved_questions = models.ManyToManyField(Question)
+ score = models.IntegerField(default=0, editable=False)
def __str__(self):
return str(self.user.username)
+
+ def calculate_score(self):
+ score = 0
+ for chal in self.solved_challenges.all():
+ score = score + chal.score
+ for ques in self.solved_questions.all():
+ score = score + ques.score
+
+ return score
+
+ def save(self, *args, **kwargs):
+ '''On save, update score '''
+
+ self.score = self.calculate_score()
+ return super(UserProfile, self).save(*args, **kwargs)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
| Update accounts model with scoring system | ## Code Before:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
solvedChallenges=models.CharField(solved=[],max_length=256)
solvedQuestions=models.CharField(solved=[],max_length=256)
score = models.IntegerField(default=0)
def __str__(self):
return str(self.user.username)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
## Instruction:
Update accounts model with scoring system
## Code After:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from challenges.models import Challenge
from questionnaire.models import Question
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
solved_challenges = models.ManyToManyField(Challenge)
solved_questions = models.ManyToManyField(Question)
score = models.IntegerField(default=0, editable=False)
def __str__(self):
return str(self.user.username)
def calculate_score(self):
score = 0
for chal in self.solved_challenges.all():
score = score + chal.score
for ques in self.solved_questions.all():
score = score + ques.score
return score
def save(self, *args, **kwargs):
'''On save, update score '''
self.score = self.calculate_score()
return super(UserProfile, self).save(*args, **kwargs)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
| from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
+ from challenges.models import Challenge
+ from questionnaire.models import Question
+
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=256, blank=True)
- solvedChallenges=models.CharField(solved=[],max_length=256)
- solvedQuestions=models.CharField(solved=[],max_length=256)
- score = models.IntegerField(default=0)
+ solved_challenges = models.ManyToManyField(Challenge)
+ solved_questions = models.ManyToManyField(Question)
+ score = models.IntegerField(default=0, editable=False)
def __str__(self):
return str(self.user.username)
+
+ def calculate_score(self):
+ score = 0
+ for chal in self.solved_challenges.all():
+ score = score + chal.score
+ for ques in self.solved_questions.all():
+ score = score + ques.score
+
+ return score
+
+ def save(self, *args, **kwargs):
+ '''On save, update score '''
+
+ self.score = self.calculate_score()
+ return super(UserProfile, self).save(*args, **kwargs)
# Method to link the User and UserProfile models
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save() |
4124297475fb7d77bf492e721a74fcfa02547a14 | benchmark/bench_logger_level_low.py | benchmark/bench_logger_level_low.py | """Benchmarks too low logger levels"""
from logbook import Logger, ERROR
log = Logger('Test logger')
log.level = ERROR
def run():
for x in xrange(500):
log.warning('this is not handled')
| """Benchmarks too low logger levels"""
from logbook import Logger, StreamHandler, ERROR
from cStringIO import StringIO
log = Logger('Test logger')
log.level = ERROR
def run():
out = StringIO()
with StreamHandler(out):
for x in xrange(500):
log.warning('this is not handled')
| Create a stream handler even though it's not used to have the same overhead on both logbook and logging | Create a stream handler even though it's not used to have the same overhead on both logbook and logging
| Python | bsd-3-clause | DasIch/logbook,maykinmedia/logbook,alonho/logbook,fayazkhan/logbook,maykinmedia/logbook,Rafiot/logbook,dvarrazzo/logbook,mbr/logbook,mitsuhiko/logbook,dvarrazzo/logbook,RazerM/logbook,FintanH/logbook,omergertel/logbook,dommert/logbook,DasIch/logbook,alex/logbook,alonho/logbook,pombredanne/logbook,alonho/logbook,alex/logbook,DasIch/logbook,mbr/logbook,fayazkhan/logbook,narfdotpl/logbook,redtoad/logbook,redtoad/logbook,Rafiot/logbook,omergertel/logbook,Rafiot/logbook,omergertel/logbook | """Benchmarks too low logger levels"""
- from logbook import Logger, ERROR
+ from logbook import Logger, StreamHandler, ERROR
+ from cStringIO import StringIO
log = Logger('Test logger')
log.level = ERROR
def run():
+ out = StringIO()
+ with StreamHandler(out):
- for x in xrange(500):
+ for x in xrange(500):
- log.warning('this is not handled')
+ log.warning('this is not handled')
| Create a stream handler even though it's not used to have the same overhead on both logbook and logging | ## Code Before:
"""Benchmarks too low logger levels"""
from logbook import Logger, ERROR
log = Logger('Test logger')
log.level = ERROR
def run():
for x in xrange(500):
log.warning('this is not handled')
## Instruction:
Create a stream handler even though it's not used to have the same overhead on both logbook and logging
## Code After:
"""Benchmarks too low logger levels"""
from logbook import Logger, StreamHandler, ERROR
from cStringIO import StringIO
log = Logger('Test logger')
log.level = ERROR
def run():
out = StringIO()
with StreamHandler(out):
for x in xrange(500):
log.warning('this is not handled')
| """Benchmarks too low logger levels"""
- from logbook import Logger, ERROR
+ from logbook import Logger, StreamHandler, ERROR
? +++++++++++++++
+ from cStringIO import StringIO
log = Logger('Test logger')
log.level = ERROR
def run():
+ out = StringIO()
+ with StreamHandler(out):
- for x in xrange(500):
+ for x in xrange(500):
? ++++
- log.warning('this is not handled')
+ log.warning('this is not handled')
? ++++
|
90c816bd40a4971dda8bd96d865efb1dee131566 | files/install_workflow.py | files/install_workflow.py | import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
with open(args.workflow_path, 'r') as wf_file:
import_uuid = json.load(wf_file).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| Make sure the opened workflow file gets closed after it's been loaded | Make sure the opened workflow file gets closed after it's been loaded
| Python | mit | galaxyproject/ansible-galaxy-tools,galaxyproject/ansible-tools,nuwang/ansible-galaxy-tools,anmoljh/ansible-galaxy-tools | import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
- import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
+ with open(args.workflow_path, 'r') as wf_file:
+ import_uuid = json.load(wf_file).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| Make sure the opened workflow file gets closed after it's been loaded | ## Code Before:
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
## Instruction:
Make sure the opened workflow file gets closed after it's been loaded
## Code After:
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
with open(args.workflow_path, 'r') as wf_file:
import_uuid = json.load(wf_file).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
- import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
+ with open(args.workflow_path, 'r') as wf_file:
+ import_uuid = json.load(wf_file).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main() |
ca214643b2a93bd9362182134624a8641b44aba2 | tree_stars/tree_stars.py | tree_stars/tree_stars.py | from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
| from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
| Add solution using format method for centering. | Add solution using format method for centering.
| Python | mit | bm5w/codeeval | from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
- spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
+ print ('{:^' + str(2 * levels + 2) + '}').format(stars)
+ # alternate method without using format centering
+ # spaces = (levels+2-sub_level) * ' '
- print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
+ # print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
-
if __name__ == '__main__':
main(int(argv[1]))
| Add solution using format method for centering. | ## Code Before:
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
## Instruction:
Add solution using format method for centering.
## Code After:
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
| from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
- spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
+ print ('{:^' + str(2 * levels + 2) + '}').format(stars)
+ # alternate method without using format centering
+ # spaces = (levels+2-sub_level) * ' '
- print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
+ # print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
? ++
-
if __name__ == '__main__':
main(int(argv[1])) |
6d8b6cfe9e2de860b4b39a1e0f0bb8fa45e6b96f | manage.py | manage.py |
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
|
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
| Fix import location of environment variables | Fix import location of environment variables
| Python | mit | moremorefor/Logpot,moremorefor/Logpot,moremorefor/Logpot | +
+ import os
+ if os.path.exists('.env'):
+ print('Importing environment from .env...')
+ for line in open('.env'):
+ var = line.strip().split('=')
+ if len(var) == 2:
+ os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
- import os
-
- if os.path.exists('.env'):
- print('Importing environment from .env...')
- for line in open('.env'):
- var = line.strip().split('=')
- if len(var) == 2:
- os.environ[var[0]] = var[1]
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
| Fix import location of environment variables | ## Code Before:
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
## Instruction:
Fix import location of environment variables
## Code After:
import os
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run()
| +
+ import os
+ if os.path.exists('.env'):
+ print('Importing environment from .env...')
+ for line in open('.env'):
+ var = line.strip().split('=')
+ if len(var) == 2:
+ os.environ[var[0]] = var[1]
from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass
from db_create import (
init_db,
drop_db,
init_admin_user,
init_entry,
init_category,
init_tag
)
from flask.ext.migrate import MigrateCommand
from logpot.app import app
- import os
-
- if os.path.exists('.env'):
- print('Importing environment from .env...')
- for line in open('.env'):
- var = line.strip().split('=')
- if len(var) == 2:
- os.environ[var[0]] = var[1]
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def run():
app.run(threaded=True)
@manager.command
def initialize():
if prompt_bool("Are you sure you want to create DB and initialize?"):
drop_db()
init_db()
if init_admin():
init_category()
init_tag()
init_entry()
print('Success!')
@manager.command
def init_admin():
name = prompt('Resister admin user.\n[?] input username: ')
email = prompt('[?] input email: ')
password = prompt_pass('[?] input password: ')
confirm_password = prompt_pass('[?] input password again: ')
if not password == confirm_password:
print('Password does not match.')
return False
else:
init_admin_user(name, email, password)
return True
if __name__ == "__main__":
manager.run() |
ac850c8f9284fbe6fd8e6318431d5e4856f26c7c | openquake/calculators/tests/classical_risk_test.py | openquake/calculators/tests/classical_risk_test.py | import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
| import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
out = self.run_calc(case_1.__file__, 'job_risk.ini', exports='xml')
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
| Work on classical_risk test_case_1 and test_case_2 | Work on classical_risk test_case_1 and test_case_2
| Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine | import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
- raise unittest.SkipTest
+ out = self.run_calc(case_1.__file__, 'job_risk.ini', exports='xml')
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
| Work on classical_risk test_case_1 and test_case_2 | ## Code Before:
import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
## Instruction:
Work on classical_risk test_case_1 and test_case_2
## Code After:
import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
out = self.run_calc(case_1.__file__, 'job_risk.ini', exports='xml')
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
| import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self):
- raise unittest.SkipTest
+ out = self.run_calc(case_1.__file__, 'job_risk.ini', exports='xml')
@attr('qa', 'risk', 'classical_risk')
def test_case_2(self):
raise unittest.SkipTest
@attr('qa', 'risk', 'classical_risk')
def test_case_3(self):
out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
[fname] = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname)
@attr('qa', 'risk', 'classical_risk')
def test_case_4(self):
out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini',
exports='csv')
fnames = out['avg_losses-rlzs', 'csv']
self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0])
self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1]) |
52a4a10d54374b08c5835d02077fd1edcdc547ac | tests/test_union_energy_grids/results.py | tests/test_union_energy_grids/results.py |
import sys
# import statepoint
sys.path.insert(0, '../../src/utils')
import statepoint
# read in statepoint file
if len(sys.argv) > 1:
sp = statepoint.StatePoint(sys.argv[1])
else:
sp = statepoint.StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
import sys
sys.path.insert(0, '../../src/utils')
from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
print(sys.argv)
sp = StatePoint(sys.argv[1])
else:
sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
| Fix import for statepoint for test_union_energy_grids | Fix import for statepoint for test_union_energy_grids
| Python | mit | smharper/openmc,paulromano/openmc,mit-crpg/openmc,bhermanmit/openmc,wbinventor/openmc,paulromano/openmc,samuelshaner/openmc,mit-crpg/openmc,smharper/openmc,samuelshaner/openmc,johnnyliu27/openmc,mit-crpg/openmc,lilulu/openmc,walshjon/openmc,shikhar413/openmc,liangjg/openmc,shikhar413/openmc,walshjon/openmc,paulromano/openmc,amandalund/openmc,lilulu/openmc,samuelshaner/openmc,kellyrowland/openmc,kellyrowland/openmc,wbinventor/openmc,smharper/openmc,shikhar413/openmc,johnnyliu27/openmc,smharper/openmc,wbinventor/openmc,wbinventor/openmc,walshjon/openmc,lilulu/openmc,amandalund/openmc,johnnyliu27/openmc,mjlong/openmc,liangjg/openmc,mit-crpg/openmc,paulromano/openmc,shikhar413/openmc,bhermanmit/openmc,samuelshaner/openmc,johnnyliu27/openmc,liangjg/openmc,walshjon/openmc,amandalund/openmc,amandalund/openmc,liangjg/openmc,mjlong/openmc |
import sys
- # import statepoint
sys.path.insert(0, '../../src/utils')
- import statepoint
+ from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
+ print(sys.argv)
- sp = statepoint.StatePoint(sys.argv[1])
+ sp = StatePoint(sys.argv[1])
else:
- sp = statepoint.StatePoint('statepoint.10.binary')
+ sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
-
+
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
| Fix import for statepoint for test_union_energy_grids | ## Code Before:
import sys
# import statepoint
sys.path.insert(0, '../../src/utils')
import statepoint
# read in statepoint file
if len(sys.argv) > 1:
sp = statepoint.StatePoint(sys.argv[1])
else:
sp = statepoint.StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
## Instruction:
Fix import for statepoint for test_union_energy_grids
## Code After:
import sys
sys.path.insert(0, '../../src/utils')
from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
print(sys.argv)
sp = StatePoint(sys.argv[1])
else:
sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
import sys
- # import statepoint
sys.path.insert(0, '../../src/utils')
- import statepoint
+ from openmc.statepoint import StatePoint
# read in statepoint file
if len(sys.argv) > 1:
+ print(sys.argv)
- sp = statepoint.StatePoint(sys.argv[1])
? -----------
+ sp = StatePoint(sys.argv[1])
else:
- sp = statepoint.StatePoint('statepoint.10.binary')
? -----------
+ sp = StatePoint('statepoint.10.binary')
sp.read_results()
# set up output string
outstr = ''
-
+
# write out k-combined
outstr += 'k-combined:\n'
outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr) |
46956660b1c4533e7a69fe2aa0dc17b73ce490ac | transporter/transporter.py | transporter/transporter.py | from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
if uri.scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
uri.scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
self.adapter = self.availible_adapters[uri.scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f)
| from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
default_scheme = "file"
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
scheme = uri.scheme or self.default_scheme
if scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
self.adapter = self.availible_adapters[scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f)
| Use LocalFileAdapter when no scheme is given | Use LocalFileAdapter when no scheme is given
>>> t1 = Transporter('/file/path')
>>> t2 = Transporter('file:/file/path')
>>> type(t1.adapter) == type(t2.adapter)
True
>>> t1.pwd() == t2.pwd()
True | Python | bsd-2-clause | joshmaker/transporter | from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
+ default_scheme = "file"
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
+ scheme = uri.scheme or self.default_scheme
- if uri.scheme not in self.availible_adapters:
+ if scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
- uri.scheme, [s for s in self.availible_adapters])
+ scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
- self.adapter = self.availible_adapters[uri.scheme](uri)
+ self.adapter = self.availible_adapters[scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f)
| Use LocalFileAdapter when no scheme is given | ## Code Before:
from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
if uri.scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
uri.scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
self.adapter = self.availible_adapters[uri.scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f)
## Instruction:
Use LocalFileAdapter when no scheme is given
## Code After:
from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
default_scheme = "file"
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
scheme = uri.scheme or self.default_scheme
if scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
self.adapter = self.availible_adapters[scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f)
| from urlparse import urlparse
import os
import adapters
try:
import paramiko
except ImportError:
pass
"""The following protocals are supported ftp, ftps, http and https.
sftp and ssh require paramiko to be installed
"""
class Transporter(object):
availible_adapters = {
"ftp": adapters.FtpAdapter,
"ftps": adapters.FtpAdapter,
"file": adapters.LocalFileAdapter
}
+ default_scheme = "file"
adapter = None
def __init__(self, uri):
uri = urlparse(uri)
+ scheme = uri.scheme or self.default_scheme
- if uri.scheme not in self.availible_adapters:
? ----
+ if scheme not in self.availible_adapters:
msg = u"{0} is not a support scheme. Availible schemes: {1}".format(
- uri.scheme, [s for s in self.availible_adapters])
? ----
+ scheme, [s for s in self.availible_adapters])
raise NotImplemented(msg)
- self.adapter = self.availible_adapters[uri.scheme](uri)
? ----
+ self.adapter = self.availible_adapters[scheme](uri)
def __getattr__(self, attr):
return getattr(self.adapter, attr)
def __repr__(self):
return u'<Transporter {0}>'.format(self.adapter.__repr__())
def download(uri):
f = os.path.basename(uri)
uri = os.path.dirname(uri)
uri = urlparse(uri)
return Transporter(uri).download(f)
def upload(f, uri):
return Transporter(uri).upload(f)
def transport(source, destination):
f = download(source)
return upload(destination, f) |
e5c8379c987d2d7ae60d5f9321bb96f278549167 | apel/parsers/__init__.py | apel/parsers/__init__.py | '''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser
| '''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
from htcondor import HTCondorParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser
| Add HTCondorParser to init imports | Add HTCondorParser to init imports
| Python | apache-2.0 | apel/apel,tofu-rocketry/apel,tofu-rocketry/apel,stfc/apel,apel/apel,stfc/apel | '''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
+ from htcondor import HTCondorParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser
| Add HTCondorParser to init imports | ## Code Before:
'''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser
## Instruction:
Add HTCondorParser to init imports
## Code After:
'''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
from htcondor import HTCondorParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser
| '''
Copyright (C) 2012 STFC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package with Apel parsers.
@author: Will Rogers, Konrad Jopek
'''
LOGGER_ID = 'parser'
from parser import Parser
from blah import BlahParser
+ from htcondor import HTCondorParser
from lsf import LSFParser
from pbs import PBSParser
from sge import SGEParser
from slurm import SlurmParser |
7dffcd1ea4b44decb8abb4e7d60cc07d665b4ce3 | subscription/api.py | subscription/api.py | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL
}
| from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL,
'user_account': ALL
}
| Add filter for limiting to one account | Add filter for limiting to one account
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
- 'to_addr': ALL
+ 'to_addr': ALL,
+ 'user_account': ALL
}
| Add filter for limiting to one account | ## Code Before:
from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL
}
## Instruction:
Add filter for limiting to one account
## Code After:
from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL,
'user_account': ALL
}
| from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
- 'to_addr': ALL
+ 'to_addr': ALL,
? +
+ 'user_account': ALL
} |
0df7044bf2c697fe87ea82e4e82ae8895c7fa4a6 | wsme/restjson.py | wsme/restjson.py | import base64
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
def prepare_encode(value, datatype):
if datatype in wsme.types.pod_types:
return value
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
d[name] = prepare_encode(getattr(value, name), attr.datatype)
return d
if datatype in wsme.types.dt_types:
return value.isoformat()
if datatype is wsme.types.binary:
return base64.encode()
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
return json.dumps({'result': prepare_encode(result, return_type)})
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol)
| import base64
import datetime
from simplegeneric import generic
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
@generic
def tojson(datatype, value):
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
d[name] = tojson(attr.datatype, getattr(value, name))
return d
return value
@tojson.when_object(datetime.date)
def date_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(datetime.time)
def time_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(datetime.datetime)
def datetime_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(wsme.types.binary)
def datetime_tojson(datatype, value):
return base64.encode(value)
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
return json.dumps({'result': tojson(return_type, result)})
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol)
| Use generic to prepare the json output so that non-structured custom types can be added | Use generic to prepare the json output so that non-structured custom types can be added
| Python | mit | stackforge/wsme | import base64
+ import datetime
+
+ from simplegeneric import generic
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
+ @generic
+ def tojson(datatype, value):
- def prepare_encode(value, datatype):
- if datatype in wsme.types.pod_types:
- return value
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
- d[name] = prepare_encode(getattr(value, name), attr.datatype)
+ d[name] = tojson(attr.datatype, getattr(value, name))
return d
- if datatype in wsme.types.dt_types:
+ return value
+
+
+ @tojson.when_object(datetime.date)
+ def date_tojson(datatype, value):
- return value.isoformat()
+ return value.isoformat()
- if datatype is wsme.types.binary:
+
+
+ @tojson.when_object(datetime.time)
+ def time_tojson(datatype, value):
+ return value.isoformat()
+
+ @tojson.when_object(datetime.datetime)
+ def datetime_tojson(datatype, value):
+ return value.isoformat()
+
+
+ @tojson.when_object(wsme.types.binary)
+ def datetime_tojson(datatype, value):
- return base64.encode()
+ return base64.encode(value)
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
- return json.dumps({'result': prepare_encode(result, return_type)})
+ return json.dumps({'result': tojson(return_type, result)})
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol)
| Use generic to prepare the json output so that non-structured custom types can be added | ## Code Before:
import base64
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
def prepare_encode(value, datatype):
if datatype in wsme.types.pod_types:
return value
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
d[name] = prepare_encode(getattr(value, name), attr.datatype)
return d
if datatype in wsme.types.dt_types:
return value.isoformat()
if datatype is wsme.types.binary:
return base64.encode()
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
return json.dumps({'result': prepare_encode(result, return_type)})
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol)
## Instruction:
Use generic to prepare the json output so that non-structured custom types can be added
## Code After:
import base64
import datetime
from simplegeneric import generic
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
@generic
def tojson(datatype, value):
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
d[name] = tojson(attr.datatype, getattr(value, name))
return d
return value
@tojson.when_object(datetime.date)
def date_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(datetime.time)
def time_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(datetime.datetime)
def datetime_tojson(datatype, value):
return value.isoformat()
@tojson.when_object(wsme.types.binary)
def datetime_tojson(datatype, value):
return base64.encode(value)
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
return json.dumps({'result': tojson(return_type, result)})
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol)
| import base64
+ import datetime
+
+ from simplegeneric import generic
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
+ @generic
+ def tojson(datatype, value):
- def prepare_encode(value, datatype):
- if datatype in wsme.types.pod_types:
- return value
if wsme.types.isstructured(datatype):
d = dict()
for name, attr in wsme.types.list_attributes(datatype):
- d[name] = prepare_encode(getattr(value, name), attr.datatype)
+ d[name] = tojson(attr.datatype, getattr(value, name))
return d
- if datatype in wsme.types.dt_types:
+ return value
+
+
+ @tojson.when_object(datetime.date)
+ def date_tojson(datatype, value):
- return value.isoformat()
? ----
+ return value.isoformat()
- if datatype is wsme.types.binary:
+
+
+ @tojson.when_object(datetime.time)
+ def time_tojson(datatype, value):
+ return value.isoformat()
+
+ @tojson.when_object(datetime.datetime)
+ def datetime_tojson(datatype, value):
+ return value.isoformat()
+
+
+ @tojson.when_object(wsme.types.binary)
+ def datetime_tojson(datatype, value):
- return base64.encode()
? ----
+ return base64.encode(value)
? +++++
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
content_types = ['application/json', 'text/json', None]
def decode_args(self, req, arguments):
kw = json.loads(req.body)
return kw
def encode_result(self, result, return_type):
- return json.dumps({'result': prepare_encode(result, return_type)})
? ^^^^^^^^^ ---- --------
+ return json.dumps({'result': tojson(return_type, result)})
? ^^^^^ ++++++++
def encode_error(self, errordetail):
return json.dumps(errordetail)
register_protocol(RestJsonProtocol) |
4c1bf1757baa5beec50377724961c528f5985864 | ptest/screencapturer.py | ptest/screencapturer.py | import threading
import traceback
import plogger
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
try:
screen_shot = active_browser.get_screenshot_as_png()
except Exception as e:
plogger.warn("Failed to take the screenshot: \n%s\n%s" % (e.message, traceback.format_exc()))
return
current_thread.get_property("running_test_case_fixture").screen_shot = screen_shot
else:
pass # todo: take screen shot for desktop | import threading
import traceback
import StringIO
import plogger
try:
from PIL import ImageGrab
except ImportError:
PIL_installed = False
else:
PIL_installed = True
try:
import wx
except ImportError:
wxpython_installed = False
else:
wxpython_installed = True
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
def capture_screen():
return active_browser.get_screenshot_as_png()
elif PIL_installed:
def capture_screen():
output = StringIO.StringIO()
ImageGrab.grab().save(output, format="png")
return output.getvalue()
elif wxpython_installed:
def capture_screen():
app = wx.App(False)
screen = wx.ScreenDC()
width, height = screen.GetSize()
bmp = wx.EmptyBitmap(width, height)
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, width, height, screen, 0, 0)
output = StringIO.StringIO()
bmp.ConvertToImage().SaveStream(output, wx.BITMAP_TYPE_PNG)
return output.getvalue()
else:
return
try:
current_thread.get_property("running_test_case_fixture").screen_shot = capture_screen()
except Exception as e:
plogger.warn("Failed to take the screenshot: \n%screen\n%screen" % (e.message, traceback.format_exc())) | Support capture screenshot for no-selenium test | Support capture screenshot for no-selenium test
| Python | apache-2.0 | KarlGong/ptest,KarlGong/ptest | import threading
import traceback
+ import StringIO
import plogger
+
+ try:
+ from PIL import ImageGrab
+ except ImportError:
+ PIL_installed = False
+ else:
+ PIL_installed = True
+
+ try:
+ import wx
+ except ImportError:
+ wxpython_installed = False
+ else:
+ wxpython_installed = True
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
- try:
+ def capture_screen():
- screen_shot = active_browser.get_screenshot_as_png()
+ return active_browser.get_screenshot_as_png()
- except Exception as e:
- plogger.warn("Failed to take the screenshot: \n%s\n%s" % (e.message, traceback.format_exc()))
+ elif PIL_installed:
+ def capture_screen():
+ output = StringIO.StringIO()
+ ImageGrab.grab().save(output, format="png")
+ return output.getvalue()
+ elif wxpython_installed:
+ def capture_screen():
+ app = wx.App(False)
+ screen = wx.ScreenDC()
+ width, height = screen.GetSize()
+ bmp = wx.EmptyBitmap(width, height)
+ mem = wx.MemoryDC(bmp)
+ mem.Blit(0, 0, width, height, screen, 0, 0)
+ output = StringIO.StringIO()
+ bmp.ConvertToImage().SaveStream(output, wx.BITMAP_TYPE_PNG)
+ return output.getvalue()
+ else:
- return
+ return
+ try:
- current_thread.get_property("running_test_case_fixture").screen_shot = screen_shot
+ current_thread.get_property("running_test_case_fixture").screen_shot = capture_screen()
+ except Exception as e:
+ plogger.warn("Failed to take the screenshot: \n%screen\n%screen" % (e.message, traceback.format_exc()))
-
- else:
- pass # todo: take screen shot for desktop | Support capture screenshot for no-selenium test | ## Code Before:
import threading
import traceback
import plogger
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
try:
screen_shot = active_browser.get_screenshot_as_png()
except Exception as e:
plogger.warn("Failed to take the screenshot: \n%s\n%s" % (e.message, traceback.format_exc()))
return
current_thread.get_property("running_test_case_fixture").screen_shot = screen_shot
else:
pass # todo: take screen shot for desktop
## Instruction:
Support capture screenshot for no-selenium test
## Code After:
import threading
import traceback
import StringIO
import plogger
try:
from PIL import ImageGrab
except ImportError:
PIL_installed = False
else:
PIL_installed = True
try:
import wx
except ImportError:
wxpython_installed = False
else:
wxpython_installed = True
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
def capture_screen():
return active_browser.get_screenshot_as_png()
elif PIL_installed:
def capture_screen():
output = StringIO.StringIO()
ImageGrab.grab().save(output, format="png")
return output.getvalue()
elif wxpython_installed:
def capture_screen():
app = wx.App(False)
screen = wx.ScreenDC()
width, height = screen.GetSize()
bmp = wx.EmptyBitmap(width, height)
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, width, height, screen, 0, 0)
output = StringIO.StringIO()
bmp.ConvertToImage().SaveStream(output, wx.BITMAP_TYPE_PNG)
return output.getvalue()
else:
return
try:
current_thread.get_property("running_test_case_fixture").screen_shot = capture_screen()
except Exception as e:
plogger.warn("Failed to take the screenshot: \n%screen\n%screen" % (e.message, traceback.format_exc())) | import threading
import traceback
+ import StringIO
import plogger
+
+ try:
+ from PIL import ImageGrab
+ except ImportError:
+ PIL_installed = False
+ else:
+ PIL_installed = True
+
+ try:
+ import wx
+ except ImportError:
+ wxpython_installed = False
+ else:
+ wxpython_installed = True
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch_to.alert.dismiss()
except Exception:
break
- try:
+ def capture_screen():
- screen_shot = active_browser.get_screenshot_as_png()
? -- ^ -------
+ return active_browser.get_screenshot_as_png()
? ^^^
- except Exception as e:
- plogger.warn("Failed to take the screenshot: \n%s\n%s" % (e.message, traceback.format_exc()))
+ elif PIL_installed:
+ def capture_screen():
+ output = StringIO.StringIO()
+ ImageGrab.grab().save(output, format="png")
+ return output.getvalue()
+ elif wxpython_installed:
+ def capture_screen():
+ app = wx.App(False)
+ screen = wx.ScreenDC()
+ width, height = screen.GetSize()
+ bmp = wx.EmptyBitmap(width, height)
+ mem = wx.MemoryDC(bmp)
+ mem.Blit(0, 0, width, height, screen, 0, 0)
+ output = StringIO.StringIO()
+ bmp.ConvertToImage().SaveStream(output, wx.BITMAP_TYPE_PNG)
+ return output.getvalue()
+ else:
- return
? ----
+ return
+ try:
- current_thread.get_property("running_test_case_fixture").screen_shot = screen_shot
? ^^^^^
+ current_thread.get_property("running_test_case_fixture").screen_shot = capture_screen()
? ++++++++ ^^
+ except Exception as e:
+ plogger.warn("Failed to take the screenshot: \n%screen\n%screen" % (e.message, traceback.format_exc()))
-
- else:
- pass # todo: take screen shot for desktop |
a07c3db369fec32507a7f51b96927bfe383597bc | tests/PexpectTestCase.py | tests/PexpectTestCase.py |
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print '\n', self.id(),
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
|
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
| Make test case base compatible with Python 3 | Make test case base compatible with Python 3
| Python | isc | Wakeupbuddy/pexpect,dongguangming/pexpect,nodish/pexpect,Depado/pexpect,bangi123/pexpect,bangi123/pexpect,Depado/pexpect,quatanium/pexpect,dongguangming/pexpect,bangi123/pexpect,nodish/pexpect,blink1073/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,dongguangming/pexpect,Wakeupbuddy/pexpect,crdoconnor/pexpect,blink1073/pexpect,quatanium/pexpect,crdoconnor/pexpect,Wakeupbuddy/pexpect,Depado/pexpect,nodish/pexpect,quatanium/pexpect,blink1073/pexpect,dongguangming/pexpect,bangi123/pexpect,crdoconnor/pexpect |
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
+ from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
- print '\n', self.id(),
+ print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
| Make test case base compatible with Python 3 | ## Code Before:
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print '\n', self.id(),
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
## Instruction:
Make test case base compatible with Python 3
## Code After:
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
|
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
+ from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
- print '\n', self.id(),
? ^
+ print('\n', self.id(), end='')
? ^ ++++++++
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
|
9eb07a5b7d2875cf79bb698864d11ef29576133e | comics/utils/hash.py | comics/utils/hash.py | import hashlib
def sha256sum(filename):
"""Returns sha256sum for file"""
f = file(filename, 'rb')
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
f.close()
return m.hexdigest()
| import hashlib
def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
if filename is not None:
f = file(filename, 'rb')
else:
f = filehandle
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
if filename is not None:
f.close()
return m.hexdigest()
| Make sha256sum work with open filehandles too | Make sha256sum work with open filehandles too
| Python | agpl-3.0 | datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics | import hashlib
- def sha256sum(filename):
+ def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
+ if filename is not None:
- f = file(filename, 'rb')
+ f = file(filename, 'rb')
+ else:
+ f = filehandle
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
+ if filename is not None:
- f.close()
+ f.close()
return m.hexdigest()
| Make sha256sum work with open filehandles too | ## Code Before:
import hashlib
def sha256sum(filename):
"""Returns sha256sum for file"""
f = file(filename, 'rb')
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
f.close()
return m.hexdigest()
## Instruction:
Make sha256sum work with open filehandles too
## Code After:
import hashlib
def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
if filename is not None:
f = file(filename, 'rb')
else:
f = filehandle
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
if filename is not None:
f.close()
return m.hexdigest()
| import hashlib
- def sha256sum(filename):
+ def sha256sum(filename=None, filehandle=None):
"""Returns sha256sum for file"""
+ if filename is not None:
- f = file(filename, 'rb')
+ f = file(filename, 'rb')
? ++++
+ else:
+ f = filehandle
m = hashlib.sha256()
while True:
b = f.read(8096)
if not b:
break
m.update(b)
+ if filename is not None:
- f.close()
+ f.close()
? ++++
return m.hexdigest() |
6a7fb1ff05202f60c7036db369926e3056372123 | tests/chainer_tests/functions_tests/math_tests/test_sqrt.py | tests/chainer_tests/functions_tests/math_tests/test_sqrt.py | import unittest
import numpy
import chainer.functions as F
from chainer import testing
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
#
# sqrt
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x, dtype=numpy.float32):
return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
# TODO(takagi) Fix test of rsqrt not to use this decorator.
@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
| import unittest
import numpy
import chainer.functions as F
from chainer import testing
#
# sqrt
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| Simplify test of rsqrt function. | Simplify test of rsqrt function.
| Python | mit | chainer/chainer,niboshi/chainer,hvy/chainer,hvy/chainer,anaruse/chainer,ktnyt/chainer,jnishi/chainer,pfnet/chainer,keisuke-umezawa/chainer,cupy/cupy,ysekky/chainer,kashif/chainer,keisuke-umezawa/chainer,ronekko/chainer,niboshi/chainer,wkentaro/chainer,cupy/cupy,kiyukuta/chainer,okuta/chainer,delta2323/chainer,hvy/chainer,ktnyt/chainer,keisuke-umezawa/chainer,niboshi/chainer,hvy/chainer,ktnyt/chainer,aonotas/chainer,rezoo/chainer,okuta/chainer,jnishi/chainer,cupy/cupy,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,wkentaro/chainer,niboshi/chainer,tkerola/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,wkentaro/chainer,chainer/chainer,cupy/cupy,chainer/chainer | import unittest
import numpy
import chainer.functions as F
from chainer import testing
+ #
+ # sqrt
+
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
-
- #
- # sqrt
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
- def rsqrt(x, dtype=numpy.float32):
+ def rsqrt(x):
- return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
+ return numpy.reciprocal(numpy.sqrt(x))
- # TODO(takagi) Fix test of rsqrt not to use this decorator.
- @testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
- pass
+
+ def test_rsqrt(self):
+ x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
+ testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| Simplify test of rsqrt function. | ## Code Before:
import unittest
import numpy
import chainer.functions as F
from chainer import testing
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
#
# sqrt
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x, dtype=numpy.float32):
return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
# TODO(takagi) Fix test of rsqrt not to use this decorator.
@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
## Instruction:
Simplify test of rsqrt function.
## Code After:
import unittest
import numpy
import chainer.functions as F
from chainer import testing
#
# sqrt
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| import unittest
import numpy
import chainer.functions as F
from chainer import testing
+ #
+ # sqrt
+
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
-
- #
- # sqrt
@testing.math_function_test(F.Sqrt(), make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
- def rsqrt(x, dtype=numpy.float32):
+ def rsqrt(x):
- return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
? -------------
+ return numpy.reciprocal(numpy.sqrt(x))
- # TODO(takagi) Fix test of rsqrt not to use this decorator.
- @testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
- pass
+
+ def test_rsqrt(self):
+ x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
+ testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__) |
e01b0c9129c05e366605639553201f0dc2af2756 | django_fsm_log/apps.py | django_fsm_log/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback)
| from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback)
| Revert "Solve warning coming from django 4.0" | Revert "Solve warning coming from django 4.0"
| Python | mit | gizmag/django-fsm-log,ticosax/django-fsm-log | from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
- default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback)
| Revert "Solve warning coming from django 4.0" | ## Code Before:
from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback)
## Instruction:
Revert "Solve warning coming from django 4.0"
## Code After:
from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback)
| from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
- default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD)
StateLog = self.get_model('StateLog')
backend.setup_model(StateLog)
pre_transition.connect(backend.pre_transition_callback)
post_transition.connect(backend.post_transition_callback) |
a08483b5fc55556b46c08e988ac297b1dffaed48 | app/utils/utilities.py | app/utils/utilities.py | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
| from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
| Implement HTTPTokenAuth Store user data in global | Implement HTTPTokenAuth
Store user data in global
| Python | mit | Elbertbiggs360/buckelist-api | from re import search
- from flask import g
+ from flask import g, request
- from flask_restplus import abort
- from flask_httpauth import HTTPBasicAuth
+ from flask_httpauth import HTTPTokenAuth
from app.models.user import User
- from instance.config import Config
- auth = HTTPBasicAuth()
+ auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
- ''' Method to check that a valid email is provided '''
+ ''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
- g.current_user = User.query.filter_by(id=user.id).first()
+ g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
| Implement HTTPTokenAuth Store user data in global | ## Code Before:
from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
## Instruction:
Implement HTTPTokenAuth Store user data in global
## Code After:
from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
| from re import search
- from flask import g
+ from flask import g, request
? +++++++++
- from flask_restplus import abort
- from flask_httpauth import HTTPBasicAuth
? ^^^^^
+ from flask_httpauth import HTTPTokenAuth
? ^^^^^
from app.models.user import User
- from instance.config import Config
- auth = HTTPBasicAuth()
+ auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
- ''' Method to check that a valid email is provided '''
? ^
+ ''' Method to check that a valid email is provided '''
? ^^^^
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
- g.current_user = User.query.filter_by(id=user.id).first()
? ^
+ g.current_user = User.query.filter_by(id=user_id).first()
? ^
return True
return False |
a8066d91dc0d1e37514de0623bf382b55abcf4c7 | esridump/cli.py | esridump/cli.py | import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
if not args.jsonlines:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
for feature in dumper.iter():
args.outfile.write(json.dumps(feature))
if not args.jsonlines:
args.outfile.write(',')
args.outfile.write('\n')
if not args.jsonlines:
# args.outfile.seek(-2)
args.outfile.write(']}')
if __name__ == '__main__':
main()
| import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
if args.jsonlines:
for feature in dumper.iter():
args.outfile.write(json.dumps(feature))
args.outfile.write('\n')
else:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
feature_iter = dumper.iter()
try:
feature = feature_iter.next()
while True:
args.outfile.write(json.dumps(feature))
feature = feature_iter.next()
args.outfile.write(',\n')
except StopIteration:
args.outfile.write('\n')
args.outfile.write(']}')
if __name__ == '__main__':
main()
| Remove the extra comma at the end. | Remove the extra comma at the end.
Fixes #7
| Python | mit | iandees/esri-dump,openaddresses/pyesridump | import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
- if not args.jsonlines:
+ if args.jsonlines:
+ for feature in dumper.iter():
+ args.outfile.write(json.dumps(feature))
+ args.outfile.write('\n')
+ else:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
-
- for feature in dumper.iter():
+ feature_iter = dumper.iter()
+ try:
+ feature = feature_iter.next()
+ while True:
- args.outfile.write(json.dumps(feature))
+ args.outfile.write(json.dumps(feature))
-
- if not args.jsonlines:
+ feature = feature_iter.next()
+ args.outfile.write(',\n')
+ except StopIteration:
- args.outfile.write(',')
+ args.outfile.write('\n')
- args.outfile.write('\n')
-
- if not args.jsonlines:
- # args.outfile.seek(-2)
args.outfile.write(']}')
if __name__ == '__main__':
main()
| Remove the extra comma at the end. | ## Code Before:
import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
if not args.jsonlines:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
for feature in dumper.iter():
args.outfile.write(json.dumps(feature))
if not args.jsonlines:
args.outfile.write(',')
args.outfile.write('\n')
if not args.jsonlines:
# args.outfile.seek(-2)
args.outfile.write(']}')
if __name__ == '__main__':
main()
## Instruction:
Remove the extra comma at the end.
## Code After:
import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
if args.jsonlines:
for feature in dumper.iter():
args.outfile.write(json.dumps(feature))
args.outfile.write('\n')
else:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
feature_iter = dumper.iter()
try:
feature = feature_iter.next()
while True:
args.outfile.write(json.dumps(feature))
feature = feature_iter.next()
args.outfile.write(',\n')
except StopIteration:
args.outfile.write('\n')
args.outfile.write(']}')
if __name__ == '__main__':
main()
| import argparse
import simplejson as json
from esridump.dumper import EsriDumper
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("outfile", type=argparse.FileType('w'))
parser.add_argument("--jsonlines", action='store_true', default=False)
args = parser.parse_args()
dumper = EsriDumper(args.url)
- if not args.jsonlines:
? ----
+ if args.jsonlines:
+ for feature in dumper.iter():
+ args.outfile.write(json.dumps(feature))
+ args.outfile.write('\n')
+ else:
args.outfile.write('{"type":"FeatureCollection","features":[\n')
-
- for feature in dumper.iter():
? ^^^ ^^ -
+ feature_iter = dumper.iter()
? ^^^ +++++ ^
+ try:
+ feature = feature_iter.next()
+ while True:
- args.outfile.write(json.dumps(feature))
+ args.outfile.write(json.dumps(feature))
? ++++++++
-
- if not args.jsonlines:
+ feature = feature_iter.next()
+ args.outfile.write(',\n')
+ except StopIteration:
- args.outfile.write(',')
? ^
+ args.outfile.write('\n')
? ^^
- args.outfile.write('\n')
-
- if not args.jsonlines:
- # args.outfile.seek(-2)
args.outfile.write(']}')
if __name__ == '__main__':
main() |
38d7092f07884cb2530f95a5dc24ba177bfbe699 | ncclient/operations/third_party/nexus/rpc.py | ncclient/operations/third_party/nexus/rpc.py | from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmd):
parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
child_node.text = cmd
return self._request(parent_node)
| from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
return self._request(node)
| Allow specifying multiple cmd elements | Allow specifying multiple cmd elements
| Python | apache-2.0 | nwautomator/ncclient,joysboy/ncclient,aitorhh/ncclient,ncclient/ncclient,vnitinv/ncclient,cmoberg/ncclient,earies/ncclient,einarnn/ncclient,leopoul/ncclient,kroustou/ncclient,lightlu/ncclient,nnakamot/ncclient,OpenClovis/ncclient,GIC-de/ncclient | from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
- def request(self, cmd):
+ def request(self, cmds):
- parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
+ node = etree.Element(qualify('exec-command', NXOS_1_0))
- child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
- child_node.text = cmd
- return self._request(parent_node)
+ for cmd in cmds:
+ etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
+
+ return self._request(node)
+ | Allow specifying multiple cmd elements | ## Code Before:
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmd):
parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
child_node.text = cmd
return self._request(parent_node)
## Instruction:
Allow specifying multiple cmd elements
## Code After:
from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
return self._request(node)
| from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
- def request(self, cmd):
+ def request(self, cmds):
? +
- parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
? -------
+ node = etree.Element(qualify('exec-command', NXOS_1_0))
+
+ for cmd in cmds:
- child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
? ---------- ^ -------
+ etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
? ^^ +++++++++++
- child_node.text = cmd
+
- return self._request(parent_node)
? -------
+ return self._request(node) |
4de72b4bd349ebf16c0046c4ed9034914c03ffb5 | cea/interfaces/dashboard/api/utils.py | cea/interfaces/dashboard/api/utils.py |
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params |
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p: cea.config.Parameter):
params = {'name': p.name, 'type': p.typename, 'help': p.help}
try:
params["value"] = p.get()
except cea.ConfigError as e:
print(e)
params["value"] = ""
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params | Fix `weather_helper` bug when creating new scenario | Fix `weather_helper` bug when creating new scenario
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst |
from flask import current_app
import cea.config
import cea.inputlocator
- def deconstruct_parameters(p):
+ def deconstruct_parameters(p: cea.config.Parameter):
- params = {'name': p.name, 'type': p.typename,
+ params = {'name': p.name, 'type': p.typename, 'help': p.help}
- 'value': p.get(), 'help': p.help}
+ try:
+ params["value"] = p.get()
+ except cea.ConfigError as e:
+ print(e)
+ params["value"] = ""
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params | Fix `weather_helper` bug when creating new scenario | ## Code Before:
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params
## Instruction:
Fix `weather_helper` bug when creating new scenario
## Code After:
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p: cea.config.Parameter):
params = {'name': p.name, 'type': p.typename, 'help': p.help}
try:
params["value"] = p.get()
except cea.ConfigError as e:
print(e)
params["value"] = ""
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params |
from flask import current_app
import cea.config
import cea.inputlocator
- def deconstruct_parameters(p):
+ def deconstruct_parameters(p: cea.config.Parameter):
- params = {'name': p.name, 'type': p.typename,
+ params = {'name': p.name, 'type': p.typename, 'help': p.help}
? ++++++++++++++++
- 'value': p.get(), 'help': p.help}
+ try:
+ params["value"] = p.get()
+ except cea.ConfigError as e:
+ print(e)
+ params["value"] = ""
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'WeatherPathParameter':
config = current_app.cea_config
locator = cea.inputlocator.InputLocator(config.scenario)
params['choices'] = {wn: locator.get_weather(
wn) for wn in locator.get_weather_names()}
elif p.typename == 'DatabasePathParameter':
params['choices'] = p._choices
return params |
5837df594f9c18ffe62e90dd4d6ba30fdde98dde | flaskbb/utils/database.py | flaskbb/utils/database.py | import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
# store naive datetime for sqlite
if dialect.name == "sqlite":
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
if dialect.name == "sqlite" and value is not None:
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value
| import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
# store naive datetime for sqlite and mysql
if dialect.name in ("sqlite", "mysql"):
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
if dialect.name in ("sqlite", "mysql") and value is not None:
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value
| Use the naive datetime format for MySQL as well | Use the naive datetime format for MySQL as well
See the SQLAlchemy docs for more information:
http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial
ects.mysql.DATETIME
| Python | bsd-3-clause | realityone/flaskbb,realityone/flaskbb,realityone/flaskbb | import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
- # store naive datetime for sqlite
+ # store naive datetime for sqlite and mysql
- if dialect.name == "sqlite":
+ if dialect.name in ("sqlite", "mysql"):
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
- if dialect.name == "sqlite" and value is not None:
+ if dialect.name in ("sqlite", "mysql") and value is not None:
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value
| Use the naive datetime format for MySQL as well | ## Code Before:
import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
# store naive datetime for sqlite
if dialect.name == "sqlite":
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
if dialect.name == "sqlite" and value is not None:
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value
## Instruction:
Use the naive datetime format for MySQL as well
## Code After:
import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
# store naive datetime for sqlite and mysql
if dialect.name in ("sqlite", "mysql"):
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
if dialect.name in ("sqlite", "mysql") and value is not None:
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value
| import pytz
from flaskbb.extensions import db
class CRUDMixin(object):
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def save(self):
"""Saves the object to the database."""
db.session.add(self)
db.session.commit()
return self
def delete(self):
"""Delete the object from the database."""
db.session.delete(self)
db.session.commit()
return self
class UTCDateTime(db.TypeDecorator):
impl = db.DateTime
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
- # store naive datetime for sqlite
+ # store naive datetime for sqlite and mysql
? ++++++++++
- if dialect.name == "sqlite":
? ^^
+ if dialect.name in ("sqlite", "mysql"):
? ^^ + ++++++++++
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, value, dialect):
"""Way out of the database."""
# convert naive datetime to non naive datetime
- if dialect.name == "sqlite" and value is not None:
? ^^
+ if dialect.name in ("sqlite", "mysql") and value is not None:
? ^^ + ++++++++++
return value.replace(tzinfo=pytz.UTC)
# other dialects are already non-naive
return value |
312bb90415218398ddbe9250cfe7dbc4bb013e14 | opal/core/lookuplists.py | opal/core/lookuplists.py | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
| from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| Delete commented out old code. | Delete commented out old code.
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
-
- # class LookupList(models.Model):
- # class Meta:
- # abstract = True
-
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
-
- # def lookup_list(name, module=__name__):
- # """
- # Given the name of a lookup list, return the tuple of class_name, bases, attrs
- # for the user to define the class
- # """
- # prefix = 'Lookup List: '
- # class_name = name.capitalize() # TODO handle camelcase properly
- # bases = (LookupList,)
- # attrs = {
- # 'name': models.CharField(max_length=255, unique=True),
- # 'synonyms': generic.GenericRelation('opal.Synonym'),
- # 'Meta': type('Meta', (object,), {'ordering': ['name'],
- # 'verbose_name': prefix+name}),
- # '__unicode__': lambda self: self.name,
- # '__module__': module,
- # }
- # return class_name, bases, attrs
- | Delete commented out old code. | ## Code Before:
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
## Instruction:
Delete commented out old code.
## Code After:
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
-
- # class LookupList(models.Model):
- # class Meta:
- # abstract = True
-
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
-
-
- # def lookup_list(name, module=__name__):
- # """
- # Given the name of a lookup list, return the tuple of class_name, bases, attrs
- # for the user to define the class
- # """
- # prefix = 'Lookup List: '
- # class_name = name.capitalize() # TODO handle camelcase properly
- # bases = (LookupList,)
- # attrs = {
- # 'name': models.CharField(max_length=255, unique=True),
- # 'synonyms': generic.GenericRelation('opal.Synonym'),
- # 'Meta': type('Meta', (object,), {'ordering': ['name'],
- # 'verbose_name': prefix+name}),
- # '__unicode__': lambda self: self.name,
- # '__module__': module,
- # }
- # return class_name, bases, attrs |
0668b59d8ec73e80976928706f96922605fe4f67 | tsserver/models.py | tsserver/models.py | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
| from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
| Remove integer ID in Telemetry model | Remove integer ID in Telemetry model
| Python | mit | m4tx/techswarm-server | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
- id = db.Column(db.Integer, primary_key=True)
+ timestamp = db.Column(db.DateTime, primary_key=True)
- timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
| Remove integer ID in Telemetry model | ## Code Before:
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
## Instruction:
Remove integer ID in Telemetry model
## Code After:
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
| from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
- id = db.Column(db.Integer, primary_key=True)
? ^ ^^ ^ -
+ timestamp = db.Column(db.DateTime, primary_key=True)
? + ^^^^^^^ ^^ ^^^
- timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure} |
15964c974220c88a1b2fbca353d4a11b180e2bd8 | _launch.py | _launch.py | from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
def Command(cmd):
def ex(application=''):
# print 'execute', cmd + application
send_command(cmd + application)
return Function(ex)
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None
| from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command, Command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None
| Refactor Command action to dragonglue.command | Refactor Command action to dragonglue.command
| Python | mit | drocco007/vox_commands | from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
- from dragonglue.command import send_command
+ from dragonglue.command import send_command, Command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
-
-
- def Command(cmd):
- def ex(application=''):
- # print 'execute', cmd + application
- send_command(cmd + application)
-
- return Function(ex)
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None
| Refactor Command action to dragonglue.command | ## Code Before:
from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
def Command(cmd):
def ex(application=''):
# print 'execute', cmd + application
send_command(cmd + application)
return Function(ex)
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None
## Instruction:
Refactor Command action to dragonglue.command
## Code After:
from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
from dragonglue.command import send_command, Command
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None
| from dragonfly import (Grammar, MappingRule, Choice, Text, Key, Function)
- from dragonglue.command import send_command
+ from dragonglue.command import send_command, Command
? +++++++++
grammar = Grammar("launch")
applications = {
'sublime': 'w-s',
'pycharm': 'w-d',
'chrome': 'w-f',
'logs': 'w-j',
'SQL': 'w-k',
'IPython': 'w-l',
'shell': 'w-semicolon',
'terminal': 'w-a',
# 'spotify': 'spotify /home/dan/bin/spotify',
}
# aliases
applications['charm'] = applications['pycharm']
applications['termie'] = applications['terminal']
-
-
- def Command(cmd):
- def ex(application=''):
- # print 'execute', cmd + application
- send_command(cmd + application)
-
- return Function(ex)
launch_rule = MappingRule(
name="launch",
mapping={
'Do run': Key('w-x'),
'get <application>': Key('%(application)s'),
# 're-browse': Key('w-F'),
'voice sync': Command('subl --command voice_sync'),
'(touch | refresh) multi-edit': Command('touch /home/drocco/source/voice/natlink/commands/_multiedit.py'),
},
extras=[
Choice('application', applications)
]
)
grammar.add_rule(launch_rule)
grammar.load()
def unload():
global grammar
if grammar: grammar.unload()
grammar = None |
dd2d5e96672fc7870434f030ca63f6d7111642f9 | resources/launchers/alfanousDesktop.py | resources/launchers/alfanousDesktop.py |
import alfanousDesktop.Gui
alfanousDesktop.Gui.main()
|
import sys
# The paths should be generated by setup script
sys.argv.extend(
'-i', '/usr/share/alfanous-indexes/',
'-l', '/usr/locale/',
'-c', '/usr/share/alfanous-config/')
from alfanousDesktop.Gui import *
main()
| Add resource paths to python launcher script (proxy) | Add resource paths to python launcher script (proxy)
Former-commit-id: 7d20874c43637f1236442333f60a88ec653f53f2 | Python | agpl-3.0 | muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous,muslih/alfanous |
- import alfanousDesktop.Gui
+ import sys
- alfanousDesktop.Gui.main()
+ # The paths should be generated by setup script
+ sys.argv.extend(
+ '-i', '/usr/share/alfanous-indexes/',
+ '-l', '/usr/locale/',
+ '-c', '/usr/share/alfanous-config/')
+ from alfanousDesktop.Gui import *
+
+ main()
+ | Add resource paths to python launcher script (proxy) | ## Code Before:
import alfanousDesktop.Gui
alfanousDesktop.Gui.main()
## Instruction:
Add resource paths to python launcher script (proxy)
## Code After:
import sys
# The paths should be generated by setup script
sys.argv.extend(
'-i', '/usr/share/alfanous-indexes/',
'-l', '/usr/locale/',
'-c', '/usr/share/alfanous-config/')
from alfanousDesktop.Gui import *
main()
|
- import alfanousDesktop.Gui
+ import sys
- alfanousDesktop.Gui.main()
+ # The paths should be generated by setup script
+ sys.argv.extend(
+ '-i', '/usr/share/alfanous-indexes/',
+ '-l', '/usr/locale/',
+ '-c', '/usr/share/alfanous-config/')
+
+ from alfanousDesktop.Gui import *
+
+ main() |
90a94b1d511aa17f167d783992fe0f874ad529c1 | examples/python_interop/python_interop.py | examples/python_interop/python_interop.py |
from __future__ import print_function
import legion
@legion.task
def f(ctx):
print("inside task f")
@legion.task
def main_task(ctx):
print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id)
f(ctx)
|
from __future__ import print_function
import legion
@legion.task
def f(ctx, *args):
print("inside task f%s" % (args,))
@legion.task
def main_task(ctx):
print("inside main()")
f(ctx, 1, "asdf", True)
| Test Python support for arguments. | examples: Test Python support for arguments.
| Python | apache-2.0 | StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion |
from __future__ import print_function
import legion
@legion.task
- def f(ctx):
+ def f(ctx, *args):
- print("inside task f")
+ print("inside task f%s" % (args,))
@legion.task
def main_task(ctx):
- print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id)
- f(ctx)
+ print("inside main()")
+ f(ctx, 1, "asdf", True)
| Test Python support for arguments. | ## Code Before:
from __future__ import print_function
import legion
@legion.task
def f(ctx):
print("inside task f")
@legion.task
def main_task(ctx):
print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id)
f(ctx)
## Instruction:
Test Python support for arguments.
## Code After:
from __future__ import print_function
import legion
@legion.task
def f(ctx, *args):
print("inside task f%s" % (args,))
@legion.task
def main_task(ctx):
print("inside main()")
f(ctx, 1, "asdf", True)
|
from __future__ import print_function
import legion
@legion.task
- def f(ctx):
+ def f(ctx, *args):
? +++++++
- print("inside task f")
+ print("inside task f%s" % (args,))
? ++ +++++++++ +
@legion.task
def main_task(ctx):
- print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id)
- f(ctx)
+ print("inside main()")
+ f(ctx, 1, "asdf", True) |
fdc0bb75271b90a31072f79b95283e1156d50181 | waffle/decorators.py | waffle/decorators.py | from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
if flag_name.startswith('!'):
active = is_active(request, flag_name[1:])
else:
active = is_active(request, flag_name)
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator
| from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
if flag_name.startswith('!'):
active = is_active(request, flag_name[1:])
else:
active = is_active(request, flag_name)
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator
| Make the decorator actually work again. | Make the decorator actually work again.
| Python | bsd-3-clause | isotoma/django-waffle,TwigWorld/django-waffle,rlr/django-waffle,webus/django-waffle,groovecoder/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,safarijv/django-waffle,paulcwatts/django-waffle,JeLoueMonCampingCar/django-waffle,11craft/django-waffle,festicket/django-waffle,styleseat/django-waffle,mark-adams/django-waffle,rodgomes/django-waffle,crccheck/django-waffle,mark-adams/django-waffle,webus/django-waffle,groovecoder/django-waffle,mwaaas/django-waffle-session,hwkns/django-waffle,VladimirFilonov/django-waffle,ekohl/django-waffle,festicket/django-waffle,paulcwatts/django-waffle,TwigWorld/django-waffle,mwaaas/django-waffle-session,VladimirFilonov/django-waffle,rlr/django-waffle,willkg/django-waffle,engagespark/django-waffle,hwkns/django-waffle,crccheck/django-waffle,JeLoueMonCampingCar/django-waffle,TwigWorld/django-waffle,hwkns/django-waffle,safarijv/django-waffle,webus/django-waffle,rodgomes/django-waffle,engagespark/django-waffle,safarijv/django-waffle,festicket/django-waffle,groovecoder/django-waffle,styleseat/django-waffle,mwaaas/django-waffle-session,mark-adams/django-waffle,paulcwatts/django-waffle,VladimirFilonov/django-waffle,webus/django-waffle,rlr/django-waffle,willkg/django-waffle,ilanbm/django-waffle,festicket/django-waffle,crccheck/django-waffle,rodgomes/django-waffle,ilanbm/django-waffle,ekohl/django-waffle,groovecoder/django-waffle,hwkns/django-waffle,isotoma/django-waffle,11craft/django-waffle,rlr/django-waffle,ilanbm/django-waffle,JeLoueMonCampingCar/django-waffle,isotoma/django-waffle,paulcwatts/django-waffle,VladimirFilonov/django-waffle,engagespark/django-waffle,engagespark/django-waffle,rsalmaso/django-waffle,styleseat/django-waffle,mark-adams/django-waffle,rsalmaso/django-waffle,isotoma/django-waffle,rsalmaso/django-waffle,rsalmaso/django-waffle,rodgomes/django-waffle,mwaaas/django-waffle-session,styleseat/django-waffle,ilanbm/django-waffle,safarijv/django-waffle | from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
- if flag_name.startswith('!'):
- active = is_active(request, flag_name[1:])
- else:
- active = is_active(request, flag_name)
-
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
+ if flag_name.startswith('!'):
+ active = is_active(request, flag_name[1:])
+ else:
+ active = is_active(request, flag_name)
+
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator
| Make the decorator actually work again. | ## Code Before:
from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
if flag_name.startswith('!'):
active = is_active(request, flag_name[1:])
else:
active = is_active(request, flag_name)
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator
## Instruction:
Make the decorator actually work again.
## Code After:
from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
if flag_name.startswith('!'):
active = is_active(request, flag_name[1:])
else:
active = is_active(request, flag_name)
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator
| from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
- if flag_name.startswith('!'):
- active = is_active(request, flag_name[1:])
- else:
- active = is_active(request, flag_name)
-
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
+ if flag_name.startswith('!'):
+ active = is_active(request, flag_name[1:])
+ else:
+ active = is_active(request, flag_name)
+
if not active:
raise Http404
return view(request, *args, **kwargs)
return _wrapped_view
return decorator |
7072389221f7e287328cecc695b93a77d04c69ba | tests/basecli_test.py | tests/basecli_test.py | from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
def test_init(self):
assert self.app.main(['ass2m_test', 'init']) in (0, None)
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
| from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
import sys
import re
from StringIO import StringIO
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
def beginCapture(self):
self.stdout = sys.stdout
# begin capture
sys.stdout = StringIO()
def endCapture(self):
captured = sys.stdout
# end capture
sys.stdout = self.stdout
self.stdout = None
return captured.getvalue()
def test_init(self):
self.beginCapture()
assert self.app.main(['ass2m_test', 'init']) in (0, None)
output = self.endCapture()
assert output.strip() == "Ass2m working directory created."
self.beginCapture()
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
output = self.endCapture()
assert re.match(re.escape(r'/')+r'\s+'+re.escape(r'all(rl-)'), output, re.S)
assert re.match(".+"+re.escape(r'/.ass2m/')+r'\s+'+re.escape(r'all(---)'), output, re.S)
| Test and capture the CLI output | Test and capture the CLI output
| Python | agpl-3.0 | laurentb/assnet,laurentb/assnet | from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
+ import sys
+ import re
+ from StringIO import StringIO
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
+ def beginCapture(self):
+ self.stdout = sys.stdout
+ # begin capture
+ sys.stdout = StringIO()
+
+ def endCapture(self):
+ captured = sys.stdout
+ # end capture
+ sys.stdout = self.stdout
+ self.stdout = None
+ return captured.getvalue()
+
def test_init(self):
+ self.beginCapture()
assert self.app.main(['ass2m_test', 'init']) in (0, None)
+ output = self.endCapture()
+ assert output.strip() == "Ass2m working directory created."
+ self.beginCapture()
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
+ output = self.endCapture()
+ assert re.match(re.escape(r'/')+r'\s+'+re.escape(r'all(rl-)'), output, re.S)
+ assert re.match(".+"+re.escape(r'/.ass2m/')+r'\s+'+re.escape(r'all(---)'), output, re.S)
| Test and capture the CLI output | ## Code Before:
from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
def test_init(self):
assert self.app.main(['ass2m_test', 'init']) in (0, None)
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
## Instruction:
Test and capture the CLI output
## Code After:
from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
import sys
import re
from StringIO import StringIO
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
def beginCapture(self):
self.stdout = sys.stdout
# begin capture
sys.stdout = StringIO()
def endCapture(self):
captured = sys.stdout
# end capture
sys.stdout = self.stdout
self.stdout = None
return captured.getvalue()
def test_init(self):
self.beginCapture()
assert self.app.main(['ass2m_test', 'init']) in (0, None)
output = self.endCapture()
assert output.strip() == "Ass2m working directory created."
self.beginCapture()
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
output = self.endCapture()
assert re.match(re.escape(r'/')+r'\s+'+re.escape(r'all(rl-)'), output, re.S)
assert re.match(".+"+re.escape(r'/.ass2m/')+r'\s+'+re.escape(r'all(---)'), output, re.S)
| from unittest import TestCase
from ass2m.cli import CLI
from tempfile import mkdtemp
import shutil
+ import sys
+ import re
+ from StringIO import StringIO
class BaseCLITest(TestCase):
def setUp(self):
self.root = mkdtemp(prefix='ass2m_test_root')
self.app = CLI(self.root)
def tearDown(self):
if self.root:
shutil.rmtree(self.root)
+ def beginCapture(self):
+ self.stdout = sys.stdout
+ # begin capture
+ sys.stdout = StringIO()
+
+ def endCapture(self):
+ captured = sys.stdout
+ # end capture
+ sys.stdout = self.stdout
+ self.stdout = None
+ return captured.getvalue()
+
def test_init(self):
+ self.beginCapture()
assert self.app.main(['ass2m_test', 'init']) in (0, None)
+ output = self.endCapture()
+ assert output.strip() == "Ass2m working directory created."
+ self.beginCapture()
assert self.app.main(['ass2m_test', 'tree']) in (0, None)
+ output = self.endCapture()
+ assert re.match(re.escape(r'/')+r'\s+'+re.escape(r'all(rl-)'), output, re.S)
+ assert re.match(".+"+re.escape(r'/.ass2m/')+r'\s+'+re.escape(r'all(---)'), output, re.S) |
1ae797e18286fd781797689a567f9d23ab3179d1 | modules/tools.py | modules/tools.py | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def has_expired(self):
return self.expired
| inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def restart(self):
self.expired = False
self.elapsed = 0
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def has_expired(self):
return self.expired
| Add a restart() method to Timer. | Add a restart() method to Timer.
| Python | mit | kxgames/kxg | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
-
- def register(self, callback):
- self.callbacks.append(callback)
-
- def unregister(self, callback):
- self.callbacks.remove(callback)
-
- def pause(self):
- self.paused = True
-
- def unpause(self):
- self.pause = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
+ def restart(self):
+ self.expired = False
+ self.elapsed = 0
+
+ def pause(self):
+ self.paused = True
+
+ def unpause(self):
+ self.pause = False
+
+ def register(self, callback):
+ self.callbacks.append(callback)
+
+ def unregister(self, callback):
+ self.callbacks.remove(callback)
+
def has_expired(self):
return self.expired
| Add a restart() method to Timer. | ## Code Before:
inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def has_expired(self):
return self.expired
## Instruction:
Add a restart() method to Timer.
## Code After:
inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def restart(self):
self.expired = False
self.elapsed = 0
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def has_expired(self):
return self.expired
| inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
-
- def register(self, callback):
- self.callbacks.append(callback)
-
- def unregister(self, callback):
- self.callbacks.remove(callback)
-
- def pause(self):
- self.paused = True
-
- def unpause(self):
- self.pause = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
+ def restart(self):
+ self.expired = False
+ self.elapsed = 0
+
+ def pause(self):
+ self.paused = True
+
+ def unpause(self):
+ self.pause = False
+
+ def register(self, callback):
+ self.callbacks.append(callback)
+
+ def unregister(self, callback):
+ self.callbacks.remove(callback)
+
def has_expired(self):
return self.expired
|
e31192cf4989c1cef481eb92d6a91ae99dd8e5f5 | src/pip/_internal/distributions/__init__.py | src/pip/_internal/distributions/__init__.py | from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
if install_req.link and install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req)
| from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
if install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req)
| Simplify conditional for choosing WheelDistribution | Simplify conditional for choosing WheelDistribution
| Python | mit | xavfernandez/pip,pradyunsg/pip,rouge8/pip,rouge8/pip,sbidoul/pip,sbidoul/pip,pypa/pip,pfmoore/pip,pradyunsg/pip,xavfernandez/pip,pfmoore/pip,xavfernandez/pip,pypa/pip,rouge8/pip | from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
- if install_req.link and install_req.is_wheel:
+ if install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req)
| Simplify conditional for choosing WheelDistribution | ## Code Before:
from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
if install_req.link and install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req)
## Instruction:
Simplify conditional for choosing WheelDistribution
## Code After:
from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
if install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req)
| from pip._internal.distributions.source import SourceDistribution
from pip._internal.distributions.wheel import WheelDistribution
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.req.req_install import InstallRequirement
def make_distribution_for_install_requirement(install_req):
# type: (InstallRequirement) -> AbstractDistribution
"""Returns a Distribution for the given InstallRequirement
"""
# If it's not an editable, is a wheel, it's a WheelDistribution
if install_req.editable:
return SourceDistribution(install_req)
- if install_req.link and install_req.is_wheel:
+ if install_req.is_wheel:
return WheelDistribution(install_req)
# Otherwise, a SourceDistribution
return SourceDistribution(install_req) |
19964dc65cecbbb043da3fe85bf355423cf9ce3c | shop/products/admin/forms.py | shop/products/admin/forms.py |
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
|
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
def save(self, commit=True):
product = super(ProductForm, self).save(commit)
if 'category' in self.changed_data:
product.attribute_values.all().delete()
return product
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
| Clear attr values on category change. | Clear attr values on category change.
| Python | isc | pmaigutyak/mp-shop,pmaigutyak/mp-shop,pmaigutyak/mp-shop |
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
+
+ def save(self, commit=True):
+ product = super(ProductForm, self).save(commit)
+
+ if 'category' in self.changed_data:
+ product.attribute_values.all().delete()
+
+ return product
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
| Clear attr values on category change. | ## Code Before:
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
## Instruction:
Clear attr values on category change.
## Code After:
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
def save(self, commit=True):
product = super(ProductForm, self).save(commit)
if 'category' in self.changed_data:
product.attribute_values.all().delete()
return product
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
|
from django.apps import apps
from django import forms
from suit.sortables import SortableTabularInline
from multiupload.fields import MultiFileField
class ProductForm(forms.ModelForm):
images = MultiFileField(max_num=100, min_num=1, required=False)
+ def save(self, commit=True):
+ product = super(ProductForm, self).save(commit)
+
+ if 'category' in self.changed_data:
+ product.attribute_values.all().delete()
+
+ return product
+
class Meta:
model = apps.get_model('products', 'Product')
fields = '__all__'
class ProductImageInline(SortableTabularInline):
fields = ('preview', )
readonly_fields = ['preview']
model = apps.get_model('products', 'ProductImage')
extra = 0
max_num = 0
|
09bf3b9883096e7a433508a6d6e03efad2a137df | httpavail.py | httpavail.py | import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
print('Checking', args.url)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
response.raise_for_status()
return response.status_code
if check() == 200:
sys.exit(0)
else:
sys.exit(1)
| import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
print('Checking', args.url, 'for HTTP code', args.status_code)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
if response.status_code != args.status_code:
raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code))
try:
check()
sys.exit(0)
except Exception as e:
print(str(e))
sys.exit(1)
| Make the expected HTTP status code configurable | Make the expected HTTP status code configurable
| Python | mit | ulich/docker-httpavail | import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
+ argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
- print('Checking', args.url)
+ print('Checking', args.url, 'for HTTP code', args.status_code)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
- response.raise_for_status()
- return response.status_code
+ if response.status_code != args.status_code:
+ raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code))
- if check() == 200:
+
+ try:
+ check()
sys.exit(0)
- else:
+ except Exception as e:
+ print(str(e))
sys.exit(1)
| Make the expected HTTP status code configurable | ## Code Before:
import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
print('Checking', args.url)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
response.raise_for_status()
return response.status_code
if check() == 200:
sys.exit(0)
else:
sys.exit(1)
## Instruction:
Make the expected HTTP status code configurable
## Code After:
import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
print('Checking', args.url, 'for HTTP code', args.status_code)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
if response.status_code != args.status_code:
raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code))
try:
check()
sys.exit(0)
except Exception as e:
print(str(e))
sys.exit(1)
| import sys, requests, argparse
from retrying import retry
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
argparser.add_argument('url')
argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available')
argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry')
+ argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code')
args = argparser.parse_args()
@retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000)
def check():
- print('Checking', args.url)
+ print('Checking', args.url, 'for HTTP code', args.status_code)
sys.stdout.flush()
response = requests.get(args.url, timeout = 1)
- response.raise_for_status()
- return response.status_code
+ if response.status_code != args.status_code:
+ raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code))
- if check() == 200:
+
+ try:
+ check()
sys.exit(0)
- else:
+ except Exception as e:
+ print(str(e))
sys.exit(1) |
323cc3f50fa0bbd072bfe243443adf12e1b25220 | bluebottle/projects/migrations/0019_auto_20170118_1537.py | bluebottle/projects/migrations/0019_auto_20170118_1537.py | from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
]
operations = [
migrations.RunPython(create_auth_token)
]
| from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
('quotes', '0005_auto_20180717_1017'),
('slides', '0006_auto_20180717_1017'),
]
operations = [
migrations.RunPython(create_auth_token)
]
| Add dependency on different migrations | Add dependency on different migrations
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
+ ('quotes', '0005_auto_20180717_1017'),
+ ('slides', '0006_auto_20180717_1017'),
]
operations = [
migrations.RunPython(create_auth_token)
]
| Add dependency on different migrations | ## Code Before:
from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
]
operations = [
migrations.RunPython(create_auth_token)
]
## Instruction:
Add dependency on different migrations
## Code After:
from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
('quotes', '0005_auto_20180717_1017'),
('slides', '0006_auto_20180717_1017'),
]
operations = [
migrations.RunPython(create_auth_token)
]
| from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_model('members', 'member')
Token = apps.get_model('authtoken', 'token')
member = Member.objects.create(
email='devteam+accounting@onepercentclub.com',
username='accounting'
)
token = Token.objects.create(
user=member,
key=generate_key()
)
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
+ ('quotes', '0005_auto_20180717_1017'),
+ ('slides', '0006_auto_20180717_1017'),
]
operations = [
migrations.RunPython(create_auth_token)
] |
0f49230309ac115ff78eddd36bcd153d7f3b75ea | data_aggregator/threads.py | data_aggregator/threads.py | import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
# run next job
job = next(values_iter)
thread.run(func, job, self.mp_queue)
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False
| import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
# run thread with the next value
value = next(values_iter)
thread.run(func, value, self.mp_queue)
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False
| Remove reference to "job" from ThreadPool | Remove reference to "job" from ThreadPool
| Python | apache-2.0 | uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics | import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
- # run next job
+ # run thread with the next value
- job = next(values_iter)
+ value = next(values_iter)
- thread.run(func, job, self.mp_queue)
+ thread.run(func, value, self.mp_queue)
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False
| Remove reference to "job" from ThreadPool | ## Code Before:
import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
# run next job
job = next(values_iter)
thread.run(func, job, self.mp_queue)
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False
## Instruction:
Remove reference to "job" from ThreadPool
## Code After:
import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
# run thread with the next value
value = next(values_iter)
thread.run(func, value, self.mp_queue)
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False
| import queue
import threading
from multiprocessing import Queue
class ThreadPool():
def __init__(self, processes=20):
self.processes = processes
self.threads = [Thread() for _ in range(0, processes)]
self.mp_queue = Queue()
def yield_dead_threads(self):
for thread in self.threads:
if not thread.is_alive():
yield thread
def map(self, func, values):
completed_count = 0
values_iter = iter(values)
while completed_count < len(values):
try:
self.mp_queue.get_nowait()
completed_count += 1
except queue.Empty:
pass
for thread in self.yield_dead_threads():
try:
- # run next job
+ # run thread with the next value
- job = next(values_iter)
? ^^^
+ value = next(values_iter)
? ^^^^^
- thread.run(func, job, self.mp_queue)
? ^^^
+ thread.run(func, value, self.mp_queue)
? ^^^^^
except StopIteration:
break
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
class Thread():
def __init__(self):
self.thread = None
def run(self, target, *args, **kwargs):
self.thread = threading.Thread(target=target,
args=args,
kwargs=kwargs)
self.thread.start()
def is_alive(self):
if self.thread:
return self.thread.is_alive()
else:
return False |
2301b0bfdb216f31428e6c9ca0bf6b2951a5e64b | symposion/forms.py | symposion/forms.py | from django import forms
import account.forms
class SignupForm(account.forms.SignupForm):
first_name = forms.CharField()
last_name = forms.CharField()
email_confirm = forms.EmailField(label="Confirm Email")
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
del self.fields["username"]
self.fields.keyOrder = [
"email",
"email_confirm",
"first_name",
"last_name",
"password",
"password_confirm"
]
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm
| try:
from collections import OrderedDict
except ImportError:
OrderedDict = None
import account.forms
from django import forms
from django.utils.translation import ugettext_lazy as _
class SignupForm(account.forms.SignupForm):
first_name = forms.CharField(label=_("First name"))
last_name = forms.CharField(label=_("Last name"))
email_confirm = forms.EmailField(label=_("Confirm Email"))
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
field_order = [
"first_name",
"last_name",
"email",
"email_confirm",
"password",
"password_confirm"
]
del self.fields["username"]
if not OrderedDict or hasattr(self.fields, "keyOrder"):
self.fields.keyOrder = field_order
else:
self.fields = OrderedDict((k, self.fields[k]) for k in field_order)
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm
| Fix order fields in signup form | Fix order fields in signup form
| Python | bsd-3-clause | toulibre/symposion,toulibre/symposion | - from django import forms
+ try:
+ from collections import OrderedDict
+ except ImportError:
+ OrderedDict = None
import account.forms
+ from django import forms
+ from django.utils.translation import ugettext_lazy as _
class SignupForm(account.forms.SignupForm):
- first_name = forms.CharField()
+ first_name = forms.CharField(label=_("First name"))
- last_name = forms.CharField()
+ last_name = forms.CharField(label=_("Last name"))
- email_confirm = forms.EmailField(label="Confirm Email")
+ email_confirm = forms.EmailField(label=_("Confirm Email"))
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
- del self.fields["username"]
- self.fields.keyOrder = [
+ field_order = [
+ "first_name",
+ "last_name",
"email",
"email_confirm",
- "first_name",
- "last_name",
"password",
"password_confirm"
]
+ del self.fields["username"]
+ if not OrderedDict or hasattr(self.fields, "keyOrder"):
+ self.fields.keyOrder = field_order
+ else:
+ self.fields = OrderedDict((k, self.fields[k]) for k in field_order)
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm
| Fix order fields in signup form | ## Code Before:
from django import forms
import account.forms
class SignupForm(account.forms.SignupForm):
first_name = forms.CharField()
last_name = forms.CharField()
email_confirm = forms.EmailField(label="Confirm Email")
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
del self.fields["username"]
self.fields.keyOrder = [
"email",
"email_confirm",
"first_name",
"last_name",
"password",
"password_confirm"
]
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm
## Instruction:
Fix order fields in signup form
## Code After:
try:
from collections import OrderedDict
except ImportError:
OrderedDict = None
import account.forms
from django import forms
from django.utils.translation import ugettext_lazy as _
class SignupForm(account.forms.SignupForm):
first_name = forms.CharField(label=_("First name"))
last_name = forms.CharField(label=_("Last name"))
email_confirm = forms.EmailField(label=_("Confirm Email"))
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
field_order = [
"first_name",
"last_name",
"email",
"email_confirm",
"password",
"password_confirm"
]
del self.fields["username"]
if not OrderedDict or hasattr(self.fields, "keyOrder"):
self.fields.keyOrder = field_order
else:
self.fields = OrderedDict((k, self.fields[k]) for k in field_order)
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm
| - from django import forms
+ try:
+ from collections import OrderedDict
+ except ImportError:
+ OrderedDict = None
import account.forms
+ from django import forms
+ from django.utils.translation import ugettext_lazy as _
class SignupForm(account.forms.SignupForm):
- first_name = forms.CharField()
+ first_name = forms.CharField(label=_("First name"))
? ++++++++++++++++++++ +
- last_name = forms.CharField()
+ last_name = forms.CharField(label=_("Last name"))
? +++++++++++++++++++ +
- email_confirm = forms.EmailField(label="Confirm Email")
+ email_confirm = forms.EmailField(label=_("Confirm Email"))
? ++ +
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
- del self.fields["username"]
- self.fields.keyOrder = [
? ----- ^^^^^^
+ field_order = [
? ^^
+ "first_name",
+ "last_name",
"email",
"email_confirm",
- "first_name",
- "last_name",
"password",
"password_confirm"
]
+ del self.fields["username"]
+ if not OrderedDict or hasattr(self.fields, "keyOrder"):
+ self.fields.keyOrder = field_order
+ else:
+ self.fields = OrderedDict((k, self.fields[k]) for k in field_order)
def clean_email_confirm(self):
email = self.cleaned_data.get("email")
email_confirm = self.cleaned_data["email_confirm"]
if email:
if email != email_confirm:
raise forms.ValidationError(
"Email address must match previously typed email address")
return email_confirm |
887ad6280df9c6e88a036783097f87626436ca9f | Lib/importlib/test/import_/util.py | Lib/importlib/test/import_/util.py | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
| import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
| Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later. | Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
+ def importlib_only(fxn):
+ """Decorator to skip a test if using __builtins__.__import__."""
- importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
+ return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
| Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later. | ## Code Before:
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
## Instruction:
Fix the importlib_only test decorator to work again; don't capture the flag variable as it might change later.
## Code After:
import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook
| import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
+ def importlib_only(fxn):
+ """Decorator to skip a test if using __builtins__.__import__."""
- importlib_only = unittest.skipIf(using___import__, "importlib-specific test")
? ^^^^ ^^^^^ ----
+ return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
? ^^^^ + ^^ +++++
def mock_path_hook(*entries, importer):
"""A mock sys.path_hooks entry."""
def hook(entry):
if entry not in entries:
raise ImportError
return importer
return hook |
984d8626a146770fe93d54ae107cd33dc3d2f481 | dbmigrator/commands/init_schema_migrations.py | dbmigrator/commands/init_schema_migrations.py |
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
| Add "applied" timestamp to schema migrations table | Add "applied" timestamp to schema migrations table
| Python | agpl-3.0 | karenc/db-migrator |
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
- version TEXT NOT NULL
+ version TEXT NOT NULL,
+ applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
| Add "applied" timestamp to schema migrations table | ## Code Before:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
## Instruction:
Add "applied" timestamp to schema migrations table
## Code After:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
- version TEXT NOT NULL
+ version TEXT NOT NULL,
? +
+ applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command |
94b6b97dc1e706a6560092aa29cbe4e21f052924 | froide/account/apps.py | froide/account/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
menu_registry.register(get_settings_menu_item)
menu_registry.register(get_request_menu_item)
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
def get_request_menu_item(request):
return MenuItem(
section='before_request', order=999,
url=reverse('account-show'),
label=_('My requests')
)
def get_settings_menu_item(request):
return MenuItem(
section='after_settings', order=-1,
url=reverse('account-settings'),
label=_('Settings')
)
| Make settings and requests menu items | Make settings and requests menu items | Python | mit | fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
+ from django.urls import reverse
+
+ from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
+ menu_registry.register(get_settings_menu_item)
+ menu_registry.register(get_request_menu_item)
+
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
+
+ def get_request_menu_item(request):
+ return MenuItem(
+ section='before_request', order=999,
+ url=reverse('account-show'),
+ label=_('My requests')
+ )
+
+
+ def get_settings_menu_item(request):
+ return MenuItem(
+ section='after_settings', order=-1,
+ url=reverse('account-settings'),
+ label=_('Settings')
+ )
+ | Make settings and requests menu items | ## Code Before:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
## Instruction:
Make settings and requests menu items
## Code After:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
menu_registry.register(get_settings_menu_item)
menu_registry.register(get_request_menu_item)
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
def get_request_menu_item(request):
return MenuItem(
section='before_request', order=999,
url=reverse('account-show'),
label=_('My requests')
)
def get_settings_menu_item(request):
return MenuItem(
section='after_settings', order=-1,
url=reverse('account-settings'),
label=_('Settings')
)
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
+ from django.urls import reverse
+
+ from .menu import menu_registry, MenuItem
class AccountConfig(AppConfig):
name = 'froide.account'
verbose_name = _("Account")
def ready(self):
from froide.bounce.signals import user_email_bounced
user_email_bounced.connect(deactivate_user_after_bounce)
+ menu_registry.register(get_settings_menu_item)
+ menu_registry.register(get_request_menu_item)
+
def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs):
if not should_deactivate:
return
if not bounce.user:
return
bounce.user.deactivate()
+
+
+ def get_request_menu_item(request):
+ return MenuItem(
+ section='before_request', order=999,
+ url=reverse('account-show'),
+ label=_('My requests')
+ )
+
+
+ def get_settings_menu_item(request):
+ return MenuItem(
+ section='after_settings', order=-1,
+ url=reverse('account-settings'),
+ label=_('Settings')
+ ) |
b344d63ad3ff7abff0772a744e951d5d5c8438f3 | carepoint/models/address_mixin.py | carepoint/models/address_mixin.py |
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
| Add ForeignKey on addr_id in carepoint cph address model | Add ForeignKey on addr_id in carepoint cph address model
| Python | mit | laslabs/Python-Carepoint |
from sqlalchemy import (Column,
Integer,
DateTime,
+ ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
- addr_id = Column(Integer, primary_key=True)
+ addr_id = Column(
+ Integer,
+ ForeignKey('csaddr.addr_id'),
+ primary_key=True,
+ )
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
| Add ForeignKey on addr_id in carepoint cph address model | ## Code Before:
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
## Instruction:
Add ForeignKey on addr_id in carepoint cph address model
## Code After:
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
from sqlalchemy import (Column,
Integer,
DateTime,
+ ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
- addr_id = Column(Integer, primary_key=True)
+ addr_id = Column(
+ Integer,
+ ForeignKey('csaddr.addr_id'),
+ primary_key=True,
+ )
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime) |
00c28d76d93331d7a501f0006cbadcaef48e499f | d1lod/tests/conftest.py | d1lod/tests/conftest.py | import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
return sesame.Repository(store, 'test')
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo)
| import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
namespaces = {
'owl': 'http://www.w3.org/2002/07/owl#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'xsd': 'http://www.w3.org/2001/XMLSchema#',
'foaf': 'http://xmlns.com/foaf/0.1/',
'dcterms': 'http://purl.org/dc/terms/',
'datacite': 'http://purl.org/spar/datacite/',
'glbase': 'http://schema.geolink.org/',
'd1dataset': 'http://lod.dataone.org/dataset/',
'd1person': 'http://lod.dataone.org/person/',
'd1org': 'http://lod.dataone.org/organization/',
'd1node': 'https://cn.dataone.org/cn/v1/node/',
'd1landing': 'https://search.dataone.org/#view/',
"prov": "http://www.w3.org/ns/prov#"
}
repository = sesame.Repository(store, 'test', ns=namespaces)
return repository
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo)
| Add default set of namespaces to test repository instance | Add default set of namespaces to test repository instance
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod | import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
+ namespaces = {
+ 'owl': 'http://www.w3.org/2002/07/owl#',
+ 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
+ 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
+ 'xsd': 'http://www.w3.org/2001/XMLSchema#',
+ 'foaf': 'http://xmlns.com/foaf/0.1/',
+ 'dcterms': 'http://purl.org/dc/terms/',
+ 'datacite': 'http://purl.org/spar/datacite/',
+ 'glbase': 'http://schema.geolink.org/',
+ 'd1dataset': 'http://lod.dataone.org/dataset/',
+ 'd1person': 'http://lod.dataone.org/person/',
+ 'd1org': 'http://lod.dataone.org/organization/',
+ 'd1node': 'https://cn.dataone.org/cn/v1/node/',
+ 'd1landing': 'https://search.dataone.org/#view/',
+ "prov": "http://www.w3.org/ns/prov#"
+ }
+
- return sesame.Repository(store, 'test')
+ repository = sesame.Repository(store, 'test', ns=namespaces)
+
+ return repository
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo)
| Add default set of namespaces to test repository instance | ## Code Before:
import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
return sesame.Repository(store, 'test')
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo)
## Instruction:
Add default set of namespaces to test repository instance
## Code After:
import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
namespaces = {
'owl': 'http://www.w3.org/2002/07/owl#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'xsd': 'http://www.w3.org/2001/XMLSchema#',
'foaf': 'http://xmlns.com/foaf/0.1/',
'dcterms': 'http://purl.org/dc/terms/',
'datacite': 'http://purl.org/spar/datacite/',
'glbase': 'http://schema.geolink.org/',
'd1dataset': 'http://lod.dataone.org/dataset/',
'd1person': 'http://lod.dataone.org/person/',
'd1org': 'http://lod.dataone.org/organization/',
'd1node': 'https://cn.dataone.org/cn/v1/node/',
'd1landing': 'https://search.dataone.org/#view/',
"prov": "http://www.w3.org/ns/prov#"
}
repository = sesame.Repository(store, 'test', ns=namespaces)
return repository
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo)
| import pytest
from d1lod import sesame
@pytest.fixture(scope="module")
def store():
return sesame.Store('localhost', 8080)
@pytest.fixture(scope="module")
def repo(store):
+ namespaces = {
+ 'owl': 'http://www.w3.org/2002/07/owl#',
+ 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
+ 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
+ 'xsd': 'http://www.w3.org/2001/XMLSchema#',
+ 'foaf': 'http://xmlns.com/foaf/0.1/',
+ 'dcterms': 'http://purl.org/dc/terms/',
+ 'datacite': 'http://purl.org/spar/datacite/',
+ 'glbase': 'http://schema.geolink.org/',
+ 'd1dataset': 'http://lod.dataone.org/dataset/',
+ 'd1person': 'http://lod.dataone.org/person/',
+ 'd1org': 'http://lod.dataone.org/organization/',
+ 'd1node': 'https://cn.dataone.org/cn/v1/node/',
+ 'd1landing': 'https://search.dataone.org/#view/',
+ "prov": "http://www.w3.org/ns/prov#"
+ }
+
- return sesame.Repository(store, 'test')
? ^ ^
+ repository = sesame.Repository(store, 'test', ns=namespaces)
? ++++ ^ ^^^ +++++++++++++++
+
+ return repository
@pytest.fixture(scope="module")
def interface(repo):
return sesame.Interface(repo) |
1118541b1cdea7f6079bb63d000ba54f69dfa119 | books/views.py | books/views.py | from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
data = form.cleaned_data
models.Receipt.objects.create(title=data.get("title"),
price=data.get("price"),
user=request.user)
return HttpResponseRedirect(reverse('receipt_list',
args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form})
| from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect(reverse('receipt_list', args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form})
| Use form.save for receipt creation | Use form.save for receipt creation
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance | from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
- from django.http import HttpResponseRedirect
+ from django.shortcuts import redirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
+ form.instance.user = request.user
+ form.save()
+ return redirect(reverse('receipt_list', args=[request.user.id]))
- data = form.cleaned_data
- models.Receipt.objects.create(title=data.get("title"),
- price=data.get("price"),
- user=request.user)
- return HttpResponseRedirect(reverse('receipt_list',
- args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form})
| Use form.save for receipt creation | ## Code Before:
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
data = form.cleaned_data
models.Receipt.objects.create(title=data.get("title"),
price=data.get("price"),
user=request.user)
return HttpResponseRedirect(reverse('receipt_list',
args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form})
## Instruction:
Use form.save for receipt creation
## Code After:
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect(reverse('receipt_list', args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form})
| from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
- from django.http import HttpResponseRedirect
+ from django.shortcuts import redirect
from django.shortcuts import render
from books import models
from books import forms
@login_required
def receipt_list(request, user_id):
user = User.objects.get(id=user_id)
ctx = {}
ctx['user'] = user
ctx['receipts'] = models.Receipt.objects.filter(user=user).order_by('-id')
return render(request, 'receipt_list.html', context=ctx)
@login_required
def receipt_create(request, user_id):
if request.method == "POST":
form = forms.ReceiptForm(request.POST)
if form.is_valid():
+ form.instance.user = request.user
+ form.save()
+ return redirect(reverse('receipt_list', args=[request.user.id]))
- data = form.cleaned_data
- models.Receipt.objects.create(title=data.get("title"),
- price=data.get("price"),
- user=request.user)
- return HttpResponseRedirect(reverse('receipt_list',
- args=[request.user.id]))
else:
form = forms.ReceiptForm()
return render(request, 'receipt_create.html', {'form': form}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.