commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 0 2.94k | new_contents stringlengths 1 4.43k | subject stringlengths 15 444 | message stringlengths 16 3.45k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 5 43.2k | prompt stringlengths 17 4.58k | response stringlengths 1 4.43k | prompt_tagged stringlengths 58 4.62k | response_tagged stringlengths 1 4.43k | text stringlengths 132 7.29k | text_tagged stringlengths 173 7.33k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6de5612c0e92b4e7c7ca56b59d7fd5859aeb3409 | apps/polls/urls.py | apps/polls/urls.py | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.detail, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) | Use generic views: Less code is better | Use generic views: Less code is better
| Python | bsd-3-clause | hoale/teracy-tutorial,hoale/teracy-tutorial | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)Use generic views: Less code is better | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.detail, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) | <commit_before>from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)<commit_msg>Use generic views: Less code is better<commit_after> | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.detail, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) | from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)Use generic views: Less code is betterfrom django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.detail, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) | <commit_before>from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)<commit_msg>Use generic views: Less code is better<commit_after>from django.conf.urls import patterns, url
from apps.polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5
url(r'^(?P<poll_id>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.detail, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
) |
8849f78d8e9d63942162264d4223e9db277142d7 | aligot/tests/test_user.py | aligot/tests/test_user.py | # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
| # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
def test_delete(self):
"""
Simple deletion of an user in DB
Wait for 204 response.
"""
user = User.objects.create_user(
username='test',
password='test',
email='mail@mail.com'
)
self.client.force_authenticate(user=user)
self.assertEqual(1, User.objects.count(), 'ORM don\'t insert user in DB')
response = self.client.delete(reverse('user-detail', args=[user.id]))
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content) | Add test to delete user in DB | Add test to delete user in DB
| Python | mit | aligot-project/aligot,aligot-project/aligot,aligot-project/aligot,skitoo/aligot | # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
Add test to delete user in DB | # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
def test_delete(self):
"""
Simple deletion of an user in DB
Wait for 204 response.
"""
user = User.objects.create_user(
username='test',
password='test',
email='mail@mail.com'
)
self.client.force_authenticate(user=user)
self.assertEqual(1, User.objects.count(), 'ORM don\'t insert user in DB')
response = self.client.delete(reverse('user-detail', args=[user.id]))
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content) | <commit_before># coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
<commit_msg>Add test to delete user in DB<commit_after> | # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
def test_delete(self):
"""
Simple deletion of an user in DB
Wait for 204 response.
"""
user = User.objects.create_user(
username='test',
password='test',
email='mail@mail.com'
)
self.client.force_authenticate(user=user)
self.assertEqual(1, User.objects.count(), 'ORM don\'t insert user in DB')
response = self.client.delete(reverse('user-detail', args=[user.id]))
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content) | # coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
Add test to delete user in DB# coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
def test_delete(self):
"""
Simple deletion of an user in DB
Wait for 204 response.
"""
user = User.objects.create_user(
username='test',
password='test',
email='mail@mail.com'
)
self.client.force_authenticate(user=user)
self.assertEqual(1, User.objects.count(), 'ORM don\'t insert user in DB')
response = self.client.delete(reverse('user-detail', args=[user.id]))
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content) | <commit_before># coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
<commit_msg>Add test to delete user in DB<commit_after># coding: utf-8
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from ..models import User
class TestUser(TestCase):
def setUp(self):
self.client = APIClient()
def test_create_without_params(self):
self.assertEquals(status.HTTP_400_BAD_REQUEST, self.client.post(reverse('user-create')).status_code)
self.assertEquals(0, User.objects.count())
def test_create(self):
"""
Create user & wait for 201 response.
"""
data = {
'username': 'test',
'password': 'test',
'email': 'test@mail.com'
}
response = self.client.post(reverse('user-create'), data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.content)
self.assertEqual(1, User.objects.count())
# Check the first
user = User.objects.all()[0]
self.assertEqual(user.username, data['username'], 'Username in DB don\'t match')
def test_delete(self):
"""
Simple deletion of an user in DB
Wait for 204 response.
"""
user = User.objects.create_user(
username='test',
password='test',
email='mail@mail.com'
)
self.client.force_authenticate(user=user)
self.assertEqual(1, User.objects.count(), 'ORM don\'t insert user in DB')
response = self.client.delete(reverse('user-detail', args=[user.id]))
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content) |
55e0c877dbe1a073534c9cf445ffe58715160b8e | metadata/RomsLite/hooks/post-stage.py | metadata/RomsLite/hooks/post-stage.py | import os
import shutil
from wmt.utils.hook import find_simulation_input_file
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in ('river_forcing_file', 'waves_forcing_file'):
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
| import os
import shutil
from wmt.utils.hook import find_simulation_input_file
_DEFAULT_FILES = {
'river_forcing_file': 'river.nc',
'waves_forcing_file': 'waves.nc',
}
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in _DEFAULT_FILES:
if env[name] != _DEFAULT_FILES[name]:
try:
os.remove(os.path.join(os.curdir, 'Forcing', env[name]))
except OSError:
pass
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
| Remove default forcing files if not being used. | Remove default forcing files if not being used.
| Python | mit | csdms/wmt-metadata | import os
import shutil
from wmt.utils.hook import find_simulation_input_file
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in ('river_forcing_file', 'waves_forcing_file'):
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
Remove default forcing files if not being used. | import os
import shutil
from wmt.utils.hook import find_simulation_input_file
_DEFAULT_FILES = {
'river_forcing_file': 'river.nc',
'waves_forcing_file': 'waves.nc',
}
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in _DEFAULT_FILES:
if env[name] != _DEFAULT_FILES[name]:
try:
os.remove(os.path.join(os.curdir, 'Forcing', env[name]))
except OSError:
pass
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
| <commit_before>import os
import shutil
from wmt.utils.hook import find_simulation_input_file
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in ('river_forcing_file', 'waves_forcing_file'):
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
<commit_msg>Remove default forcing files if not being used.<commit_after> | import os
import shutil
from wmt.utils.hook import find_simulation_input_file
_DEFAULT_FILES = {
'river_forcing_file': 'river.nc',
'waves_forcing_file': 'waves.nc',
}
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in _DEFAULT_FILES:
if env[name] != _DEFAULT_FILES[name]:
try:
os.remove(os.path.join(os.curdir, 'Forcing', env[name]))
except OSError:
pass
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
| import os
import shutil
from wmt.utils.hook import find_simulation_input_file
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in ('river_forcing_file', 'waves_forcing_file'):
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
Remove default forcing files if not being used.import os
import shutil
from wmt.utils.hook import find_simulation_input_file
_DEFAULT_FILES = {
'river_forcing_file': 'river.nc',
'waves_forcing_file': 'waves.nc',
}
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in _DEFAULT_FILES:
if env[name] != _DEFAULT_FILES[name]:
try:
os.remove(os.path.join(os.curdir, 'Forcing', env[name]))
except OSError:
pass
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
| <commit_before>import os
import shutil
from wmt.utils.hook import find_simulation_input_file
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in ('river_forcing_file', 'waves_forcing_file'):
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
<commit_msg>Remove default forcing files if not being used.<commit_after>import os
import shutil
from wmt.utils.hook import find_simulation_input_file
_DEFAULT_FILES = {
'river_forcing_file': 'river.nc',
'waves_forcing_file': 'waves.nc',
}
def execute(env):
"""Perform post-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
for name in _DEFAULT_FILES:
if env[name] != _DEFAULT_FILES[name]:
try:
os.remove(os.path.join(os.curdir, 'Forcing', env[name]))
except OSError:
pass
src = find_simulation_input_file(env[name])
shutil.copy(src, os.path.join(os.curdir, 'Forcing'))
|
6d68d07f30f2244b13207c6eaf9d4662492b04e2 | run.py | run.py | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| Change indentation tab to spaces. | Change indentation tab to spaces.
| Python | bsd-3-clause | vanesa/kid-o,vanesa/kid-o,vanesa/kid-o,vanesa/kid-o | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
Change indentation tab to spaces. | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| <commit_before>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
<commit_msg>Change indentation tab to spaces.<commit_after> | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
Change indentation tab to spaces.#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| <commit_before>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
<commit_msg>Change indentation tab to spaces.<commit_after>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
|
442136bb1d32baa1be50c3b88caed344e3979cd3 | website/project/taxonomies/__init__.py | website/project/taxonomies/__init__.py | from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
@mongo_utils.unique_on(['id', '_id'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
type = fields.StringField(required=True)
text = fields.StringField(required=True)
parent_ids = fields.StringField(list=True)
def get_absolute_url(self):
return '{}taxonomies/?filter[id]={}'.format(self.absolute_api_v2_url, self._id)
| from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
| Update Subject model -remove superfluous type field -fix parents field type -update url building | Update Subject model
-remove superfluous type field
-fix parents field type
-update url building
| Python | apache-2.0 | TomBaxter/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,sloria/osf.io,alexschiller/osf.io,emetsger/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,rdhyee/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,chrisseto/osf.io,hmoco/osf.io,felliott/osf.io,caneruguz/osf.io,acshi/osf.io,erinspace/osf.io,caneruguz/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,mattclark/osf.io,alexschiller/osf.io,samchrisinger/osf.io,acshi/osf.io,rdhyee/osf.io,caseyrollins/osf.io,caneruguz/osf.io,erinspace/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,cslzchen/osf.io,acshi/osf.io,monikagrabowska/osf.io,icereval/osf.io,Nesiehr/osf.io,mfraezz/osf.io,hmoco/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,mluo613/osf.io,baylee-d/osf.io,chrisseto/osf.io,chennan47/osf.io,leb2dg/osf.io,cslzchen/osf.io,binoculars/osf.io,mattclark/osf.io,chrisseto/osf.io,TomBaxter/osf.io,mluo613/osf.io,alexschiller/osf.io,cwisecarver/osf.io,pattisdr/osf.io,icereval/osf.io,laurenrevere/osf.io,mfraezz/osf.io,icereval/osf.io,felliott/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,acshi/osf.io,felliott/osf.io,sloria/osf.io,samchrisinger/osf.io,crcresearch/osf.io,chrisseto/osf.io,Nesiehr/osf.io,aaxelb/osf.io,mattclark/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,erinspace/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,laurenrevere/osf.io,leb2dg/osf.io,saradbowman/osf.io,samchrisinger/osf.io,caneruguz/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,binoculars/osf.io,mluo613/osf.io,pattisdr/osf.io,aaxelb/osf.io,Nesiehr/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,emetsger/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,rdhyee/osf.io,emetsger/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,adlius/osf.io,alexschiller/osf.io,aaxelb/osf.io,cslzchen/osf.io,crcresearch/osf.io,adlius/osf.io,acshi/osf.io,sloria/osf.io,mfraezz/osf.io,binoculars/osf.io,caseyrollins/osf.io,cwisecarver/osf.io,hmoco/osf.io,Nesiehr/osf.io,hmoco/osf.io,cslzchen/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,crcresearch/osf.io | from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
@mongo_utils.unique_on(['id', '_id'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
type = fields.StringField(required=True)
text = fields.StringField(required=True)
parent_ids = fields.StringField(list=True)
def get_absolute_url(self):
return '{}taxonomies/?filter[id]={}'.format(self.absolute_api_v2_url, self._id)
Update Subject model
-remove superfluous type field
-fix parents field type
-update url building | from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
| <commit_before>from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
@mongo_utils.unique_on(['id', '_id'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
type = fields.StringField(required=True)
text = fields.StringField(required=True)
parent_ids = fields.StringField(list=True)
def get_absolute_url(self):
return '{}taxonomies/?filter[id]={}'.format(self.absolute_api_v2_url, self._id)
<commit_msg>Update Subject model
-remove superfluous type field
-fix parents field type
-update url building<commit_after> | from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
| from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
@mongo_utils.unique_on(['id', '_id'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
type = fields.StringField(required=True)
text = fields.StringField(required=True)
parent_ids = fields.StringField(list=True)
def get_absolute_url(self):
return '{}taxonomies/?filter[id]={}'.format(self.absolute_api_v2_url, self._id)
Update Subject model
-remove superfluous type field
-fix parents field type
-update url buildingfrom modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
| <commit_before>from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
@mongo_utils.unique_on(['id', '_id'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
type = fields.StringField(required=True)
text = fields.StringField(required=True)
parent_ids = fields.StringField(list=True)
def get_absolute_url(self):
return '{}taxonomies/?filter[id]={}'.format(self.absolute_api_v2_url, self._id)
<commit_msg>Update Subject model
-remove superfluous type field
-fix parents field type
-update url building<commit_after>from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.StringField(required=True)
parents = fields.ForeignField('subject', list=True)
@property
def absolute_api_v2_url(self):
return api_v2_url('taxonomies/{}/'.format(self._id))
def get_absolute_url(self):
return self.absolute_api_v2_url
|
e391aa732eb0e713e7dc6bb9c767998425bc987b | src/server/__init__.py | src/server/__init__.py | """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy import version, __version__
| """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy._generated.Client_Observer import ClientObserver
from telepathy._generated.Client_Approver import ClientApprover
from telepathy._generated.Client_Handler import ClientHandler
from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests
from telepathy import version, __version__
| Add the generated Client interfaces to the telepathy.server namespace | Add the generated Client interfaces to the telepathy.server namespace
| Python | lgpl-2.1 | PabloCastellano/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,PabloCastellano/telepathy-python,detrout/telepathy-python,epage/telepathy-python,max-posedon/telepathy-python,epage/telepathy-python,max-posedon/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,detrout/telepathy-python | """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy import version, __version__
Add the generated Client interfaces to the telepathy.server namespace | """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy._generated.Client_Observer import ClientObserver
from telepathy._generated.Client_Approver import ClientApprover
from telepathy._generated.Client_Handler import ClientHandler
from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests
from telepathy import version, __version__
| <commit_before>"""
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy import version, __version__
<commit_msg>Add the generated Client interfaces to the telepathy.server namespace<commit_after> | """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy._generated.Client_Observer import ClientObserver
from telepathy._generated.Client_Approver import ClientApprover
from telepathy._generated.Client_Handler import ClientHandler
from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests
from telepathy import version, __version__
| """
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy import version, __version__
Add the generated Client interfaces to the telepathy.server namespace"""
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy._generated.Client_Observer import ClientObserver
from telepathy._generated.Client_Approver import ClientApprover
from telepathy._generated.Client_Handler import ClientHandler
from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests
from telepathy import version, __version__
| <commit_before>"""
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy import version, __version__
<commit_msg>Add the generated Client interfaces to the telepathy.server namespace<commit_after>"""
telepathy-python - Base classes defining the interfaces of the Telepathy framework
Copyright (C) 2005, 2006 Collabora Limited
Copyright (C) 2005, 2006 Nokia Corporation
Copyright (C) 2006 INdT
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from telepathy.server.connmgr import *
from telepathy.server.conn import *
from telepathy.server.channel import *
from telepathy.server.channelmanager import *
from telepathy.server.debug import *
from telepathy.server.handle import *
from telepathy.server.media import *
from telepathy.server.properties import *
from telepathy._generated.Client_Observer import ClientObserver
from telepathy._generated.Client_Approver import ClientApprover
from telepathy._generated.Client_Handler import ClientHandler
from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests
from telepathy import version, __version__
|
f980e56d583f1669d56bef6e15df8c2818f99467 | ejpi/constants.py | ejpi/constants.py | __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| Bump for icon harmattan build | Bump for icon harmattan build
| Python | lgpl-2.1 | epage/ejpi,epage/ejpi,epage/ejpi | __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
Bump for icon harmattan build | __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| <commit_before>__pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
<commit_msg>Bump for icon harmattan build<commit_after> | __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
Bump for icon harmattan build__pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| <commit_before>__pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
<commit_msg>Bump for icon harmattan build<commit_after>__pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
|
d3428d9bb8baf67176e1bd6a22b96845ebcdf42e | indico/migrations/versions/201705221530_3ca338ed5192_remove_background_image_and_add.py | indico/migrations/versions/201705221530_3ca338ed5192_remove_background_image_and_add.py | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
| """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
| Add missing index command in revision | Designer: Add missing index command in revision
| Python | mit | pferreir/indico,pferreir/indico,OmeGak/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,indico/indico,OmeGak/indico,mvidalgarcia/indico,pferreir/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,indico/indico,OmeGak/indico,mic4ael/indico,mvidalgarcia/indico,mic4ael/indico,ThiefMaster/indico,ThiefMaster/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,DirkHoffmann/indico | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
Designer: Add missing index command in revision | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
| <commit_before>"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
<commit_msg>Designer: Add missing index command in revision<commit_after> | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
| """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
Designer: Add missing index command in revision"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
| <commit_before>"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
def downgrade():
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
<commit_msg>Designer: Add missing index command in revision<commit_after>"""Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('designer_templates', sa.Column('backside_template_id', sa.Integer(), nullable=True), schema='indico')
op.create_foreign_key(None,
'designer_templates', 'designer_templates',
['backside_template_id'], ['id'],
source_schema='indico', referent_schema='indico')
op.create_index(None, 'designer_templates', ['backside_template_id'], schema='indico')
def downgrade():
op.drop_index('ix_designer_templates_backside_template_id', table_name='designer_templates', schema='indico')
op.drop_constraint('fk_designer_templates_backside_template_id_designer_templates', 'designer_templates',
schema='indico')
op.drop_column('designer_templates', 'backside_template_id', schema='indico')
|
abc1d8c52b9893f1695b2f81126b22820cddfc67 | src/argon2/__init__.py | src/argon2/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"hash_secret",
"hash_secret_raw",
"low_level",
"verify_password",
"verify_secret",
]
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"low_level",
"verify_password",
]
| Remove unimported symbols from __all__ | Remove unimported symbols from __all__
I don't quite understand, why flake8 didn't catch this...
| Python | mit | hynek/argon2_cffi,hynek/argon2_cffi | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"hash_secret",
"hash_secret_raw",
"low_level",
"verify_password",
"verify_secret",
]
Remove unimported symbols from __all__
I don't quite understand, why flake8 didn't catch this... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"low_level",
"verify_password",
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"hash_secret",
"hash_secret_raw",
"low_level",
"verify_password",
"verify_secret",
]
<commit_msg>Remove unimported symbols from __all__
I don't quite understand, why flake8 didn't catch this...<commit_after> | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"low_level",
"verify_password",
]
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"hash_secret",
"hash_secret_raw",
"low_level",
"verify_password",
"verify_secret",
]
Remove unimported symbols from __all__
I don't quite understand, why flake8 didn't catch this...# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"low_level",
"verify_password",
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"hash_secret",
"hash_secret_raw",
"low_level",
"verify_password",
"verify_secret",
]
<commit_msg>Remove unimported symbols from __all__
I don't quite understand, why flake8 didn't catch this...<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from . import exceptions, low_level
from ._legacy import (
hash_password,
hash_password_raw,
verify_password,
)
from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
PasswordHasher,
)
from .low_level import Type
__version__ = "16.1.0.dev0"
__title__ = "argon2_cffi"
__description__ = "The secure Argon2 password hashing algorithm."
__uri__ = "https://argon2-cffi.readthedocs.org/"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 {author}".format(author=__author__)
__all__ = [
"DEFAULT_HASH_LENGTH",
"DEFAULT_MEMORY_COST",
"DEFAULT_PARALLELISM",
"DEFAULT_RANDOM_SALT_LENGTH",
"DEFAULT_TIME_COST",
"PasswordHasher",
"Type",
"exceptions",
"hash_password",
"hash_password_raw",
"low_level",
"verify_password",
]
|
98cd52a2c635a50b6664212ace5e98090246aba2 | python/bracket-push/bracket_push.py | python/bracket-push/bracket_push.py | class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_brackets | class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
| Fix method name to conform to tests | Fix method name to conform to tests
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_bracketsFix method name to conform to tests | class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
| <commit_before>class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_brackets<commit_msg>Fix method name to conform to tests<commit_after> | class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
| class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_bracketsFix method name to conform to testsclass CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
| <commit_before>class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_brackets<commit_msg>Fix method name to conform to tests<commit_after>class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
|
830119c570ed9ec3693d9e002b07777c5542bb1f | modelToParseFile/parseFileBacteriaList.py | modelToParseFile/parseFileBacteriaList.py | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
for linia in file:
print linia | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
listBacteria = []
listDeseases = []
for linia in file:
line = linia.split("\t")
listBacteria.append(line[0])
listDeseases.append(line[1])
print listBacteria
print listDeseases | Split text by \t, and added lists of bacteria and diseases | Split text by \t, and added lists of bacteria and diseases
| Python | apache-2.0 | kgruba/oop_python | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
for linia in file:
print liniaSplit text by \t, and added lists of bacteria and diseases | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
listBacteria = []
listDeseases = []
for linia in file:
line = linia.split("\t")
listBacteria.append(line[0])
listDeseases.append(line[1])
print listBacteria
print listDeseases | <commit_before>class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
for linia in file:
print linia<commit_msg>Split text by \t, and added lists of bacteria and diseases<commit_after> | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
listBacteria = []
listDeseases = []
for linia in file:
line = linia.split("\t")
listBacteria.append(line[0])
listDeseases.append(line[1])
print listBacteria
print listDeseases | class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
for linia in file:
print liniaSplit text by \t, and added lists of bacteria and diseasesclass parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
listBacteria = []
listDeseases = []
for linia in file:
line = linia.split("\t")
listBacteria.append(line[0])
listDeseases.append(line[1])
print listBacteria
print listDeseases | <commit_before>class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
for linia in file:
print linia<commit_msg>Split text by \t, and added lists of bacteria and diseases<commit_after>class parseFileBacteriaList:
'Class for read and print information from text file'
bacteriaName = []
fileName = ""
def __init__(self,fileName):
self.fileName = fileName
def readFile(self):
file = open(self.fileName).readlines()
listBacteria = []
listDeseases = []
for linia in file:
line = linia.split("\t")
listBacteria.append(line[0])
listDeseases.append(line[1])
print listBacteria
print listDeseases |
cd359f8487ee5aab3645a0089695967802e485d0 | samples/python/uppercase/py/func.py | samples/python/uppercase/py/func.py | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
reply.body = request.body.upper()
return reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
| import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iterator of request values and is itself an iterator of response values.
'''
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request_iterator, context):
for request in request_iterator:
reply = types.Reply()
reply.body = request.body.upper()
yield reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
| Enable GRPC Streaming in Python uppercase sample | Enable GRPC Streaming in Python uppercase sample
| Python | apache-2.0 | markfisher/sk8s,markfisher/sk8s,markfisher/sk8s,markfisher/sk8s | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
reply.body = request.body.upper()
return reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
Enable GRPC Streaming in Python uppercase sample | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iterator of request values and is itself an iterator of response values.
'''
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request_iterator, context):
for request in request_iterator:
reply = types.Reply()
reply.body = request.body.upper()
yield reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
| <commit_before>import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
reply.body = request.body.upper()
return reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
<commit_msg>Enable GRPC Streaming in Python uppercase sample<commit_after> | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iterator of request values and is itself an iterator of response values.
'''
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request_iterator, context):
for request in request_iterator:
reply = types.Reply()
reply.body = request.body.upper()
yield reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
| import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
reply.body = request.body.upper()
return reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
Enable GRPC Streaming in Python uppercase sampleimport os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iterator of request values and is itself an iterator of response values.
'''
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request_iterator, context):
for request in request_iterator:
reply = types.Reply()
reply.body = request.body.upper()
yield reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
| <commit_before>import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
reply.body = request.body.upper()
return reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
<commit_msg>Enable GRPC Streaming in Python uppercase sample<commit_after>import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iterator of request values and is itself an iterator of response values.
'''
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request_iterator, context):
for request in request_iterator:
reply = types.Reply()
reply.body = request.body.upper()
yield reply
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
function.add_StringFunctionServicer_to_server(StringFunctionServicer(), server)
server.add_insecure_port('%s:%s' % ('[::]', os.environ.get("GRPC_PORT","10382")))
server.start()
while True:
time.sleep(10)
|
34fdb69aa6a414c65a05ee25a0cb1b09e3196221 | packages/cardpay-subgraph-extraction/export.py | packages/cardpay-subgraph-extraction/export.py | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export() | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
| Support environment variables for the extraction | Support environment variables for the extraction
| Python | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export()Support environment variables for the extraction | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
| <commit_before>from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export()<commit_msg>Support environment variables for the extraction<commit_after> | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
| from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export()Support environment variables for the extractionfrom subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
| <commit_before>from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://graph-node:let-me-in@localhost:5432/graph-node",
help="The database string for connections, defaults to a local graph-node",
)
@click.option(
"--output-location",
default="data",
help="The base output location, whether local or cloud",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'):
extract_from_config(
file_name,
database_string,
output_location
)
if __name__ == "__main__":
export()<commit_msg>Support environment variables for the extraction<commit_after>from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.environ.get(
"SE_DATABASE_STRING",
"postgresql://graph-node:let-me-in@localhost:5432/graph-node",
),
help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node",
)
@click.option(
"--output-location",
default=os.environ.get("SE_OUTPUT_LOCATION", "data"),
help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data",
)
def export(subgraph_config_folder, database_string, output_location):
for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"):
extract_from_config(file_name, database_string, output_location)
if __name__ == "__main__":
export()
|
1e980277f53d12686264b8ce816e65ffea16a2dd | examples/basic.py | examples/basic.py | from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x):
y = self.submit(increment, x)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
| import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, yy)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
| Update example: add a delay task | Update example: add a delay task
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x):
y = self.submit(increment, x)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
Update example: add a delay task | import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, yy)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
| <commit_before>from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x):
y = self.submit(increment, x)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
<commit_msg>Update example: add a delay task<commit_after> | import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, yy)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
| from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x):
y = self.submit(increment, x)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
Update example: add a delay taskimport time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, yy)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
| <commit_before>from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x):
y = self.submit(increment, x)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
<commit_msg>Update example: add a delay task<commit_after>import time
from simpleflow import (
activity,
Workflow,
)
@activity.with_attributes(task_list='quickstart')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, yy)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
return z.result
|
2548c8a46b04a34db218e522704fa171d8d6f7b7 | nephele.py | nephele.py | """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
| """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
| Use four spaces, just like in Python. | Use four spaces, just like in Python.
| Python | mit | EmilStenstrom/nephele | """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
Use four spaces, just like in Python. | """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
| <commit_before>"""Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
<commit_msg>Use four spaces, just like in Python.<commit_after> | """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
| """Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
Use four spaces, just like in Python."""Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
| <commit_before>"""Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
<commit_msg>Use four spaces, just like in Python.<commit_after>"""Nephele - Finding movies to watch on the internet is easy,
finding GOOD movies to watch is hard. Let Nephele, the greek
nymph of the clouds, help you.
Usage:
nephele.py get_popular [--debug]
nephele.py get_grades <directory> [--debug]
Options:
-h --help Show this screen.
--debug Print debug information.
"""
from docopt import docopt
import importlib
if __name__ == '__main__':
arguments = docopt(__doc__)
command_str = "get_popular" if arguments["get_popular"] else "get_grades"
command = importlib.import_module("commands." + command_str)
command.main(arguments)
|
942044eeab89d81b75836268b3635d49a4dbb3ee | ynr/apps/parties/management/commands/parties_import_from_ec.py | ynr/apps/parties/management/commands/parties_import_from_ec.py | from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = "My shiny new management command."
def add_arguments(self, parser):
parser.add_argument("--clear-emblems", action="store_true")
parser.add_argument("--output-new-parties", action="store_true")
parser.add_argument("--skip-create-joint", action="store_true")
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
| from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = """
Import policital parties that can stand candidates from The Electoral
Commission's API in to the Parties app.
This command creates 3 types of object: parties, descriptions and emblems.
It also creates joint parties. That is, a psudo-party that allows us to
mark candidates as standing for 2 parties.
"""
def add_arguments(self, parser):
parser.add_argument(
"--clear-emblems",
action="store_true",
help="Deletes all emblems and re-downloads them all",
)
parser.add_argument(
"--output-new-parties",
action="store_true",
help="Write newly created parties to stdout (helpful for notifying of newly registererd parties)",
)
parser.add_argument(
"--skip-create-joint",
action="store_true",
help="Don't make psudo-parties from joint descriptions",
)
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
| Document the party importer command | Document the party importer command
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = "My shiny new management command."
def add_arguments(self, parser):
parser.add_argument("--clear-emblems", action="store_true")
parser.add_argument("--output-new-parties", action="store_true")
parser.add_argument("--skip-create-joint", action="store_true")
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
Document the party importer command | from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = """
Import policital parties that can stand candidates from The Electoral
Commission's API in to the Parties app.
This command creates 3 types of object: parties, descriptions and emblems.
It also creates joint parties. That is, a psudo-party that allows us to
mark candidates as standing for 2 parties.
"""
def add_arguments(self, parser):
parser.add_argument(
"--clear-emblems",
action="store_true",
help="Deletes all emblems and re-downloads them all",
)
parser.add_argument(
"--output-new-parties",
action="store_true",
help="Write newly created parties to stdout (helpful for notifying of newly registererd parties)",
)
parser.add_argument(
"--skip-create-joint",
action="store_true",
help="Don't make psudo-parties from joint descriptions",
)
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
| <commit_before>from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = "My shiny new management command."
def add_arguments(self, parser):
parser.add_argument("--clear-emblems", action="store_true")
parser.add_argument("--output-new-parties", action="store_true")
parser.add_argument("--skip-create-joint", action="store_true")
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
<commit_msg>Document the party importer command<commit_after> | from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = """
Import policital parties that can stand candidates from The Electoral
Commission's API in to the Parties app.
This command creates 3 types of object: parties, descriptions and emblems.
It also creates joint parties. That is, a psudo-party that allows us to
mark candidates as standing for 2 parties.
"""
def add_arguments(self, parser):
parser.add_argument(
"--clear-emblems",
action="store_true",
help="Deletes all emblems and re-downloads them all",
)
parser.add_argument(
"--output-new-parties",
action="store_true",
help="Write newly created parties to stdout (helpful for notifying of newly registererd parties)",
)
parser.add_argument(
"--skip-create-joint",
action="store_true",
help="Don't make psudo-parties from joint descriptions",
)
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
| from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = "My shiny new management command."
def add_arguments(self, parser):
parser.add_argument("--clear-emblems", action="store_true")
parser.add_argument("--output-new-parties", action="store_true")
parser.add_argument("--skip-create-joint", action="store_true")
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
Document the party importer commandfrom django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = """
Import policital parties that can stand candidates from The Electoral
Commission's API in to the Parties app.
This command creates 3 types of object: parties, descriptions and emblems.
It also creates joint parties. That is, a psudo-party that allows us to
mark candidates as standing for 2 parties.
"""
def add_arguments(self, parser):
parser.add_argument(
"--clear-emblems",
action="store_true",
help="Deletes all emblems and re-downloads them all",
)
parser.add_argument(
"--output-new-parties",
action="store_true",
help="Write newly created parties to stdout (helpful for notifying of newly registererd parties)",
)
parser.add_argument(
"--skip-create-joint",
action="store_true",
help="Don't make psudo-parties from joint descriptions",
)
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
| <commit_before>from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = "My shiny new management command."
def add_arguments(self, parser):
parser.add_argument("--clear-emblems", action="store_true")
parser.add_argument("--output-new-parties", action="store_true")
parser.add_argument("--skip-create-joint", action="store_true")
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
<commit_msg>Document the party importer command<commit_after>from django.core.management.base import BaseCommand
from parties.importer import ECPartyImporter
from parties.models import PartyEmblem
class Command(BaseCommand):
help = """
Import policital parties that can stand candidates from The Electoral
Commission's API in to the Parties app.
This command creates 3 types of object: parties, descriptions and emblems.
It also creates joint parties. That is, a psudo-party that allows us to
mark candidates as standing for 2 parties.
"""
def add_arguments(self, parser):
parser.add_argument(
"--clear-emblems",
action="store_true",
help="Deletes all emblems and re-downloads them all",
)
parser.add_argument(
"--output-new-parties",
action="store_true",
help="Write newly created parties to stdout (helpful for notifying of newly registererd parties)",
)
parser.add_argument(
"--skip-create-joint",
action="store_true",
help="Don't make psudo-parties from joint descriptions",
)
def handle(self, *args, **options):
if options["clear_emblems"]:
for emblem in PartyEmblem.objects.all():
emblem.image.delete()
emblem.delete()
importer = ECPartyImporter()
importer.do_import()
if not options["skip_create_joint"]:
importer.create_joint_parties()
if options["output_new_parties"] and importer.collector:
self.stdout.write("Found new political parties!")
for party in importer.collector:
self.stdout.write(str(party))
|
08afe7e2946f4343d016f55bfacb4f7bac1d3cb2 | herana/urls.py | herana/urls.py | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| Change admin index title: 'Dashboard' | Change admin index title: 'Dashboard'
| Python | mit | Code4SA/herana,Code4SA/herana,Code4SA/herana,Code4SA/herana | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
Change admin index title: 'Dashboard' | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
<commit_msg>Change admin index title: 'Dashboard'<commit_after> | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
Change admin index title: 'Dashboard'from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
<commit_msg>Change admin index title: 'Dashboard'<commit_after>from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
|
e388e3490502acac90ef4c249ba1af63b5698ab7 | print_web_django/api/views.py | print_web_django/api/views.py | from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
| from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
| Add user to posted print object | Add user to posted print object
| Python | mit | aabmass/print-web,aabmass/print-web,aabmass/print-web | from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
Add user to posted print object | from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
| <commit_before>from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
<commit_msg>Add user to posted print object<commit_after> | from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
| from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
Add user to posted print objectfrom rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
| <commit_before>from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
<commit_msg>Add user to posted print object<commit_after>from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
|
be915a11ebd0d9c4e8a0a52b1bdcc7ca2abfbfb1 | sms_sender.py | sms_sender.py | from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
| from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
| Change topic + add exception handling | Change topic + add exception handling | Python | apache-2.0 | antongorshkov/kafkasms | from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
Change topic + add exception handling | from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
| <commit_before>from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
<commit_msg>Change topic + add exception handling<commit_after> | from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
| from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
Change topic + add exception handlingfrom kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
| <commit_before>from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['kafka_test1'])
while True:
for message in consumer:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
<commit_msg>Change topic + add exception handling<commit_after>from kafka import KafkaConsumer
import os
import nexmo
import json
client = nexmo.Client( key=os.environ["API_KEY"],
secret=os.environ["API_SECRET"])
consumer = KafkaConsumer(bootstrap_servers=os.environ["KAFKA"],
value_deserializer=lambda m: json.loads(m.decode('ascii')))
consumer.subscribe(['sms_response'])
while True:
for message in consumer:
try:
client.send_message({ 'from' : message.value['from'],
'to' : message.value['to'],
'text' : message.value['text']})
except:
print 'Unexpected error'
|
9792b1a03af3a3a3c0b9d517cefaee4c137c2a2d | pyirt/utl/__init__.py | pyirt/utl/__init__.py | __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_in_temp=True)
from . import clib
| __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_dir="/tmp/pyximport/", build_in_temp=True)
from . import clib
| Add custom build_dir opt for pyximport.install | Add custom build_dir opt for pyximport.install
| Python | mit | 17zuoye/pyirt,arunlodhi/pyirt,wlbksy/pyirt | __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_in_temp=True)
from . import clib
Add custom build_dir opt for pyximport.install | __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_dir="/tmp/pyximport/", build_in_temp=True)
from . import clib
| <commit_before>__all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_in_temp=True)
from . import clib
<commit_msg>Add custom build_dir opt for pyximport.install<commit_after> | __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_dir="/tmp/pyximport/", build_in_temp=True)
from . import clib
| __all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_in_temp=True)
from . import clib
Add custom build_dir opt for pyximport.install__all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_dir="/tmp/pyximport/", build_in_temp=True)
from . import clib
| <commit_before>__all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_in_temp=True)
from . import clib
<commit_msg>Add custom build_dir opt for pyximport.install<commit_after>__all__ = ["tools", "loader", "clib"]
from . import tools
from . import loader
import pyximport
pyximport.install(build_dir="/tmp/pyximport/", build_in_temp=True)
from . import clib
|
002a598afbdf86472611c018d17d0eff8a9690aa | flocker/provision/_sphinx.py | flocker/provision/_sphinx.py | from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = self.arguments[0]
runner = FakeRunner()
try:
namedAny(task)(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = namedAny(self.arguments[0])
runner = FakeRunner()
try:
task(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
# The following three lines record (some?) of the dependencies of the
# directive, so automatic regeneration happens. Specifically, it
# records this file, and the file where the task is declared.
task_file = getsourcefile(task)
self.state.document.settings.record_dependencies.add(task_file)
self.state.document.settings.record_dependencies.add(__file__)
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
| Add state change to sphinx plugin. | Add state change to sphinx plugin.
| Python | apache-2.0 | jml/flocker,wallnerryan/flocker-profiles,runcom/flocker,adamtheturtle/flocker,lukemarsden/flocker,1d4Nf6/flocker,mbrukman/flocker,Azulinho/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,agonzalezro/flocker,jml/flocker,1d4Nf6/flocker,runcom/flocker,agonzalezro/flocker,hackday-profilers/flocker,achanda/flocker,LaynePeng/flocker,AndyHuu/flocker,moypray/flocker,mbrukman/flocker,runcom/flocker,LaynePeng/flocker,AndyHuu/flocker,adamtheturtle/flocker,lukemarsden/flocker,Azulinho/flocker,agonzalezro/flocker,w4ngyi/flocker,adamtheturtle/flocker,jml/flocker,moypray/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,achanda/flocker,w4ngyi/flocker,1d4Nf6/flocker,w4ngyi/flocker,achanda/flocker,hackday-profilers/flocker,LaynePeng/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,Azulinho/flocker | from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = self.arguments[0]
runner = FakeRunner()
try:
namedAny(task)(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
Add state change to sphinx plugin. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = namedAny(self.arguments[0])
runner = FakeRunner()
try:
task(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
# The following three lines record (some?) of the dependencies of the
# directive, so automatic regeneration happens. Specifically, it
# records this file, and the file where the task is declared.
task_file = getsourcefile(task)
self.state.document.settings.record_dependencies.add(task_file)
self.state.document.settings.record_dependencies.add(__file__)
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
| <commit_before>from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = self.arguments[0]
runner = FakeRunner()
try:
namedAny(task)(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
<commit_msg>Add state change to sphinx plugin.<commit_after> | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = namedAny(self.arguments[0])
runner = FakeRunner()
try:
task(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
# The following three lines record (some?) of the dependencies of the
# directive, so automatic regeneration happens. Specifically, it
# records this file, and the file where the task is declared.
task_file = getsourcefile(task)
self.state.document.settings.record_dependencies.add(task_file)
self.state.document.settings.record_dependencies.add(__file__)
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
| from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = self.arguments[0]
runner = FakeRunner()
try:
namedAny(task)(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
Add state change to sphinx plugin.# Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = namedAny(self.arguments[0])
runner = FakeRunner()
try:
task(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
# The following three lines record (some?) of the dependencies of the
# directive, so automatic regeneration happens. Specifically, it
# records this file, and the file where the task is declared.
task_file = getsourcefile(task)
self.state.document.settings.record_dependencies.add(task_file)
self.state.document.settings.record_dependencies.add(__file__)
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
| <commit_before>from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = self.arguments[0]
runner = FakeRunner()
try:
namedAny(task)(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
<commit_msg>Add state change to sphinx plugin.<commit_after># Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
def put(self, content, path):
raise NotImplementedError("put not supported.")
class TaskDirective(Directive):
"""
Implementation of the C{frameimage} directive.
"""
required_arguments = 1
def run(self):
task = namedAny(self.arguments[0])
runner = FakeRunner()
try:
task(runner)
except NotImplementedError as e:
raise self.error("task: %s" % (e.args[0],))
lines = ['.. code-block:: bash', '']
lines += [' %s' % (command,) for command in runner.commands]
# The following three lines record (some?) of the dependencies of the
# directive, so automatic regeneration happens. Specifically, it
# records this file, and the file where the task is declared.
task_file = getsourcefile(task)
self.state.document.settings.record_dependencies.add(task_file)
self.state.document.settings.record_dependencies.add(__file__)
node = nodes.Element()
text = StringList(lines)
self.state.nested_parse(text, self.content_offset, node)
return node.children
def setup(app):
"""
Entry point for sphinx extension.
"""
app.add_directive('task', TaskDirective)
|
e5bf18be1ad32a39f0eef2bbc8f5bd4674cef7a5 | tests/test_dump.py | tests/test_dump.py | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
| """ Testing gitwash dumper
"""
import os
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
_downpath = os.path.abspath(_downpath)
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
DOC_DIR = pjoin(_downpath, 'gitwash')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
#shutil.rmtree(TMPDIR)
print TMPDIR
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
gitwdir = pjoin(TMPDIR, 'gitwash')
assert_true(os.path.isdir(gitwdir))
for dirpath, dirnames, filenames in os.walk(gitwdir):
if not dirpath.endswith('gitwash'):
raise RuntimeError('I only know about the gitwash directory')
for filename in filenames:
print filename
old_fname = pjoin(DOC_DIR, filename)
new_fname = pjoin(dirpath, filename)
old_contents = file(old_fname, 'rt').readlines()
new_contents = file(new_fname, 'rt').readlines()
for old, new in zip(old_contents, new_contents):
if 'PROJECT' in old and not filename.endswith('.inc'):
assert_false('PROJECT' in new)
assert_true('my_project' in new)
| TEST - add test for replacement in files | TEST - add test for replacement in files
| Python | bsd-2-clause | QuLogic/gitwash,QuLogic/gitwash | """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
TEST - add test for replacement in files | """ Testing gitwash dumper
"""
import os
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
_downpath = os.path.abspath(_downpath)
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
DOC_DIR = pjoin(_downpath, 'gitwash')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
#shutil.rmtree(TMPDIR)
print TMPDIR
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
gitwdir = pjoin(TMPDIR, 'gitwash')
assert_true(os.path.isdir(gitwdir))
for dirpath, dirnames, filenames in os.walk(gitwdir):
if not dirpath.endswith('gitwash'):
raise RuntimeError('I only know about the gitwash directory')
for filename in filenames:
print filename
old_fname = pjoin(DOC_DIR, filename)
new_fname = pjoin(dirpath, filename)
old_contents = file(old_fname, 'rt').readlines()
new_contents = file(new_fname, 'rt').readlines()
for old, new in zip(old_contents, new_contents):
if 'PROJECT' in old and not filename.endswith('.inc'):
assert_false('PROJECT' in new)
assert_true('my_project' in new)
| <commit_before>""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
<commit_msg>TEST - add test for replacement in files<commit_after> | """ Testing gitwash dumper
"""
import os
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
_downpath = os.path.abspath(_downpath)
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
DOC_DIR = pjoin(_downpath, 'gitwash')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
#shutil.rmtree(TMPDIR)
print TMPDIR
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
gitwdir = pjoin(TMPDIR, 'gitwash')
assert_true(os.path.isdir(gitwdir))
for dirpath, dirnames, filenames in os.walk(gitwdir):
if not dirpath.endswith('gitwash'):
raise RuntimeError('I only know about the gitwash directory')
for filename in filenames:
print filename
old_fname = pjoin(DOC_DIR, filename)
new_fname = pjoin(dirpath, filename)
old_contents = file(old_fname, 'rt').readlines()
new_contents = file(new_fname, 'rt').readlines()
for old, new in zip(old_contents, new_contents):
if 'PROJECT' in old and not filename.endswith('.inc'):
assert_false('PROJECT' in new)
assert_true('my_project' in new)
| """ Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
TEST - add test for replacement in files""" Testing gitwash dumper
"""
import os
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
_downpath = os.path.abspath(_downpath)
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
DOC_DIR = pjoin(_downpath, 'gitwash')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
#shutil.rmtree(TMPDIR)
print TMPDIR
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
gitwdir = pjoin(TMPDIR, 'gitwash')
assert_true(os.path.isdir(gitwdir))
for dirpath, dirnames, filenames in os.walk(gitwdir):
if not dirpath.endswith('gitwash'):
raise RuntimeError('I only know about the gitwash directory')
for filename in filenames:
print filename
old_fname = pjoin(DOC_DIR, filename)
new_fname = pjoin(dirpath, filename)
old_contents = file(old_fname, 'rt').readlines()
new_contents = file(new_fname, 'rt').readlines()
for old, new in zip(old_contents, new_contents):
if 'PROJECT' in old and not filename.endswith('.inc'):
assert_false('PROJECT' in new)
assert_true('my_project' in new)
| <commit_before>""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
<commit_msg>TEST - add test for replacement in files<commit_after>""" Testing gitwash dumper
"""
import os
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
_downpath = os.path.abspath(_downpath)
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
DOC_DIR = pjoin(_downpath, 'gitwash')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
#shutil.rmtree(TMPDIR)
print TMPDIR
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
gitwdir = pjoin(TMPDIR, 'gitwash')
assert_true(os.path.isdir(gitwdir))
for dirpath, dirnames, filenames in os.walk(gitwdir):
if not dirpath.endswith('gitwash'):
raise RuntimeError('I only know about the gitwash directory')
for filename in filenames:
print filename
old_fname = pjoin(DOC_DIR, filename)
new_fname = pjoin(dirpath, filename)
old_contents = file(old_fname, 'rt').readlines()
new_contents = file(new_fname, 'rt').readlines()
for old, new in zip(old_contents, new_contents):
if 'PROJECT' in old and not filename.endswith('.inc'):
assert_false('PROJECT' in new)
assert_true('my_project' in new)
|
d2438a4f3618a2f087ddf49380c5753a4b9805d5 | zou/app/models/attachment_file.py | zou/app/models/attachment_file.py | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
| from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
@classmethod
def create_from_import(cls, data):
data.pop("type", None)
data.pop("comment", None)
previous_data = cls.get(data["id"])
if previous_data is None:
return cls.create(**data)
else:
previous_data.update(data)
return previous_data
| Fix import for attachment files | [sync] Fix import for attachment files
| Python | agpl-3.0 | cgwire/zou | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
[sync] Fix import for attachment files | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
@classmethod
def create_from_import(cls, data):
data.pop("type", None)
data.pop("comment", None)
previous_data = cls.get(data["id"])
if previous_data is None:
return cls.create(**data)
else:
previous_data.update(data)
return previous_data
| <commit_before>from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
<commit_msg>[sync] Fix import for attachment files<commit_after> | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
@classmethod
def create_from_import(cls, data):
data.pop("type", None)
data.pop("comment", None)
previous_data = cls.get(data["id"])
if previous_data is None:
return cls.create(**data)
else:
previous_data.update(data)
return previous_data
| from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
[sync] Fix import for attachment filesfrom sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
@classmethod
def create_from_import(cls, data):
data.pop("type", None)
data.pop("comment", None)
previous_data = cls.get(data["id"])
if previous_data is None:
return cls.create(**data)
else:
previous_data.update(data)
return previous_data
| <commit_before>from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
<commit_msg>[sync] Fix import for attachment files<commit_after>from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class AttachmentFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is attached to a comment.
"""
name = db.Column(db.String(250))
size = db.Column(db.Integer(), default=1)
extension = db.Column(db.String(6))
mimetype = db.Column(db.String(255))
comment_id = db.Column(
UUIDType(binary=False), db.ForeignKey("comment.id"), index=True
)
__table_args__ = (
db.UniqueConstraint("name", "comment_id", name="attachment_uc"),
)
def __repr__(self):
return "<AttachmentFile %s>" % self.id
def present(self):
return {
"id": str(self.id),
"name": self.name,
"extension": self.extension,
"size": self.size,
}
@classmethod
def create_from_import(cls, data):
data.pop("type", None)
data.pop("comment", None)
previous_data = cls.get(data["id"])
if previous_data is None:
return cls.create(**data)
else:
previous_data.update(data)
return previous_data
|
fea9c44be08719f0fcca98a1d531a83c9db4c6af | tests/test_urls.py | tests/test_urls.py | import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden')
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
| import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
def test_urls_cache_is_cleared(testdir):
testdir.makepyfile(myurls="""
from django.conf.urls import patterns, url
def fake_view(request):
pass
urlpatterns = patterns('', url(r'first/$', fake_view, name='first'))
""")
testdir.makepyfile("""
from django.core.urlresolvers import reverse, NoReverseMatch
import pytest
@pytest.mark.urls('myurls')
def test_something():
reverse('first')
def test_something_else():
with pytest.raises(NoReverseMatch):
reverse('first')
""")
result = testdir.runpytest()
assert result.ret == 0
| Add test to confirm url cache is cleared | Add test to confirm url cache is cleared
| Python | bsd-3-clause | pombredanne/pytest_django,thedrow/pytest-django,ktosiek/pytest-django,tomviner/pytest-django | import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden')
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
Add test to confirm url cache is cleared | import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
def test_urls_cache_is_cleared(testdir):
testdir.makepyfile(myurls="""
from django.conf.urls import patterns, url
def fake_view(request):
pass
urlpatterns = patterns('', url(r'first/$', fake_view, name='first'))
""")
testdir.makepyfile("""
from django.core.urlresolvers import reverse, NoReverseMatch
import pytest
@pytest.mark.urls('myurls')
def test_something():
reverse('first')
def test_something_else():
with pytest.raises(NoReverseMatch):
reverse('first')
""")
result = testdir.runpytest()
assert result.ret == 0
| <commit_before>import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden')
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
<commit_msg>Add test to confirm url cache is cleared<commit_after> | import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
def test_urls_cache_is_cleared(testdir):
testdir.makepyfile(myurls="""
from django.conf.urls import patterns, url
def fake_view(request):
pass
urlpatterns = patterns('', url(r'first/$', fake_view, name='first'))
""")
testdir.makepyfile("""
from django.core.urlresolvers import reverse, NoReverseMatch
import pytest
@pytest.mark.urls('myurls')
def test_something():
reverse('first')
def test_something_else():
with pytest.raises(NoReverseMatch):
reverse('first')
""")
result = testdir.runpytest()
assert result.ret == 0
| import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden')
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
Add test to confirm url cache is clearedimport pytest
from django.conf import settings
from pytest_django_test.compat import force_text
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
def test_urls_cache_is_cleared(testdir):
testdir.makepyfile(myurls="""
from django.conf.urls import patterns, url
def fake_view(request):
pass
urlpatterns = patterns('', url(r'first/$', fake_view, name='first'))
""")
testdir.makepyfile("""
from django.core.urlresolvers import reverse, NoReverseMatch
import pytest
@pytest.mark.urls('myurls')
def test_something():
reverse('first')
def test_something_else():
with pytest.raises(NoReverseMatch):
reverse('first')
""")
result = testdir.runpytest()
assert result.ret == 0
| <commit_before>import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
pytestmark = pytest.mark.urls('pytest_django_test.urls_overridden')
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
<commit_msg>Add test to confirm url cache is cleared<commit_after>import pytest
from django.conf import settings
from pytest_django_test.compat import force_text
try:
from django.core.urlresolvers import is_valid_path
except ImportError:
from django.core.urlresolvers import resolve, Resolver404
def is_valid_path(path, urlconf=None):
"""Return True if path resolves against default URL resolver
This is a convenience method to make working with "is this a
match?" cases easier, avoiding unnecessarily indented
try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls():
assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
assert is_valid_path('/overridden_url/')
@pytest.mark.urls('pytest_django_test.urls_overridden')
def test_urls_client(client):
response = client.get('/overridden_url/')
assert force_text(response.content) == 'Overridden urlconf works!'
def test_urls_cache_is_cleared(testdir):
testdir.makepyfile(myurls="""
from django.conf.urls import patterns, url
def fake_view(request):
pass
urlpatterns = patterns('', url(r'first/$', fake_view, name='first'))
""")
testdir.makepyfile("""
from django.core.urlresolvers import reverse, NoReverseMatch
import pytest
@pytest.mark.urls('myurls')
def test_something():
reverse('first')
def test_something_else():
with pytest.raises(NoReverseMatch):
reverse('first')
""")
result = testdir.runpytest()
assert result.ret == 0
|
9f0b9b68a3c9dfaa64942e55fc97e435b8eb6f50 | bayespy/nodes/__init__.py | bayespy/nodes/__init__.py | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
| ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Add
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
| Include Add node in user API documentation | DOC: Include Add node in user API documentation
| Python | mit | bayespy/bayespy,jluttine/bayespy | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
DOC: Include Add node in user API documentation | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Add
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
| <commit_before>################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
<commit_msg>DOC: Include Add node in user API documentation<commit_after> | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Add
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
| ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
DOC: Include Add node in user API documentation################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Add
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
| <commit_before>################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
<commit_msg>DOC: Include Add node in user API documentation<commit_after>################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
================
.. currentmodule:: bayespy.nodes
Nodes for Gaussian variables:
.. autosummary::
:toctree: generated/
Gaussian
GaussianARD
Nodes for precision and scale variables:
.. autosummary::
:toctree: generated/
Gamma
Wishart
Exponential
Nodes for modelling Gaussian and precision variables jointly (useful as prior
for Gaussian nodes):
.. autosummary::
:toctree: generated/
GaussianGammaISO
GaussianGammaARD
GaussianWishart
Nodes for discrete count variables:
.. autosummary::
:toctree: generated/
Bernoulli
Binomial
Categorical
Multinomial
Poisson
Nodes for probabilities:
.. autosummary::
:toctree: generated/
Beta
Dirichlet
Nodes for dynamic variables:
.. autosummary::
:toctree: generated/
CategoricalMarkovChain
GaussianMarkovChain
SwitchingGaussianMarkovChain
VaryingGaussianMarkovChain
Other stochastic nodes:
.. autosummary::
:toctree: generated/
Mixture
Deterministic nodes
===================
.. autosummary::
:toctree: generated/
Dot
SumMultiply
Add
Gate
"""
# Currently, model construction and the inference network are not separated so
# the model is constructed using variational message passing nodes.
from bayespy.inference.vmp.nodes import *
|
30f0b99a2233c6009a3c41d9b22e3f946c40c3cf | kitchen/urls.py | kitchen/urls.py | """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| Set root view depending on what views are enabled | Set root view depending on what views are enabled
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen | """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Set root view depending on what views are enabled | """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| <commit_before>"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
<commit_msg>Set root view depending on what views are enabled<commit_after> | """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| """Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Set root view depending on what views are enabled"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| <commit_before>"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
urlpatterns = patterns('',
(r'^$', 'kitchen.dashboard.views.list'),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
<commit_msg>Set root view depending on what views are enabled<commit_after>"""Root URL routing"""
from django.conf.urls.defaults import patterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from kitchen.dashboard import api
import kitchen.settings as settings
if settings.SHOW_LIST_VIEW:
root_view = 'kitchen.dashboard.views.list'
elif settings.SHOW_VIRT_VIEW:
root_view = 'kitchen.dashboard.views.virt'
elif settings.SHOW_GRAPH_VIEW:
root_view = 'kitchen.dashboard.views.graph'
else:
raise Exception("No views enabled! Please edit settings.py.")
urlpatterns = patterns('',
(r'^$', root_view),
(r'^virt/$', 'kitchen.dashboard.views.virt'),
(r'^graph/$', 'kitchen.dashboard.views.graph'),
(r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'),
(r'^api/nodes/(?P<name>\w+)$', api.get_node),
(r'^api/nodes', api.get_nodes),
(r'^api/roles', api.get_roles),
(r'^404', TemplateView.as_view(template_name="404.html")),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
8c05a08d3d0a9a759c7bbbca6a975d5dfc0e166b | apps/auth/db/db.py | apps/auth/db/db.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
| # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import g, current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
def is_authorized(self, **kwargs):
if kwargs.get("user_id") is None:
return False
auth = self.find_one(_id=kwargs.get("user_id"), req=None)
return str(g.auth['_id']) == str(auth.get("_id"))
| Check that the session is the right one | [SD-1422] Check that the session is the right one
| Python | agpl-3.0 | fritzSF/superdesk,verifiedpixel/superdesk,fritzSF/superdesk,akintolga/superdesk,fritzSF/superdesk,superdesk/superdesk-aap,ancafarcas/superdesk,darconny/superdesk,ancafarcas/superdesk,darconny/superdesk,verifiedpixel/superdesk,akintolga/superdesk-aap,Aca-jov/superdesk,sivakuna-aap/superdesk,mugurrus/superdesk,ioanpocol/superdesk-ntb,akintolga/superdesk,superdesk/superdesk,mdhaman/superdesk-aap,pavlovicnemanja92/superdesk,thnkloud9/superdesk,verifiedpixel/superdesk,akintolga/superdesk-aap,petrjasek/superdesk-server,mdhaman/superdesk,petrjasek/superdesk-ntb,akintolga/superdesk-aap,plamut/superdesk,superdesk/superdesk-aap,sivakuna-aap/superdesk,akintolga/superdesk,mugurrus/superdesk,marwoodandrew/superdesk,pavlovicnemanja/superdesk,vied12/superdesk,pavlovicnemanja92/superdesk,vied12/superdesk,vied12/superdesk,petrjasek/superdesk,fritzSF/superdesk,verifiedpixel/superdesk,pavlovicnemanja92/superdesk,ioanpocol/superdesk,vied12/superdesk,superdesk/superdesk,ancafarcas/superdesk,thnkloud9/superdesk,petrjasek/superdesk-ntb,petrjasek/superdesk,fritzSF/superdesk,gbbr/superdesk,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,plamut/superdesk,ioanpocol/superdesk,akintolga/superdesk-aap,superdesk/superdesk,petrjasek/superdesk-ntb,petrjasek/superdesk,superdesk/superdesk-aap,superdesk/superdesk,mdhaman/superdesk-aap,liveblog/superdesk,akintolga/superdesk,sivakuna-aap/superdesk,superdesk/superdesk-aap,liveblog/superdesk,marwoodandrew/superdesk,amagdas/superdesk,mugurrus/superdesk,ioanpocol/superdesk,superdesk/superdesk-ntb,pavlovicnemanja92/superdesk,gbbr/superdesk,darconny/superdesk,amagdas/superdesk,liveblog/superdesk,petrjasek/superdesk,sivakuna-aap/superdesk,amagdas/superdesk,plamut/superdesk,marwoodandrew/superdesk,Aca-jov/superdesk,mdhaman/superdesk,plamut/superdesk,marwoodandrew/superdesk-aap,hlmnrmr/superdesk,marwoodandrew/superdesk-aap,sjunaid/superdesk,mdhaman/superdesk-aap,superdesk/superdesk-ntb,sivakuna-aap/superdesk,superdesk/superdesk-ntb,pavlovicnemanja/superdesk,verifiedpixel/superdesk,sjunaid/superdesk,plamut/superdesk,superdesk/superdesk-ntb,marwoodandrew/superdesk-aap,ioanpocol/superdesk-ntb,thnkloud9/superdesk,mdhaman/superdesk,hlmnrmr/superdesk,amagdas/superdesk,petrjasek/superdesk-server,marwoodandrew/superdesk-aap,pavlovicnemanja92/superdesk,liveblog/superdesk,marwoodandrew/superdesk,hlmnrmr/superdesk,pavlovicnemanja/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,Aca-jov/superdesk,mdhaman/superdesk-aap,gbbr/superdesk,petrjasek/superdesk-ntb,akintolga/superdesk,vied12/superdesk,amagdas/superdesk,sjunaid/superdesk | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
[SD-1422] Check that the session is the right one | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import g, current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
def is_authorized(self, **kwargs):
if kwargs.get("user_id") is None:
return False
auth = self.find_one(_id=kwargs.get("user_id"), req=None)
return str(g.auth['_id']) == str(auth.get("_id"))
| <commit_before># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
<commit_msg>[SD-1422] Check that the session is the right one<commit_after> | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import g, current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
def is_authorized(self, **kwargs):
if kwargs.get("user_id") is None:
return False
auth = self.find_one(_id=kwargs.get("user_id"), req=None)
return str(g.auth['_id']) == str(auth.get("_id"))
| # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
[SD-1422] Check that the session is the right one# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import g, current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
def is_authorized(self, **kwargs):
if kwargs.get("user_id") is None:
return False
auth = self.find_one(_id=kwargs.get("user_id"), req=None)
return str(g.auth['_id']) == str(auth.get("_id"))
| <commit_before># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
<commit_msg>[SD-1422] Check that the session is the right one<commit_after># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import bcrypt
from apps.auth.service import AuthService
from superdesk import get_resource_service
from superdesk.errors import CredentialsAuthError
from flask import g, current_app as app
class DbAuthService(AuthService):
def authenticate(self, credentials):
user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username'))
if not user:
raise CredentialsAuthError(credentials)
password = credentials.get('password').encode('UTF-8')
hashed = user.get('password').encode('UTF-8')
if not (password and hashed):
raise CredentialsAuthError(credentials)
try:
rehashed = bcrypt.hashpw(password, hashed)
if hashed != rehashed:
raise CredentialsAuthError(credentials)
except ValueError:
raise CredentialsAuthError(credentials)
return user
def on_deleted(self, doc):
'''
:param doc: A deleted auth doc AKA a session
:return:
'''
# notify that the session has ended
app.on_session_end(doc['user'], doc['_id'])
def is_authorized(self, **kwargs):
if kwargs.get("user_id") is None:
return False
auth = self.find_one(_id=kwargs.get("user_id"), req=None)
return str(g.auth['_id']) == str(auth.get("_id"))
|
6ff11990b7d22be537eb6cbf4f373e1e416ecaf2 | spiralgalaxygame/tests/test_callee.py | spiralgalaxygame/tests/test_callee.py | import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func(): pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
| import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func():
pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
| Break an empty func definition into multiple lines for clearer coverage output. | Break an empty func definition into multiple lines for clearer coverage output.
| Python | agpl-3.0 | nejucomo/sgg,nejucomo/sgg,nejucomo/sgg | import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func(): pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
Break an empty func definition into multiple lines for clearer coverage output. | import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func():
pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
| <commit_before>import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func(): pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
<commit_msg>Break an empty func definition into multiple lines for clearer coverage output.<commit_after> | import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func():
pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
| import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func(): pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
Break an empty func definition into multiple lines for clearer coverage output.import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func():
pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
| <commit_before>import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func(): pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
<commit_msg>Break an empty func definition into multiple lines for clearer coverage output.<commit_after>import unittest
from spiralgalaxygame import callee
class calleeTests (unittest.TestCase):
def test_str_of_func(self):
def my_func():
pass
self.assertEqual(callee.name_of(my_func), 'my_func')
def test_str_of_type(self):
class MyType (object): pass
self.assertEqual(callee.name_of(MyType), 'MyType')
def test_str_of_method(self):
class MyType (object):
def my_method(self):
pass
self.assertEqual(callee.name_of(MyType.my_method), 'MyType.my_method')
|
ad813973421ed828f724a999fabbc12c4e429247 | src/nodeconductor_paas_oracle/filters.py | src/nodeconductor_paas_oracle/filters.py | import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
| import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
| Use generic state filter instead of custom one | Use generic state filter instead of custom one
- ITACLOUD-6837
| Python | mit | opennode/nodeconductor-paas-oracle | import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
Use generic state filter instead of custom one
- ITACLOUD-6837 | import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
| <commit_before>import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
<commit_msg>Use generic state filter instead of custom one
- ITACLOUD-6837<commit_after> | import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
| import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
Use generic state filter instead of custom one
- ITACLOUD-6837import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
| <commit_before>import django_filters
from .models import Deployment
class DeploymentFilter(django_filters.FilterSet):
db_name = django_filters.CharFilter()
state = django_filters.CharFilter()
class Meta(object):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
<commit_msg>Use generic state filter instead of custom one
- ITACLOUD-6837<commit_after>import django_filters
from nodeconductor.structure.filters import BaseResourceStateFilter
from .models import Deployment
class DeploymentFilter(BaseResourceStateFilter):
db_name = django_filters.CharFilter()
class Meta(BaseResourceStateFilter.Meta):
model = Deployment
fields = [
'db_name',
'state',
]
order_by = [
'state',
# desc
'-state',
]
|
d4da069b43174482f3a75e9553e8283be905fa16 | cla_public/apps/base/filters.py | cla_public/apps/base/filters.py | # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
| # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from urlparse import urlparse, parse_qs
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
| Add Jinja filter to convert URL params to dict | BE: Add Jinja filter to convert URL params to dict
| Python | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
BE: Add Jinja filter to convert URL params to dict | # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from urlparse import urlparse, parse_qs
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
| <commit_before># -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
<commit_msg>BE: Add Jinja filter to convert URL params to dict<commit_after> | # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from urlparse import urlparse, parse_qs
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
| # -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
BE: Add Jinja filter to convert URL params to dict# -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from urlparse import urlparse, parse_qs
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
| <commit_before># -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
<commit_msg>BE: Add Jinja filter to convert URL params to dict<commit_after># -*- coding: utf-8 -*-
"Jinja custom filters"
import re
from urlparse import urlparse, parse_qs
from cla_public.apps.base import base
from babel.dates import format_datetime
@base.app_template_filter()
def datetime(dt, format='medium', locale='en_GB'):
if format == 'full':
format = "EEEE, d MMMM y 'at' HH:mm"
elif format == 'medium':
format = "EE, dd/MM/y 'at' h:mma"
elif format == 'short':
format = "dd/MM/y, h:mma"
return format_datetime(dt, format, locale=locale)
@base.app_template_filter()
def url_to_human(value):
return re.sub(r'(^https?://)|(/$)', '', value)
@base.app_template_filter()
def human_to_url(value):
return re.sub(r'^((?!https?://).*)', r'http://\1', value)
@base.app_template_filter()
def query_to_dict(value, prop=None):
result = parse_qs(urlparse(value).query)
if prop:
result = result[prop]
return result
|
cd374366dc6d49cc543a037fba8398e5b724c382 | tabula/util.py | tabula/util.py | import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| Remove textwrap because python 2.7 lacks indent() function | Remove textwrap because python 2.7 lacks indent() function
| Python | mit | chezou/tabula-py | import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
Remove textwrap because python 2.7 lacks indent() function | import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| <commit_before>import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
<commit_msg>Remove textwrap because python 2.7 lacks indent() function<commit_after> | import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
Remove textwrap because python 2.7 lacks indent() functionimport warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| <commit_before>import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
<commit_msg>Remove textwrap because python 2.7 lacks indent() function<commit_after>import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
ab640dc35ff87bc32e1e3b54012f69610e73d8d0 | sync_scheduler.py | sync_scheduler.py | from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
import kombu
from datetime import datetime
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
}
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| Make scheduler do primary reads only | Make scheduler do primary reads only | Python | apache-2.0 | cmgrote/tapiriik,niosus/tapiriik,gavioto/tapiriik,dlenski/tapiriik,olamy/tapiriik,cmgrote/tapiriik,olamy/tapiriik,cheatos101/tapiriik,gavioto/tapiriik,marxin/tapiriik,niosus/tapiriik,cheatos101/tapiriik,cheatos101/tapiriik,mduggan/tapiriik,campbellr/tapiriik,abs0/tapiriik,mjnbike/tapiriik,niosus/tapiriik,marxin/tapiriik,niosus/tapiriik,olamy/tapiriik,mjnbike/tapiriik,cgourlay/tapiriik,mduggan/tapiriik,campbellr/tapiriik,abhijit86k/tapiriik,brunoflores/tapiriik,dlenski/tapiriik,olamy/tapiriik,marxin/tapiriik,cgourlay/tapiriik,cpfair/tapiriik,cpfair/tapiriik,gavioto/tapiriik,campbellr/tapiriik,mjnbike/tapiriik,gavioto/tapiriik,mjnbike/tapiriik,abs0/tapiriik,brunoflores/tapiriik,abs0/tapiriik,abhijit86k/tapiriik,cheatos101/tapiriik,brunoflores/tapiriik,cmgrote/tapiriik,cpfair/tapiriik,mduggan/tapiriik,dmschreiber/tapiriik,marxin/tapiriik,abs0/tapiriik,mduggan/tapiriik,dmschreiber/tapiriik,cmgrote/tapiriik,abhijit86k/tapiriik,cpfair/tapiriik,dmschreiber/tapiriik,brunoflores/tapiriik,dlenski/tapiriik,dmschreiber/tapiriik,abhijit86k/tapiriik,cgourlay/tapiriik,cgourlay/tapiriik,dlenski/tapiriik,campbellr/tapiriik | from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
import kombu
from datetime import datetime
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
}
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
Make scheduler do primary reads only | from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| <commit_before>from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
import kombu
from datetime import datetime
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
}
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
<commit_msg>Make scheduler do primary reads only<commit_after> | from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
import kombu
from datetime import datetime
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
}
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
Make scheduler do primary reads onlyfrom tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
| <commit_before>from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
import kombu
from datetime import datetime
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
}
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
<commit_msg>Make scheduler do primary reads only<commit_after>from tapiriik.database import db
from tapiriik.messagequeue import mq
from tapiriik.sync import Sync
from datetime import datetime
from pymongo.read_preferences import ReadPreference
import kombu
import time
Sync.InitializeWorkerBindings()
producer = kombu.Producer(Sync._channel, Sync._exchange)
while True:
queueing_at = datetime.utcnow()
users = db.users.find(
{
"NextSynchronization": {"$lte": datetime.utcnow()}
},
{
"_id": True,
"SynchronizationHostRestriction": True
},
read_preference=ReadPreference.PRIMARY
)
scheduled_ids = set()
for user in users:
producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "")
scheduled_ids.add(user["_id"])
print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow()))
db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True)
time.sleep(1)
|
a7328bd229070126ca5b09bb1c9fe4c5e319bb04 | members/urls.py | members/urls.py | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
| from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| Add url for user's profile | Add url for user's profile
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
Add url for user's profile | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
<commit_msg>Add url for user's profile<commit_after> | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
Add url for user's profilefrom django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
<commit_msg>Add url for user's profile<commit_after>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
|
dbc7ad0dad6161d19f65bbf186d84d23628cfd16 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
entry_points={
'console_scripts': [
'pic2map = pic2map.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| Add entry point for the CLI script | Add entry point for the CLI script
| Python | mit | jcollado/pic2map,jcollado/pic2map,jcollado/pic2map | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
Add entry point for the CLI script | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
entry_points={
'console_scripts': [
'pic2map = pic2map.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
<commit_msg>Add entry point for the CLI script<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
entry_points={
'console_scripts': [
'pic2map = pic2map.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
Add entry point for the CLI script#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
entry_points={
'console_scripts': [
'pic2map = pic2map.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
<commit_msg>Add entry point for the CLI script<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
'coverage',
]
setup(
name='pic2map',
version='0.1.0',
description="Display pictures location in a map",
long_description=readme + '\n\n' + history,
author="Javier Collado",
author_email='jcollado@nowsecure.com',
url='https://github.com/jcollado/pic2map',
packages=[
'pic2map',
],
package_dir={'pic2map':
'pic2map'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='picture map location',
entry_points={
'console_scripts': [
'pic2map = pic2map.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
|
d94853ee368fdf4a8ef80c72dd22a9f2b2074ab3 | setup.py | setup.py | from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| Set new minimum django-appconf version | Set new minimum django-appconf version
| Python | mit | GeoNode/geonode-user-accounts,mysociety/django-user-accounts,nderituedwin/django-user-accounts,nderituedwin/django-user-accounts,pinax/django-user-accounts,ntucker/django-user-accounts,jpotterm/django-user-accounts,jawed123/django-user-accounts,GeoNode/geonode-user-accounts,jawed123/django-user-accounts,pinax/django-user-accounts,jpotterm/django-user-accounts,mysociety/django-user-accounts,ntucker/django-user-accounts | from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
Set new minimum django-appconf version | from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| <commit_before>from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
<commit_msg>Set new minimum django-appconf version<commit_after> | from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
Set new minimum django-appconf versionfrom setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| <commit_before>from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
<commit_msg>Set new minimum django-appconf version<commit_after>from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
|
4d83306f89710d70571e2b2fc2f3a61af8b5793b | setup.py | setup.py | from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli', 'boto'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
| from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli==1.12.2'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
| Fix awscli to 1.12.2 as there are errors in later versions | Fix awscli to 1.12.2 as there are errors in later versions
| Python | mit | otype/aws-helpers,otype/aws-helpers | from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli', 'boto'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
Fix awscli to 1.12.2 as there are errors in later versions | from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli==1.12.2'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
| <commit_before>from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli', 'boto'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
<commit_msg>Fix awscli to 1.12.2 as there are errors in later versions<commit_after> | from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli==1.12.2'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
| from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli', 'boto'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
Fix awscli to 1.12.2 as there are errors in later versionsfrom setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli==1.12.2'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
| <commit_before>from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli', 'boto'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
<commit_msg>Fix awscli to 1.12.2 as there are errors in later versions<commit_after>from setuptools import setup
setup(
name='aws-helpers',
description='Set of AWS helper scripts',
url='https://github.com/otype/aws-helpers',
author='Hans-Gunther Schmidt',
author_email='hans@otype.de',
version='0.1',
install_requires=['awscli==1.12.2'],
scripts=['src/aws-instances', 'src/aws-instances.py']
)
|
49b13a33d37daa513345f629f5466f9807e24b49 | setup.py | setup.py | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| Add POSIX as supported OS type | Add POSIX as supported OS type
| Python | apache-2.0 | aneilbaboo/shellvars-py | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
Add POSIX as supported OS type | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| <commit_before>from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
<commit_msg>Add POSIX as supported OS type<commit_after> | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
Add POSIX as supported OS typefrom setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| <commit_before>from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
<commit_msg>Add POSIX as supported OS type<commit_after>from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmail.com',
license='Apache2',
py_modules=['shellvars'],
long_description = read('README.md'),
url="http://github.com/aneilbaboo/shellvars-py",
author="Aneil Mallavarapu",
include_package_data = True,
classifiers = [
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
166f3d59e40ac795bc929235f8da8e192d25ed93 | setup.py | setup.py | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1.dev7',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| Revert "Pin to same version as on production." | Revert "Pin to same version as on production."
This reverts commit cd93e130ada22ae66c406ad67101e3b1bf892053.
| Python | apache-2.0 | uw-it-aca/mdot,charlon/mdot,charlon/mdot,uw-it-aca/mdot,charlon/mdot,uw-it-aca/mdot,uw-it-aca/mdot | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1.dev7',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
Revert "Pin to same version as on production."
This reverts commit cd93e130ada22ae66c406ad67101e3b1bf892053. | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| <commit_before>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1.dev7',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
<commit_msg>Revert "Pin to same version as on production."
This reverts commit cd93e130ada22ae66c406ad67101e3b1bf892053.<commit_after> | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1.dev7',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
Revert "Pin to same version as on production."
This reverts commit cd93e130ada22ae66c406ad67101e3b1bf892053.import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| <commit_before>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients==1.1.dev7',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
<commit_msg>Revert "Pin to same version as on production."
This reverts commit cd93e130ada22ae66c406ad67101e3b1bf892053.<commit_after>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mdot',
version='0.1',
packages=['mdot'],
include_package_data=True,
install_requires=[
'setuptools',
'django<1.9rc1',
'django-compressor',
'django_mobileesp',
'uw-restclients<2.0',
'django-htmlmin',
],
license='Apache License, Version 2.0',
description='A Django app to ...',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
701e1ca3f71653fe472a010b1f1ef0ec2be1eaf1 | setup.py | setup.py | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
| """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| Fix missing templates in source packages | Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
| Python | mit | kevinconway/rpmvenv | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com> | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| <commit_before>"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
<commit_msg>Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com><commit_after> | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
| <commit_before>"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.1',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
)
<commit_msg>Fix missing templates in source packages
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com><commit_after>"""Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.1.2',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager for Python virtualenv.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='MIT',
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
install_requires=[
'jinja2',
'venvctrl',
'argparse',
'pyyaml',
],
entry_points={
'console_scripts': [
'rpmvenv = rpmvenv.cmd:main',
],
},
package_data={
"rpmvenv": ["templates/*"],
},
)
|
66dcfe1561f7ab2424aec58801f547001575b885 | setup.py | setup.py | from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.1'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync'
]
)
| from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.2'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync.py'
]
)
| Fix script name Bump to 0.1.2 | Fix script name
Bump to 0.1.2
| Python | mit | sashgorokhov/gmusicsync | from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.1'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync'
]
)
Fix script name
Bump to 0.1.2 | from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.2'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync.py'
]
)
| <commit_before>from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.1'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync'
]
)
<commit_msg>Fix script name
Bump to 0.1.2<commit_after> | from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.2'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync.py'
]
)
| from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.1'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync'
]
)
Fix script name
Bump to 0.1.2from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.2'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync.py'
]
)
| <commit_before>from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.1'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync'
]
)
<commit_msg>Fix script name
Bump to 0.1.2<commit_after>from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
VERSION = '0.1.2'
setup(
install_requires=['gmusicapi', 'colorama', 'requests', 'tqdm', 'eyed3'],
name='gmusicsync',
version=VERSION,
py_modules=['gmusicsync'],
url='https://github.com/sashgorokhov/gmusicsync',
download_url='https://github.com/sashgorokhov/gmusicsync/archive/v%s.zip' % VERSION,
keywords=['gmusic', 'google music', 'music'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Multimedia :: Sound/Audio',
],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description='Google Music playlist syncing to offline destination',
scripts=[
'gmusicsync.py'
]
)
|
0793f8dcb6ed27832e7d0adfb920d9c70813f3c7 | tasks.py | tasks.py | # -*- coding: utf-8 -*-
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
| # -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
| Use new invoke's context parameter | Use new invoke's context parameter
| Python | apache-2.0 | miso-belica/sumy,miso-belica/sumy | # -*- coding: utf-8 -*-
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
Use new invoke's context parameter | # -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
| <commit_before># -*- coding: utf-8 -*-
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
<commit_msg>Use new invoke's context parameter<commit_after> | # -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
| # -*- coding: utf-8 -*-
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
Use new invoke's context parameter# -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
| <commit_before># -*- coding: utf-8 -*-
from invoke import task, run
@task
def clean():
run("rm -rf .coverage dist build")
@task(clean, default=True)
def test():
run("py.test")
@task(test)
def install():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py develop")
@task(test)
def release():
run("pandoc --from=markdown --to=rst README.md -o README.rst")
run("python setup.py register sdist bdist_wheel")
run("twine upload dist/*")
@task(test)
def bump(version="patch"):
run("bumpversion %s" % version)
run("git commit --amend")
<commit_msg>Use new invoke's context parameter<commit_after># -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("py.test")
@task(test)
def install(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py develop")
@task(test)
def release(context):
context.run("pandoc --from=markdown --to=rst README.md -o README.rst")
context.run("python setup.py register sdist bdist_wheel")
context.run("twine upload dist/*")
@task(test)
def bump(context, version="patch"):
context.run("bumpversion %s" % version)
context.run("git commit --amend")
|
f108da5ab277187fa146fc7db060f706b5e3f0ed | rest/authorView.py | rest/authorView.py | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
authSer = AuthorSerializer(author)
return JSONResponse(authSer.data)
| # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
context = {'addFriends': True}
authSer = AuthorSerializer(author, context=context)
return JSONResponse(authSer.data)
| Add friends to author view. | Add friends to author view.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
authSer = AuthorSerializer(author)
return JSONResponse(authSer.data)
Add friends to author view. | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
context = {'addFriends': True}
authSer = AuthorSerializer(author, context=context)
return JSONResponse(authSer.data)
| <commit_before># Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
authSer = AuthorSerializer(author)
return JSONResponse(authSer.data)
<commit_msg>Add friends to author view.<commit_after> | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
context = {'addFriends': True}
authSer = AuthorSerializer(author, context=context)
return JSONResponse(authSer.data)
| # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
authSer = AuthorSerializer(author)
return JSONResponse(authSer.data)
Add friends to author view.# Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
context = {'addFriends': True}
authSer = AuthorSerializer(author, context=context)
return JSONResponse(authSer.data)
| <commit_before># Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
authSer = AuthorSerializer(author)
return JSONResponse(authSer.data)
<commit_msg>Add friends to author view.<commit_after># Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = getAuthor(request, aid)
context = {'addFriends': True}
authSer = AuthorSerializer(author, context=context)
return JSONResponse(authSer.data)
|
62f9bf4cb8d02b80c0589c68a308bcba28524d14 | bootstrap_paginator/templatetags/paginator.py | bootstrap_paginator/templatetags/paginator.py |
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urllib.urlencode(get))
|
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urlencode(get))
| Use a py3 compatible urlencode | Use a py3 compatible urlencode | Python | mit | defrex/django-bootstrap-paginator |
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urllib.urlencode(get))
Use a py3 compatible urlencode |
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urlencode(get))
| <commit_before>
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urllib.urlencode(get))
<commit_msg>Use a py3 compatible urlencode<commit_after> |
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urlencode(get))
|
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urllib.urlencode(get))
Use a py3 compatible urlencode
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urlencode(get))
| <commit_before>
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urllib.urlencode(get))
<commit_msg>Use a py3 compatible urlencode<commit_after>
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
adjacent_pages = 2
page = context.get('page_obj', page)
paginator = page.paginator
startPage = page.number - adjacent_pages
if startPage <= adjacent_pages + 1:
startPage = 1
endPage = page.number + adjacent_pages + 1
page_numbers = [
n for n in range(startPage, endPage)
if n >= 1 and n <= paginator.num_pages
]
return {
'page': page,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': context['request'],
}
@register.simple_tag(takes_context=True)
def append_to_get(context, **kwargs):
get = context['request'].GET.copy()
get.update(kwargs)
return '?{1}'.format(urlencode(get))
|
547bc6520652b02dcbe908c98b7483869c9ee831 | mysite/context_processors.py | mysite/context_processors.py | from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
| from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
'MEDIA_URL',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
| Make sure MEDIA_URL is available in the context of every template | Make sure MEDIA_URL is available in the context of every template
| Python | agpl-3.0 | mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative | from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
Make sure MEDIA_URL is available in the context of every template | from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
'MEDIA_URL',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
| <commit_before>from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
<commit_msg>Make sure MEDIA_URL is available in the context of every template<commit_after> | from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
'MEDIA_URL',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
| from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
Make sure MEDIA_URL is available in the context of every templatefrom django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
'MEDIA_URL',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
| <commit_before>from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
<commit_msg>Make sure MEDIA_URL is available in the context of every template<commit_after>from django.conf import settings
SETTINGS_TO_ADD = (
'GOOGLE_ANALYTICS_ACCOUNT',
'SOURCE_HINTS',
'MEDIA_URL',
)
def add_settings(request):
"""Add some selected settings values to the context"""
return {
'settings': {
k: getattr(settings, k) for k in SETTINGS_TO_ADD
}
}
|
f974e39c216067de5af68b3016fb35f129556e44 | mscgen/setup.py | mscgen/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='mscgen Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| Improve package short and long descriptions | mscgen: Improve package short and long descriptions
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
mscgen: Improve package short and long descriptions | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='mscgen Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
<commit_msg>mscgen: Improve package short and long descriptions<commit_after> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='mscgen Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
mscgen: Improve package short and long descriptions# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='mscgen Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension mscgen',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
<commit_msg>mscgen: Improve package short and long descriptions<commit_after># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='mscgen Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
|
169eb4826ee823b28fc98477af81a69c6c521acc | client/__init__.py | client/__init__.py | __version__ = 'v1.4.3'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.4.4'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| Bump version number to v1.4.4. | Bump version number to v1.4.4.
| Python | apache-2.0 | jathak/ok-client,Cal-CS-61A-Staff/ok-client | __version__ = 'v1.4.3'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
Bump version number to v1.4.4. | __version__ = 'v1.4.4'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| <commit_before>__version__ = 'v1.4.3'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
<commit_msg>Bump version number to v1.4.4.<commit_after> | __version__ = 'v1.4.4'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.4.3'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
Bump version number to v1.4.4.__version__ = 'v1.4.4'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| <commit_before>__version__ = 'v1.4.3'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
<commit_msg>Bump version number to v1.4.4.<commit_after>__version__ = 'v1.4.4'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
|
465b39b97ec1fa619e96a0c811a496216c275aaf | src/gui/Gui.py | src/gui/Gui.py | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) | Fix error in getting mouse posititions. | Fix error in getting mouse posititions.
| Python | mit | cthit/CodeIT | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)Fix error in getting mouse posititions. | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) | <commit_before>import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)<commit_msg>Fix error in getting mouse posititions.<commit_after> | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) | import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)Fix error in getting mouse posititions.import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) | <commit_before>import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)<commit_msg>Fix error in getting mouse posititions.<commit_after>import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen) |
9c086abd428732080257d073bb6b36f04171f7d1 | utils.py | utils.py | from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
| from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
| Fix date range in worklog_period | Fix date range in worklog_period
| Python | bsd-3-clause | dongguangming/pdfdocument,matthiask/pdfdocument | from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
Fix date range in worklog_period | from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
| <commit_before>from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
<commit_msg>Fix date range in worklog_period<commit_after> | from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
| from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
Fix date range in worklog_periodfrom datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
| <commit_before>from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
<commit_msg>Fix date range in worklog_period<commit_after>from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
|
ea2d72473c958de90582e1d4ccfc77af1d578b24 | test_stack.py | test_stack.py | from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
stack.pop()
stack.pop()
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
| from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
assert stack.pop() == "grilled cheese"
assert stack.pop() == "steak"
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
def test_empty_stack_peek():
stack = Stack()
with pytest.raises(ValueError):
stack.peek()
| Add test for peek on empty stack | Add test for peek on empty stack
| Python | mit | jwarren116/data-structures-deux | from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
stack.pop()
stack.pop()
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
Add test for peek on empty stack | from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
assert stack.pop() == "grilled cheese"
assert stack.pop() == "steak"
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
def test_empty_stack_peek():
stack = Stack()
with pytest.raises(ValueError):
stack.peek()
| <commit_before>from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
stack.pop()
stack.pop()
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
<commit_msg>Add test for peek on empty stack<commit_after> | from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
assert stack.pop() == "grilled cheese"
assert stack.pop() == "steak"
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
def test_empty_stack_peek():
stack = Stack()
with pytest.raises(ValueError):
stack.peek()
| from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
stack.pop()
stack.pop()
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
Add test for peek on empty stackfrom stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
assert stack.pop() == "grilled cheese"
assert stack.pop() == "steak"
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
def test_empty_stack_peek():
stack = Stack()
with pytest.raises(ValueError):
stack.peek()
| <commit_before>from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
stack.pop()
stack.pop()
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
<commit_msg>Add test for peek on empty stack<commit_after>from stack import Stack
import pytest
def test_stack_push():
stack = Stack()
stack.push("bacon")
assert stack.top.value == "bacon"
assert stack.peek() == "bacon"
def test_stack_push_multi():
stack = Stack()
stack.push("bacon")
stack.push("steak")
stack.push("grilled cheese")
assert stack.pop() == "grilled cheese"
assert stack.pop() == "steak"
assert stack.pop() == "bacon"
def test_empty_stack_pop():
stack = Stack()
with pytest.raises(ValueError):
stack.pop()
def test_empty_stack_peek():
stack = Stack()
with pytest.raises(ValueError):
stack.peek()
|
65b4cca13c16e9de0d469ec036c1440dd598b3a0 | learning_journal/__init__.py | learning_journal/__init__.py | from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
| from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
import os
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
#authentication
dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue')
authentication_policy = AuthTktAuthenticationPolicy(
secret= dummy_auth,
hashalg='sha512',
)
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
| Add authN/authZ. Start auth process in main() | Add authN/authZ. Start auth process in main()
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal | from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
Add authN/authZ. Start auth process in main() | from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
import os
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
#authentication
dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue')
authentication_policy = AuthTktAuthenticationPolicy(
secret= dummy_auth,
hashalg='sha512',
)
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
| <commit_before>from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
<commit_msg>Add authN/authZ. Start auth process in main()<commit_after> | from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
import os
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
#authentication
dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue')
authentication_policy = AuthTktAuthenticationPolicy(
secret= dummy_auth,
hashalg='sha512',
)
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
| from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
Add authN/authZ. Start auth process in main()from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
import os
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
#authentication
dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue')
authentication_policy = AuthTktAuthenticationPolicy(
secret= dummy_auth,
hashalg='sha512',
)
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
| <commit_before>from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
<commit_msg>Add authN/authZ. Start auth process in main()<commit_after>from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
import os
from .models import (
DBSession,
Base,
)
def make_session(settings):
from sqlalchemy.orm import sessionmaker
engine = engine_from_config(settings, 'sqlalchemy')
Session = sessionmaker(bind=engine)
return Session()
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
#authentication
dummy_auth = os.environ.get(JOURNAL_AUTH_SECRET, 'testvalue')
authentication_policy = AuthTktAuthenticationPolicy(
secret= dummy_auth,
hashalg='sha512',
)
config = Configurator(settings=settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('detail_view', '/detail/{this_id}')
config.add_route('add_view', '/add')
config.add_route('edit_view', '/detail/{this_id}/edit')
config.scan()
return config.make_wsgi_app()
|
0158579b9a6c729e7af9a543caeef25018e07834 | conda_build/ldd.py | conda_build/ldd.py | from __future__ import absolute_import, division, print_function
import re
import subprocess
from conda_build import post
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
| from __future__ import absolute_import, division, print_function
import re
import subprocess
import json
from os.path import join
from conda.install import rm_rf
from conda_build import post
from conda_build.config import config
from conda_build.build import create_env
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
def get_package_linkages(pkg):
rm_rf(config.test_prefix)
specs = ['%s %s %s' % (pkg.rsplit('.tar.bz2', 1)[0].rsplit('-', 2))]
create_env(config.test_prefix, specs)
res = {}
with open(join(config.test_prefix, 'conda-meta', '-'.join(specs[0]) +
'.json')) as f:
data = json.load(f)
files = data['files']
for f in files:
if post.is_obj(f):
res[f] = ldd(f)
return res
| Add first pass at a get_package_linkages function | Add first pass at a get_package_linkages function
| Python | bsd-3-clause | takluyver/conda-build,takluyver/conda-build,sandhujasmine/conda-build,frol/conda-build,frol/conda-build,ilastik/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,rmcgibbo/conda-build,dan-blanchard/conda-build,sandhujasmine/conda-build,ilastik/conda-build,ilastik/conda-build,shastings517/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,shastings517/conda-build,rmcgibbo/conda-build,takluyver/conda-build,shastings517/conda-build,mwcraig/conda-build,frol/conda-build | from __future__ import absolute_import, division, print_function
import re
import subprocess
from conda_build import post
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
Add first pass at a get_package_linkages function | from __future__ import absolute_import, division, print_function
import re
import subprocess
import json
from os.path import join
from conda.install import rm_rf
from conda_build import post
from conda_build.config import config
from conda_build.build import create_env
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
def get_package_linkages(pkg):
rm_rf(config.test_prefix)
specs = ['%s %s %s' % (pkg.rsplit('.tar.bz2', 1)[0].rsplit('-', 2))]
create_env(config.test_prefix, specs)
res = {}
with open(join(config.test_prefix, 'conda-meta', '-'.join(specs[0]) +
'.json')) as f:
data = json.load(f)
files = data['files']
for f in files:
if post.is_obj(f):
res[f] = ldd(f)
return res
| <commit_before>from __future__ import absolute_import, division, print_function
import re
import subprocess
from conda_build import post
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
<commit_msg>Add first pass at a get_package_linkages function<commit_after> | from __future__ import absolute_import, division, print_function
import re
import subprocess
import json
from os.path import join
from conda.install import rm_rf
from conda_build import post
from conda_build.config import config
from conda_build.build import create_env
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
def get_package_linkages(pkg):
rm_rf(config.test_prefix)
specs = ['%s %s %s' % (pkg.rsplit('.tar.bz2', 1)[0].rsplit('-', 2))]
create_env(config.test_prefix, specs)
res = {}
with open(join(config.test_prefix, 'conda-meta', '-'.join(specs[0]) +
'.json')) as f:
data = json.load(f)
files = data['files']
for f in files:
if post.is_obj(f):
res[f] = ldd(f)
return res
| from __future__ import absolute_import, division, print_function
import re
import subprocess
from conda_build import post
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
Add first pass at a get_package_linkages functionfrom __future__ import absolute_import, division, print_function
import re
import subprocess
import json
from os.path import join
from conda.install import rm_rf
from conda_build import post
from conda_build.config import config
from conda_build.build import create_env
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
def get_package_linkages(pkg):
rm_rf(config.test_prefix)
specs = ['%s %s %s' % (pkg.rsplit('.tar.bz2', 1)[0].rsplit('-', 2))]
create_env(config.test_prefix, specs)
res = {}
with open(join(config.test_prefix, 'conda-meta', '-'.join(specs[0]) +
'.json')) as f:
data = json.load(f)
files = data['files']
for f in files:
if post.is_obj(f):
res[f] = ldd(f)
return res
| <commit_before>from __future__ import absolute_import, division, print_function
import re
import subprocess
from conda_build import post
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
<commit_msg>Add first pass at a get_package_linkages function<commit_after>from __future__ import absolute_import, division, print_function
import re
import subprocess
import json
from os.path import join
from conda.install import rm_rf
from conda_build import post
from conda_build.config import config
from conda_build.build import create_env
LDD_RE = re.compile(r'\s*(.*?)\s*=>\s*(.*?)\s*\(.*\)')
LDD_NOT_FOUND_RE = re.compile(r'\s*(.*?)\s*=>\s*not found')
def ldd(path):
"thin wrapper around ldd"
lines = subprocess.check_output(['ldd', path]).decode('utf-8').splitlines()
res = []
for line in lines:
if '=>' not in line:
continue
assert line[0] == '\t', (path, line)
m = LDD_RE.match(line)
if m:
res.append(m.groups())
continue
m = LDD_NOT_FOUND_RE.match(line)
if m:
res.append((m.group(1), 'not found'))
continue
if 'ld-linux' in line:
continue
raise RuntimeError("Unexpected output from ldd: %s" % line)
return res
def get_package_linkages(pkg):
rm_rf(config.test_prefix)
specs = ['%s %s %s' % (pkg.rsplit('.tar.bz2', 1)[0].rsplit('-', 2))]
create_env(config.test_prefix, specs)
res = {}
with open(join(config.test_prefix, 'conda-meta', '-'.join(specs[0]) +
'.json')) as f:
data = json.load(f)
files = data['files']
for f in files:
if post.is_obj(f):
res[f] = ldd(f)
return res
|
b2b939e13a5bcdabe09e85d7f940052f4fec8f27 | events/urls.py | events/urls.py | from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
| from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
| Allow empty calendar to be drawn | Allow empty calendar to be drawn
| Python | agpl-3.0 | mlhamel/agendadulibre,mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord | from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
Allow empty calendar to be drawn | from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
| <commit_before>from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
<commit_msg>Allow empty calendar to be drawn<commit_after> | from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
| from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
Allow empty calendar to be drawnfrom django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
| <commit_before>from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
<commit_msg>Allow empty calendar to be drawn<commit_after>from django.conf.urls.defaults import *
from django.views.generic import list_detail
from django.views.generic import date_based
from agenda.events.models import Event
general_info = {
"queryset" : Event.objects.filter(moderated=True),
"template_object_name" : "event",
}
list_info = {
"paginate_by": 25,
}
month_list_info = {
"month_format": "%m",
"date_field": "start_time",
"allow_future": True,
"allow_empty": True,
}
event_info = general_info
event_list_info = dict(general_info, **list_info)
event_list_month_info = dict(general_info, **month_list_info)
urlpatterns = patterns('',
(r'^$', list_detail.object_list, event_list_info),
(r'^(?P<object_id>\d+)/$', list_detail.object_detail, event_info),
(r'^(?P<year>\d+)/(?P<month>\d+)/$', date_based.archive_month, event_list_month_info),
)
|
fe225e4f4d9df8c913ad3ed7a6f18f51ca6a0d2a | LiSE/setup.py | LiSE/setup.py | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
| # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
| Include the examples in the LiSE package | Include the examples in the LiSE package
| Python | agpl-3.0 | LogicalDash/LiSE,LogicalDash/LiSE | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
Include the examples in the LiSE package | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
| <commit_before># This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
<commit_msg>Include the examples in the LiSE package<commit_after> | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
| # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
Include the examples in the LiSE package# This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
| <commit_before># This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
<commit_msg>Include the examples in the LiSE package<commit_after># This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"gorm>=0.8.3",
],
)
|
298cae5d7f15a667195b96c92c4b4320487c922c | tests/test_backends.py | tests/test_backends.py | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('thumbnails.backends.cache_get', lambda x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
| # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
| Fix failing mock of cache backend | Fix failing mock of cache backend
| Python | mit | relekang/python-thumbnails,python-thumbnails/python-thumbnails | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('thumbnails.backends.cache_get', lambda x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
Fix failing mock of cache backend | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
| <commit_before># -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('thumbnails.backends.cache_get', lambda x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
<commit_msg>Fix failing mock of cache backend<commit_after> | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
| # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('thumbnails.backends.cache_get', lambda x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
Fix failing mock of cache backend# -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
| <commit_before># -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('thumbnails.backends.cache_get', lambda x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
<commit_msg>Fix failing mock of cache backend<commit_after># -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filename(SourceFile('url'), '100x200', 'center', None),
['0af', 'a360db703bd5c2fe7c83843ce7738a0a6d37b']
)
self.assertEqual(
generate_filename(SourceFile('url'), '200x200', 'center', None),
['851', '521c21fe9709802e9d4eb20a5fe84c18cd3ad']
)
@mock.patch('{}.get'.format(settings.THUMBNAIL_CACHE_BACKEND), lambda o, x: True)
def test_get_thumbnail_cached(self):
self.assertTrue(get_thumbnail('', '200'))
@mock.patch('thumbnails.engines.base.ThumbnailBaseEngine.get_thumbnail')
def test_get_thumbnail(self, mock_engine_get_thumbnail):
thumbnail = get_thumbnail('http://puppies.lkng.me/400x600/', '200')
self.assertTrue(mock_engine_get_thumbnail.called)
self.assertTrue(isinstance(thumbnail, Thumbnail))
|
60c7476f63cbeb64284ef8192e686b473cf0863d | wordcloud/wordcloud.py | wordcloud/wordcloud.py | import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
| import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f:
STOP_WORDS = set(f.read().splitlines())
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
| Make stop words a set for speed optimization. | Make stop words a set for speed optimization.
| Python | agpl-3.0 | geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola | import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
Make stop words a set for speed optimization. | import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f:
STOP_WORDS = set(f.read().splitlines())
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
| <commit_before>import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
<commit_msg>Make stop words a set for speed optimization.<commit_after> | import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f:
STOP_WORDS = set(f.read().splitlines())
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
| import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
Make stop words a set for speed optimization.import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f:
STOP_WORDS = set(f.read().splitlines())
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
| <commit_before>import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines()
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
<commit_msg>Make stop words a set for speed optimization.<commit_after>import os
from operator import itemgetter
import re
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f:
STOP_WORDS = set(f.read().splitlines())
def recent_entries(max_entries=20):
return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries]
def popular_words(max_entries=20, max_words=25):
sqs = recent_entries(max_entries)
# Generate tag cloud from content of returned entries
words = {}
for entry in sqs:
text = re.sub(ur'[^\w\s]', '', entry.object.content.lower())
for x in text.split():
if x not in STOP_WORDS:
words[x] = 1 + words.get(x, 0)
wordlist = []
for word in words:
wordlist.append(
{
"text": word,
"weight": words.get(word),
"link": "/search/hansard/?q=%s" % word,
}
)
wordlist.sort(key=itemgetter('weight'), reverse=True)
return wordlist[:max_words]
|
8ed94e1fb93252eed47239d8c6a5f28796802a36 | src/cclib/__init__.py | src/cclib/__init__.py | # This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
| """cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files generated by multiple programs
and provides a consistent interface to access them.
Currently supported programs:
ADF, Firefly, GAMESS(US), GAMESS-UK, Gaussian,
Jaguar, Molpro, NWChem, ORCA, Psi, Q-Chem
Another aim is to facilitate the implementation of algorithms that are not specific
to any particular computational chemistry package and to maximise interoperability
with other open source computational chemistry and cheminformatic software libraries.
To this end, cclib provides a number of bridges to help transfer data to other libraries
as well as example methods that take parsed data as input.
"""
# This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2014 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
| Add a descriptive docstring to main cclib module | Add a descriptive docstring to main cclib module
| Python | bsd-3-clause | berquist/cclib,jchodera/cclib,ghutchis/cclib,ben-albrecht/cclib,andersx/cclib,gaursagar/cclib,Clyde-fare/cclib,ghutchis/cclib,langner/cclib,andersx/cclib,cclib/cclib,Schamnad/cclib,ATenderholt/cclib,berquist/cclib,cclib/cclib,ATenderholt/cclib,langner/cclib,berquist/cclib,cclib/cclib,langner/cclib,gaursagar/cclib,jchodera/cclib,ben-albrecht/cclib,Schamnad/cclib,Clyde-fare/cclib | # This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
Add a descriptive docstring to main cclib module | """cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files generated by multiple programs
and provides a consistent interface to access them.
Currently supported programs:
ADF, Firefly, GAMESS(US), GAMESS-UK, Gaussian,
Jaguar, Molpro, NWChem, ORCA, Psi, Q-Chem
Another aim is to facilitate the implementation of algorithms that are not specific
to any particular computational chemistry package and to maximise interoperability
with other open source computational chemistry and cheminformatic software libraries.
To this end, cclib provides a number of bridges to help transfer data to other libraries
as well as example methods that take parsed data as input.
"""
# This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2014 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
| <commit_before># This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
<commit_msg>Add a descriptive docstring to main cclib module<commit_after> | """cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files generated by multiple programs
and provides a consistent interface to access them.
Currently supported programs:
ADF, Firefly, GAMESS(US), GAMESS-UK, Gaussian,
Jaguar, Molpro, NWChem, ORCA, Psi, Q-Chem
Another aim is to facilitate the implementation of algorithms that are not specific
to any particular computational chemistry package and to maximise interoperability
with other open source computational chemistry and cheminformatic software libraries.
To this end, cclib provides a number of bridges to help transfer data to other libraries
as well as example methods that take parsed data as input.
"""
# This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2014 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
| # This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
Add a descriptive docstring to main cclib module"""cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files generated by multiple programs
and provides a consistent interface to access them.
Currently supported programs:
ADF, Firefly, GAMESS(US), GAMESS-UK, Gaussian,
Jaguar, Molpro, NWChem, ORCA, Psi, Q-Chem
Another aim is to facilitate the implementation of algorithms that are not specific
to any particular computational chemistry package and to maximise interoperability
with other open source computational chemistry and cheminformatic software libraries.
To this end, cclib provides a number of bridges to help transfer data to other libraries
as well as example methods that take parsed data as input.
"""
# This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2014 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
| <commit_before># This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
<commit_msg>Add a descriptive docstring to main cclib module<commit_after>"""cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files generated by multiple programs
and provides a consistent interface to access them.
Currently supported programs:
ADF, Firefly, GAMESS(US), GAMESS-UK, Gaussian,
Jaguar, Molpro, NWChem, ORCA, Psi, Q-Chem
Another aim is to facilitate the implementation of algorithms that are not specific
to any particular computational chemistry package and to maximise interoperability
with other open source computational chemistry and cheminformatic software libraries.
To this end, cclib provides a number of bridges to help transfer data to other libraries
as well as example methods that take parsed data as input.
"""
# This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2014 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
__version__ = "1.3"
from . import parser
from . import progress
from . import method
from . import bridge
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
|
e2c8c71114692b99f50936dceab77dfd0329a5e0 | accelerator/tests/factories/community_factory.py | accelerator/tests/factories/community_factory.py | from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
logo = "logo.jpg"
image = "image.jpg"
assignment_order = 2
| from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
icon = "icon.jpg"
image = "image.jpg"
assignment_order = 2
| Implement feedback - remove deletion | [AC-9653]: Implement feedback - remove deletion
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
logo = "logo.jpg"
image = "image.jpg"
assignment_order = 2
[AC-9653]: Implement feedback - remove deletion | from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
icon = "icon.jpg"
image = "image.jpg"
assignment_order = 2
| <commit_before>from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
logo = "logo.jpg"
image = "image.jpg"
assignment_order = 2
<commit_msg>[AC-9653]: Implement feedback - remove deletion<commit_after> | from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
icon = "icon.jpg"
image = "image.jpg"
assignment_order = 2
| from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
logo = "logo.jpg"
image = "image.jpg"
assignment_order = 2
[AC-9653]: Implement feedback - remove deletionfrom factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
icon = "icon.jpg"
image = "image.jpg"
assignment_order = 2
| <commit_before>from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
logo = "logo.jpg"
image = "image.jpg"
assignment_order = 2
<commit_msg>[AC-9653]: Implement feedback - remove deletion<commit_after>from factory import Sequence
from factory.django import DjangoModelFactory
from accelerator.models import Community
class CommunityFactory(DjangoModelFactory):
class Meta:
model = Community
name = Sequence(lambda n: "name {0}".format(n))
email = Sequence(lambda n: "user_{0}@example.com".format(n))
icon = "icon.jpg"
image = "image.jpg"
assignment_order = 2
|
6e46b79b837f61e6fa56c19d59786f6d83e6470a | pages/tests.py | pages/tests.py | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
| from django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
slug_content = Content.objects.get_page_slug(page_data['slug'])
assert(slug_content is not None)
page = slug_content.page
assert(page.title() == page_data['title'])
assert(page.slug() == page_data['slug'])
def test_03_slug_collision(self):
"""
Test a slug collision
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page1 = Content.objects.get_page_slug(page_data['slug']).page
response = c.post('/admin/pages/page/add/', page_data)
assert(response.status_code == 200)
settings.PAGE_UNIQUE_SLUG_REQUIRED = False
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page2 = Content.objects.get_page_slug(page_data['slug']).page
assert(page1.id != page2.id)
| Add a test for slug collision | Add a test for slug collision | Python | bsd-3-clause | Alwnikrotikz/django-page-cms,google-code-export/django-page-cms,google-code-export/django-page-cms,PiRSquared17/django-page-cms,Alwnikrotikz/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms,PiRSquared17/django-page-cms,Alwnikrotikz/django-page-cms,PiRSquared17/django-page-cms,odyaka341/django-page-cms,odyaka341/django-page-cms,PiRSquared17/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,odyaka341/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,pombreda/django-page-cms,pombreda/django-page-cms | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
Add a test for slug collision | from django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
slug_content = Content.objects.get_page_slug(page_data['slug'])
assert(slug_content is not None)
page = slug_content.page
assert(page.title() == page_data['title'])
assert(page.slug() == page_data['slug'])
def test_03_slug_collision(self):
"""
Test a slug collision
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page1 = Content.objects.get_page_slug(page_data['slug']).page
response = c.post('/admin/pages/page/add/', page_data)
assert(response.status_code == 200)
settings.PAGE_UNIQUE_SLUG_REQUIRED = False
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page2 = Content.objects.get_page_slug(page_data['slug']).page
assert(page1.id != page2.id)
| <commit_before>from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
<commit_msg>Add a test for slug collision<commit_after> | from django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
slug_content = Content.objects.get_page_slug(page_data['slug'])
assert(slug_content is not None)
page = slug_content.page
assert(page.title() == page_data['title'])
assert(page.slug() == page_data['slug'])
def test_03_slug_collision(self):
"""
Test a slug collision
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page1 = Content.objects.get_page_slug(page_data['slug']).page
response = c.post('/admin/pages/page/add/', page_data)
assert(response.status_code == 200)
settings.PAGE_UNIQUE_SLUG_REQUIRED = False
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page2 = Content.objects.get_page_slug(page_data['slug']).page
assert(page1.id != page2.id)
| from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
Add a test for slug collisionfrom django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
slug_content = Content.objects.get_page_slug(page_data['slug'])
assert(slug_content is not None)
page = slug_content.page
assert(page.title() == page_data['title'])
assert(page.slug() == page_data['slug'])
def test_03_slug_collision(self):
"""
Test a slug collision
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page1 = Content.objects.get_page_slug(page_data['slug']).page
response = c.post('/admin/pages/page/add/', page_data)
assert(response.status_code == 200)
settings.PAGE_UNIQUE_SLUG_REQUIRED = False
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page2 = Content.objects.get_page_slug(page_data['slug']).page
assert(page1.id != page2.id)
| <commit_before>from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
<commit_msg>Add a test for slug collision<commit_after>from django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.get('/admin/pages/page/add/')
assert(response.status_code == 200)
def test_02_create_page(self):
"""
Test that a page can be created via the admin
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
slug_content = Content.objects.get_page_slug(page_data['slug'])
assert(slug_content is not None)
page = slug_content.page
assert(page.title() == page_data['title'])
assert(page.slug() == page_data['slug'])
def test_03_slug_collision(self):
"""
Test a slug collision
"""
c = Client()
c.login(username= 'batiste', password='b')
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page1 = Content.objects.get_page_slug(page_data['slug']).page
response = c.post('/admin/pages/page/add/', page_data)
assert(response.status_code == 200)
settings.PAGE_UNIQUE_SLUG_REQUIRED = False
response = c.post('/admin/pages/page/add/', page_data)
self.assertRedirects(response, '/admin/pages/page/')
page2 = Content.objects.get_page_slug(page_data['slug']).page
assert(page1.id != page2.id)
|
07f50c1b01cce4550b3b4ecb369932166412063b | tests/commands.py | tests/commands.py | from sublime import Region
from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
| from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
# This fixes an issue where an exception is thrown when reloading the
# test commands. I don't know why this is needed, but it works. It's
# most likely a bug in ST. The exception:
# Traceback (most recent call last):
# File "/home/code/sublime_text_3/sublime_plugin.py", line 933, in run_
# return self.run(edit, **args)
# File "/home/code/.config/sublime-text-3/Packages/phpunitkit/tests/commands.py", line 11, in run
# self.view.replace(edit, Region(0, self.view.size()), text)
# TypeError: 'NoneType' object is not callable
from sublime import Region # noqa: F401
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
| Fix TypeError: 'NoneType' object is not callable when running tests | Fix TypeError: 'NoneType' object is not callable when running tests
| Python | bsd-3-clause | gerardroche/sublime-phpunit | from sublime import Region
from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
Fix TypeError: 'NoneType' object is not callable when running tests | from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
# This fixes an issue where an exception is thrown when reloading the
# test commands. I don't know why this is needed, but it works. It's
# most likely a bug in ST. The exception:
# Traceback (most recent call last):
# File "/home/code/sublime_text_3/sublime_plugin.py", line 933, in run_
# return self.run(edit, **args)
# File "/home/code/.config/sublime-text-3/Packages/phpunitkit/tests/commands.py", line 11, in run
# self.view.replace(edit, Region(0, self.view.size()), text)
# TypeError: 'NoneType' object is not callable
from sublime import Region # noqa: F401
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
| <commit_before>from sublime import Region
from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
<commit_msg>Fix TypeError: 'NoneType' object is not callable when running tests<commit_after> | from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
# This fixes an issue where an exception is thrown when reloading the
# test commands. I don't know why this is needed, but it works. It's
# most likely a bug in ST. The exception:
# Traceback (most recent call last):
# File "/home/code/sublime_text_3/sublime_plugin.py", line 933, in run_
# return self.run(edit, **args)
# File "/home/code/.config/sublime-text-3/Packages/phpunitkit/tests/commands.py", line 11, in run
# self.view.replace(edit, Region(0, self.view.size()), text)
# TypeError: 'NoneType' object is not callable
from sublime import Region # noqa: F401
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
| from sublime import Region
from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
Fix TypeError: 'NoneType' object is not callable when running testsfrom sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
# This fixes an issue where an exception is thrown when reloading the
# test commands. I don't know why this is needed, but it works. It's
# most likely a bug in ST. The exception:
# Traceback (most recent call last):
# File "/home/code/sublime_text_3/sublime_plugin.py", line 933, in run_
# return self.run(edit, **args)
# File "/home/code/.config/sublime-text-3/Packages/phpunitkit/tests/commands.py", line 11, in run
# self.view.replace(edit, Region(0, self.view.size()), text)
# TypeError: 'NoneType' object is not callable
from sublime import Region # noqa: F401
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
| <commit_before>from sublime import Region
from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
<commit_msg>Fix TypeError: 'NoneType' object is not callable when running tests<commit_after>from sublime_plugin import TextCommand
class PhpunitTestSetupFixtureCommand(TextCommand):
def run(self, edit, text):
# This fixes an issue where an exception is thrown when reloading the
# test commands. I don't know why this is needed, but it works. It's
# most likely a bug in ST. The exception:
# Traceback (most recent call last):
# File "/home/code/sublime_text_3/sublime_plugin.py", line 933, in run_
# return self.run(edit, **args)
# File "/home/code/.config/sublime-text-3/Packages/phpunitkit/tests/commands.py", line 11, in run
# self.view.replace(edit, Region(0, self.view.size()), text)
# TypeError: 'NoneType' object is not callable
from sublime import Region # noqa: F401
self.view.replace(edit, Region(0, self.view.size()), text)
if '|' in text:
cursor_placeholders = self.view.find_all('\\|')
if cursor_placeholders:
self.view.sel().clear()
for i, cursor_placeholder in enumerate(cursor_placeholders):
self.view.sel().add(cursor_placeholder.begin() - i)
self.view.replace(
edit,
Region(cursor_placeholder.begin() - i, cursor_placeholder.end() - i),
''
)
|
2f4141311af549b6d57e72534b4da0a6ce950629 | src/waldur_mastermind/analytics/serializers.py | src/waldur_mastermind/analytics/serializers.py | from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
| from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
| Fix period validation in daily quota serializer. | Fix period validation in daily quota serializer.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind | from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
Fix period validation in daily quota serializer. | from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
| <commit_before>from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
<commit_msg>Fix period validation in daily quota serializer.<commit_after> | from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
| from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
Fix period validation in daily quota serializer.from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
| <commit_before>from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
return attrs
<commit_msg>Fix period validation in daily quota serializer.<commit_after>from __future__ import unicode_literals
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from waldur_core.core.serializers import GenericRelatedField
from waldur_core.structure.models import Customer, Project
class DailyHistoryQuotaSerializer(serializers.Serializer):
scope = GenericRelatedField(related_models=(Project, Customer))
quota_names = serializers.ListField(child=serializers.CharField(), required=False)
start = serializers.DateField(format='%Y-%m-%d', required=False)
end = serializers.DateField(format='%Y-%m-%d', required=False)
def validate(self, attrs):
if 'quota_names' not in attrs:
attrs['quota_names'] = attrs['scope'].get_quotas_names
if 'end' not in attrs:
attrs['end'] = timezone.now().date()
if 'start' not in attrs:
attrs['start'] = timezone.now().date() - timedelta(days=30)
if attrs['start'] >= attrs['end']:
raise serializers.ValidationError(
_('Invalid period specified. `start` should be lesser than `end`.')
)
return attrs
|
9a4cb482cbe0f5dc2de8f6ae89dd0b78a1564a0d | pbxplore/structure/loader.py | pbxplore/structure/loader.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| Create only one MDAnalysis selection | Create only one MDAnalysis selection
| Python | mit | pierrepo/PBxplore,pierrepo/PBxplore,jbarnoud/PBxplore,jbarnoud/PBxplore,HubLot/PBxplore,HubLot/PBxplore | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
Create only one MDAnalysis selection | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| <commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
<commit_msg>Create only one MDAnalysis selection<commit_after> | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
Create only one MDAnalysis selection#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| <commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
<commit_msg>Create only one MDAnalysis selection<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
|
92e0724f28ce0e6802237b13656064c6add63b85 | fuzzers/019-ndi1mux/generate.py | fuzzers/019-ndi1mux/generate.py | #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ADI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BDI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CDI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
| #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ALUT.DI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BLUT.DI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CLUT.DI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
| Rename DI1MUX to be underneith the *LUT. | Rename DI1MUX to be underneith the *LUT.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
| Python | isc | SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray | #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ADI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BDI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CDI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
Rename DI1MUX to be underneith the *LUT.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com> | #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ALUT.DI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BLUT.DI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CLUT.DI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
| <commit_before>#!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ADI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BDI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CDI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
<commit_msg>Rename DI1MUX to be underneith the *LUT.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com><commit_after> | #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ALUT.DI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BLUT.DI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CLUT.DI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
| #!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ADI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BDI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CDI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
Rename DI1MUX to be underneith the *LUT.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>#!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ALUT.DI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BLUT.DI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CLUT.DI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
| <commit_before>#!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ADI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BDI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CDI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
<commit_msg>Rename DI1MUX to be underneith the *LUT.
Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com><commit_after>#!/usr/bin/env python3
# FIXME: getting two bits
# 00_40 31_46
# Can we find instance where they are not aliased?
WA7USED = 0
from prjxray.segmaker import Segmaker
segmk = Segmaker("design.bits")
print("Loading tags")
'''
module,loc,c31,b31,a31
my_NDI1MUX_NI_NMC31,SLICE_X12Y100,1,1,0
my_NDI1MUX_NI_NMC31,SLICE_X12Y101,1,1,1
my_NDI1MUX_NI_NMC31,SLICE_X12Y102,1,1,1
'''
f = open('params.csv', 'r')
f.readline()
for l in f:
l = l.strip()
module, loc, c31, b31, a31 = l.split(',')
c31 = int(c31)
b31 = int(b31)
a31 = int(a31)
segmk.add_site_tag(loc, "ALUT.DI1MUX.AI", 1 ^ a31)
segmk.add_site_tag(loc, "BLUT.DI1MUX.BI", 1 ^ b31)
segmk.add_site_tag(loc, "CLUT.DI1MUX.CI", 1 ^ c31)
segmk.compile()
segmk.write()
|
93dee6a3ff44fb7470b3008e8fbbaf99822bbe82 | designate/cmd/__init__.py | designate/cmd/__init__.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| Fix Redis connection over TLS | Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72
| Python | apache-2.0 | openstack/designate,openstack/designate,openstack/designate | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| <commit_before># Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
<commit_msg>Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72<commit_after> | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| <commit_before># Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
<commit_msg>Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72<commit_after># Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
|
a54a2e735950c5c31ec71613750bdf1ce194389f | django_datastream/urls.py | django_datastream/urls.py | from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = urls.patterns(
'',
urls.url(r'^', urls.include(v1_api.urls)),
)
| from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = [
urls.url(r'^', urls.include(v1_api.urls)),
]
| Fix urlpatterns for Django 1.10. | Fix urlpatterns for Django 1.10.
| Python | agpl-3.0 | wlanslovenija/django-datastream,wlanslovenija/django-datastream,wlanslovenija/django-datastream | from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = urls.patterns(
'',
urls.url(r'^', urls.include(v1_api.urls)),
)
Fix urlpatterns for Django 1.10. | from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = [
urls.url(r'^', urls.include(v1_api.urls)),
]
| <commit_before>from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = urls.patterns(
'',
urls.url(r'^', urls.include(v1_api.urls)),
)
<commit_msg>Fix urlpatterns for Django 1.10.<commit_after> | from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = [
urls.url(r'^', urls.include(v1_api.urls)),
]
| from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = urls.patterns(
'',
urls.url(r'^', urls.include(v1_api.urls)),
)
Fix urlpatterns for Django 1.10.from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = [
urls.url(r'^', urls.include(v1_api.urls)),
]
| <commit_before>from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = urls.patterns(
'',
urls.url(r'^', urls.include(v1_api.urls)),
)
<commit_msg>Fix urlpatterns for Django 1.10.<commit_after>from django.conf import urls
from tastypie import api
from . import resources
v1_api = api.Api(api_name='v1')
v1_api.register(resources.StreamResource())
urlpatterns = [
urls.url(r'^', urls.include(v1_api.urls)),
]
|
6903f63e76ac5e7686ae55348225d06e3757a64b | giphy_magic.py | giphy_magic.py | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
else:
return 'Giphy could not match {}'.format(tag)
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None:
params['tag'] = tag
return params
def giphy(tag):
params = get_params(tag)
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
elif RANDOM_ON_NO_MATCH:
return giphy(None)
else:
return 'Giphy could not match {}'.format(tag),
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| Add a constant that determines the response when no results are found | Add a constant that determines the response when no results are found
| Python | mit | AustinRochford/giphy-ipython-magic,AustinRochford/giphy-ipython-magic | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
else:
return 'Giphy could not match {}'.format(tag)
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
Add a constant that determines the response when no results are found | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None:
params['tag'] = tag
return params
def giphy(tag):
params = get_params(tag)
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
elif RANDOM_ON_NO_MATCH:
return giphy(None)
else:
return 'Giphy could not match {}'.format(tag),
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| <commit_before>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
else:
return 'Giphy could not match {}'.format(tag)
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
<commit_msg>Add a constant that determines the response when no results are found<commit_after> | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None:
params['tag'] = tag
return params
def giphy(tag):
params = get_params(tag)
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
elif RANDOM_ON_NO_MATCH:
return giphy(None)
else:
return 'Giphy could not match {}'.format(tag),
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
else:
return 'Giphy could not match {}'.format(tag)
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
Add a constant that determines the response when no results are foundfrom IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None:
params['tag'] = tag
return params
def giphy(tag):
params = get_params(tag)
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
elif RANDOM_ON_NO_MATCH:
return giphy(None)
else:
return 'Giphy could not match {}'.format(tag),
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| <commit_before>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
else:
return 'Giphy could not match {}'.format(tag)
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
<commit_msg>Add a constant that determines the response when no results are found<commit_after>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None:
params['tag'] = tag
return params
def giphy(tag):
params = get_params(tag)
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
if data and 'image_url' in data:
return Image(url=data['image_url'])
elif RANDOM_ON_NO_MATCH:
return giphy(None)
else:
return 'Giphy could not match {}'.format(tag),
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
|
02160f46d5e28c394915d44c42e4e1b09e750717 | utils/rest.py | utils/rest.py | import json
import logging
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('GET %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('DELETE %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('POST %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
| import json
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
auth = None
if 'username' in config and 'password' in config:
auth = (config['username'], config['password'])
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=auth,
verify=settings.servers.verify_ssl)
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
| Remove logging and allow anonymous access (for Crucible for example) | Remove logging and allow anonymous access (for Crucible for example)
| Python | mit | gpailler/AtlassianBot | import json
import logging
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('GET %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('DELETE %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('POST %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
Remove logging and allow anonymous access (for Crucible for example) | import json
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
auth = None
if 'username' in config and 'password' in config:
auth = (config['username'], config['password'])
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=auth,
verify=settings.servers.verify_ssl)
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
| <commit_before>import json
import logging
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('GET %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('DELETE %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('POST %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
<commit_msg>Remove logging and allow anonymous access (for Crucible for example)<commit_after> | import json
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
auth = None
if 'username' in config and 'password' in config:
auth = (config['username'], config['password'])
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=auth,
verify=settings.servers.verify_ssl)
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
| import json
import logging
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('GET %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('DELETE %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('POST %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
Remove logging and allow anonymous access (for Crucible for example)import json
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
auth = None
if 'username' in config and 'password' in config:
auth = (config['username'], config['password'])
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=auth,
verify=settings.servers.verify_ssl)
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
| <commit_before>import json
import logging
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('GET %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('DELETE %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
logging.debug('POST %s - Response %s - Data %s'
% (request.url, request.status_code, data))
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
<commit_msg>Remove logging and allow anonymous access (for Crucible for example)<commit_after>import json
import requests
import plugins.settings as settings
headers = {'accept': 'application/json'}
def get(config, path, data=None):
auth = None
if 'username' in config and 'password' in config:
auth = (config['username'], config['password'])
request = requests.get(
url=__format_url(config, path),
params=data,
headers=headers,
auth=auth,
verify=settings.servers.verify_ssl)
return request
def delete(config, path, data):
request = requests.delete(
url=__format_url(config, path),
data=json.dumps(data),
headers={
'Content-type': 'application/json',
'Accept': 'application/json'
},
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def post(config, path, data=None):
request = requests.post(
url=__format_url(config, path),
data=data,
headers=headers,
auth=(config['username'], config['password']),
verify=settings.servers.verify_ssl)
return request
def __format_url(config, path):
return '{server}{path}'.format(server=config['host'], path=path)
|
107ecde6c2373deedcb788115811bcbb50de6851 | uwiki/auth.py | uwiki/auth.py | import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
| import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
| Allow static files to go through (for now) | Allow static files to go through (for now) | Python | bsd-3-clause | mikeboers/uWiki,mikeboers/uWiki,mikeboers/uWiki,mikeboers/uWiki | import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
Allow static files to go through (for now) | import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
| <commit_before>import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
<commit_msg>Allow static files to go through (for now)<commit_after> | import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
| import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
Allow static files to go through (for now)import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
| <commit_before>import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint != 'login':
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
<commit_msg>Allow static files to go through (for now)<commit_after>import logging
from flask import request
from flask.ext.login import current_user, UserMixin, AnonymousUserMixin
from .core import app, auth
log = logging.getLogger(__name__)
app.login_manager.login_view = 'login'
@auth.context_processor
def provide_user():
return dict(user=current_user)
@app.before_request
def assert_logged_in():
if not current_user.is_authenticated() and request.endpoint not in ('login', 'static'):
return app.login_manager.unauthorized()
class Role(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
def __call__(self, user, **kw):
return self.name in getattr(user, 'roles', ())
auth.predicates['ROOT'] = Role('wheel')
auth.predicates['OBSERVER'] = Role('observer')
class _DummyAdmin(UserMixin):
id = 0
is_group = False
name = 'ADMIN'
groups = []
roles = set(('wheel', ))
__repr__ = lambda self: '<DummyAccount user:ADMIN>'
dummy_admin = _DummyAdmin()
class _DummyAnonymous(UserMixin):
id = 0
is_group = False
name = 'ANONYMOUS'
groups = []
roles = set()
__repr__ = lambda self: '<DummyAccount user:ANONYMOUS>'
dummy_anon = _DummyAnonymous()
|
a1effed87a8e90483f1ab850c77aff7c827b7f48 | install_packages.py | install_packages.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and LibSVM, just to check package's names
all_packages = packages.all_packages()
for item in all_packages:
if (item.name == "gridSearch") or (item.name == "LibSVM"):
print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/v2014.12.10/multisearch-2014.12.10.zip")
jvm.stop()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and LibSVM, just to check package's names
# all_packages = packages.all_packages()
# for item in all_packages:
# if (item.name == "gridSearch") or (item.name == "LibSVM"):
# print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/" +
# "v2016.1.30/multisearch-2016.1.30.zip")
# packages.install_package("/home/sebastian/Descargas/multisearch-2016.1.30.zip")
# packages.uninstall_package("multisearch")
jvm.stop()
| Add other options to install packages | Add other options to install packages
| Python | mit | srvanrell/libsvm-weka-python | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and LibSVM, just to check package's names
all_packages = packages.all_packages()
for item in all_packages:
if (item.name == "gridSearch") or (item.name == "LibSVM"):
print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/v2014.12.10/multisearch-2014.12.10.zip")
jvm.stop()
Add other options to install packages | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and LibSVM, just to check package's names
# all_packages = packages.all_packages()
# for item in all_packages:
# if (item.name == "gridSearch") or (item.name == "LibSVM"):
# print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/" +
# "v2016.1.30/multisearch-2016.1.30.zip")
# packages.install_package("/home/sebastian/Descargas/multisearch-2016.1.30.zip")
# packages.uninstall_package("multisearch")
jvm.stop()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and LibSVM, just to check package's names
all_packages = packages.all_packages()
for item in all_packages:
if (item.name == "gridSearch") or (item.name == "LibSVM"):
print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/v2014.12.10/multisearch-2014.12.10.zip")
jvm.stop()
<commit_msg>Add other options to install packages<commit_after> | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and LibSVM, just to check package's names
# all_packages = packages.all_packages()
# for item in all_packages:
# if (item.name == "gridSearch") or (item.name == "LibSVM"):
# print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/" +
# "v2016.1.30/multisearch-2016.1.30.zip")
# packages.install_package("/home/sebastian/Descargas/multisearch-2016.1.30.zip")
# packages.uninstall_package("multisearch")
jvm.stop()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and LibSVM, just to check package's names
all_packages = packages.all_packages()
for item in all_packages:
if (item.name == "gridSearch") or (item.name == "LibSVM"):
print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/v2014.12.10/multisearch-2014.12.10.zip")
jvm.stop()
Add other options to install packages#!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and LibSVM, just to check package's names
# all_packages = packages.all_packages()
# for item in all_packages:
# if (item.name == "gridSearch") or (item.name == "LibSVM"):
# print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/" +
# "v2016.1.30/multisearch-2016.1.30.zip")
# packages.install_package("/home/sebastian/Descargas/multisearch-2016.1.30.zip")
# packages.uninstall_package("multisearch")
jvm.stop()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and LibSVM, just to check package's names
all_packages = packages.all_packages()
for item in all_packages:
if (item.name == "gridSearch") or (item.name == "LibSVM"):
print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/v2014.12.10/multisearch-2014.12.10.zip")
jvm.stop()
<commit_msg>Add other options to install packages<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and LibSVM, just to check package's names
# all_packages = packages.all_packages()
# for item in all_packages:
# if (item.name == "gridSearch") or (item.name == "LibSVM"):
# print(item.name + " " + item.url)
# To install gridSearch and LibSVM
# packages.install_package("gridSearch", "1.0.8")
# packages.install_package("LibSVM")
# To install MultiSearch
# packages.install_package("https://github.com/fracpete/multisearch-weka-package/releases/download/" +
# "v2016.1.30/multisearch-2016.1.30.zip")
# packages.install_package("/home/sebastian/Descargas/multisearch-2016.1.30.zip")
# packages.uninstall_package("multisearch")
jvm.stop()
|
2533aa96b189eb5aaea293c57f928d594ef92eba | utils/language.py | utils/language.py | from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max_p
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
| from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
words1 = word1.split('_')
words2 = word2.split('_')
if len(words1) > 1 or len(words2) > 1:
sub_similarity = .9 * semantic_similarity(words1[-1], words2[-1])
else:
sub_similarity = 0
if sub_similarity == 1:
return sub_similarity
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max(max_p, sub_similarity)
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
| Check semantic similarity of last word in phrase as well as entire phrase | Check semantic similarity of last word in phrase as well as entire phrase
| Python | mit | rdeits/cryptics,rdeits/cryptics,rdeits/cryptics,rdeits/cryptics,rdeits/cryptics,rdeits/cryptics,rdeits/cryptics | from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max_p
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
Check semantic similarity of last word in phrase as well as entire phrase | from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
words1 = word1.split('_')
words2 = word2.split('_')
if len(words1) > 1 or len(words2) > 1:
sub_similarity = .9 * semantic_similarity(words1[-1], words2[-1])
else:
sub_similarity = 0
if sub_similarity == 1:
return sub_similarity
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max(max_p, sub_similarity)
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
| <commit_before>from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max_p
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
<commit_msg>Check semantic similarity of last word in phrase as well as entire phrase<commit_after> | from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
words1 = word1.split('_')
words2 = word2.split('_')
if len(words1) > 1 or len(words2) > 1:
sub_similarity = .9 * semantic_similarity(words1[-1], words2[-1])
else:
sub_similarity = 0
if sub_similarity == 1:
return sub_similarity
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max(max_p, sub_similarity)
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
| from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max_p
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
Check semantic similarity of last word in phrase as well as entire phrasefrom utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
words1 = word1.split('_')
words2 = word2.split('_')
if len(words1) > 1 or len(words2) > 1:
sub_similarity = .9 * semantic_similarity(words1[-1], words2[-1])
else:
sub_similarity = 0
if sub_similarity == 1:
return sub_similarity
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max(max_p, sub_similarity)
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
| <commit_before>from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max_p
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
<commit_msg>Check semantic similarity of last word in phrase as well as entire phrase<commit_after>from utils.synonyms import cached_synonyms
from nltk.corpus import wordnet as wn
def semantic_similarity(word1, word2):
words1 = word1.split('_')
words2 = word2.split('_')
if len(words1) > 1 or len(words2) > 1:
sub_similarity = .9 * semantic_similarity(words1[-1], words2[-1])
else:
sub_similarity = 0
if sub_similarity == 1:
return sub_similarity
if fast_semantic_similarity(word1, word2) == 1:
return 1
max_p = 0
for s1 in wn.synsets(word1):
for st1 in [s1] + s1.similar_tos():
for s2 in wn.synsets(word2):
for st2 in [s2] + s2.similar_tos():
p = wn.wup_similarity(st1, st2)
if p == 1:
return p
if p > max_p:
max_p = p
return max(max_p, sub_similarity)
def fast_semantic_similarity(word1, word2):
syns1 = cached_synonyms(word1)
syns1.append(word1)
syns2 = cached_synonyms(word2)
syns2.append(word2)
for s1 in syns1:
if s1 in syns2:
return 1
return 0
|
fe32099bf1b6aa387c98dd6afdfc31557fc4e1f9 | volpy/__init__.py | volpy/__init__.py | from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
| '''
Volpy
=====
A fast volume rendering implementation for Python. Volpy has support for:
1. Multithreading or multiprocessing at the rendering step
2. Native implementation of ray casting
3. Native access to NumPy arrays during rendering
4. Support for ambient and diffuse lighting terms
How to use this package
-----------------------
Volpy is organized into several different modules but the API is imported into
the root of the package. Therefore, you should write your code like this:
>>> import volpy
>>> scene = volpy.Scene(ambient=my_func)
'''
from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
| Write a docstring for the package | Write a docstring for the package
| Python | mit | OEP/volpy,OEP/volpy | from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
Write a docstring for the package | '''
Volpy
=====
A fast volume rendering implementation for Python. Volpy has support for:
1. Multithreading or multiprocessing at the rendering step
2. Native implementation of ray casting
3. Native access to NumPy arrays during rendering
4. Support for ambient and diffuse lighting terms
How to use this package
-----------------------
Volpy is organized into several different modules but the API is imported into
the root of the package. Therefore, you should write your code like this:
>>> import volpy
>>> scene = volpy.Scene(ambient=my_func)
'''
from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
| <commit_before>from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
<commit_msg>Write a docstring for the package<commit_after> | '''
Volpy
=====
A fast volume rendering implementation for Python. Volpy has support for:
1. Multithreading or multiprocessing at the rendering step
2. Native implementation of ray casting
3. Native access to NumPy arrays during rendering
4. Support for ambient and diffuse lighting terms
How to use this package
-----------------------
Volpy is organized into several different modules but the API is imported into
the root of the package. Therefore, you should write your code like this:
>>> import volpy
>>> scene = volpy.Scene(ambient=my_func)
'''
from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
| from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
Write a docstring for the package'''
Volpy
=====
A fast volume rendering implementation for Python. Volpy has support for:
1. Multithreading or multiprocessing at the rendering step
2. Native implementation of ray casting
3. Native access to NumPy arrays during rendering
4. Support for ambient and diffuse lighting terms
How to use this package
-----------------------
Volpy is organized into several different modules but the API is imported into
the root of the package. Therefore, you should write your code like this:
>>> import volpy
>>> scene = volpy.Scene(ambient=my_func)
'''
from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
| <commit_before>from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
<commit_msg>Write a docstring for the package<commit_after>'''
Volpy
=====
A fast volume rendering implementation for Python. Volpy has support for:
1. Multithreading or multiprocessing at the rendering step
2. Native implementation of ray casting
3. Native access to NumPy arrays during rendering
4. Support for ambient and diffuse lighting terms
How to use this package
-----------------------
Volpy is organized into several different modules but the API is imported into
the root of the package. Therefore, you should write your code like this:
>>> import volpy
>>> scene = volpy.Scene(ambient=my_func)
'''
from .camera import Camera
from .scene import Scene, Element, Light
from .version import __version__
from .grid import Grid
from .homogeneous import (translate, scale, rotatex, rotatey, rotatez, rotatexyz,
rotate_axis, cross)
from .geometry import Geometry, BBox
|
5e2bcc9ae44d0155be1cc72b3728c3869377e02f | website/addons/osfstorage/__init__.py | website/addons/osfstorage/__init__.py | #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': ['storageRubeusConfig.js'],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
| #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
| Remove storageRubeusConfig.js from osfstorage init.py | Remove storageRubeusConfig.js from osfstorage init.py
| Python | apache-2.0 | mfraezz/osf.io,caseyrollins/osf.io,leb2dg/osf.io,caseyrygt/osf.io,kushG/osf.io,jmcarp/osf.io,billyhunt/osf.io,Nesiehr/osf.io,haoyuchen1992/osf.io,zkraime/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,lamdnhan/osf.io,HalcyonChimera/osf.io,kushG/osf.io,wearpants/osf.io,samanehsan/osf.io,cwisecarver/osf.io,arpitar/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,Ghalko/osf.io,caseyrollins/osf.io,GaryKriebel/osf.io,mluke93/osf.io,fabianvf/osf.io,Johnetordoff/osf.io,kch8qx/osf.io,chrisseto/osf.io,AndrewSallans/osf.io,sbt9uc/osf.io,fabianvf/osf.io,ticklemepierce/osf.io,brianjgeiger/osf.io,binoculars/osf.io,ckc6cz/osf.io,asanfilippo7/osf.io,jeffreyliu3230/osf.io,SSJohns/osf.io,abought/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,adlius/osf.io,njantrania/osf.io,revanthkolli/osf.io,pattisdr/osf.io,cldershem/osf.io,brianjgeiger/osf.io,cosenal/osf.io,laurenrevere/osf.io,laurenrevere/osf.io,SSJohns/osf.io,sbt9uc/osf.io,samchrisinger/osf.io,GaryKriebel/osf.io,monikagrabowska/osf.io,arpitar/osf.io,jnayak1/osf.io,cslzchen/osf.io,felliott/osf.io,wearpants/osf.io,petermalcolm/osf.io,emetsger/osf.io,sbt9uc/osf.io,revanthkolli/osf.io,mattclark/osf.io,Ghalko/osf.io,rdhyee/osf.io,mfraezz/osf.io,cwisecarver/osf.io,leb2dg/osf.io,AndrewSallans/osf.io,crcresearch/osf.io,acshi/osf.io,mluo613/osf.io,jnayak1/osf.io,TomHeatwole/osf.io,arpitar/osf.io,erinspace/osf.io,jmcarp/osf.io,wearpants/osf.io,hmoco/osf.io,sloria/osf.io,RomanZWang/osf.io,Nesiehr/osf.io,chrisseto/osf.io,icereval/osf.io,KAsante95/osf.io,caseyrygt/osf.io,caneruguz/osf.io,KAsante95/osf.io,ckc6cz/osf.io,bdyetton/prettychart,DanielSBrown/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,monikagrabowska/osf.io,doublebits/osf.io,njantrania/osf.io,samchrisinger/osf.io,abought/osf.io,revanthkolli/osf.io,cslzchen/osf.io,MerlinZhang/osf.io,pattisdr/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,bdyetton/prettychart,himanshuo/osf.io,chrisseto/osf.io,HarryRybacki/osf.io,jnayak1/osf.io,Ghalko/osf.io,kwierman/osf.io,adlius/osf.io,mluke93/osf.io,kwierman/osf.io,leb2dg/osf.io,chennan47/osf.io,njantrania/osf.io,GageGaskins/osf.io,zkraime/osf.io,dplorimer/osf,aaxelb/osf.io,billyhunt/osf.io,GageGaskins/osf.io,emetsger/osf.io,MerlinZhang/osf.io,haoyuchen1992/osf.io,saradbowman/osf.io,doublebits/osf.io,brandonPurvis/osf.io,caseyrygt/osf.io,mfraezz/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,himanshuo/osf.io,chrisseto/osf.io,baylee-d/osf.io,zamattiac/osf.io,jinluyuan/osf.io,GageGaskins/osf.io,binoculars/osf.io,asanfilippo7/osf.io,GaryKriebel/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,icereval/osf.io,abought/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,jmcarp/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,barbour-em/osf.io,mluo613/osf.io,sloria/osf.io,asanfilippo7/osf.io,himanshuo/osf.io,doublebits/osf.io,himanshuo/osf.io,ckc6cz/osf.io,HalcyonChimera/osf.io,danielneis/osf.io,erinspace/osf.io,GageGaskins/osf.io,rdhyee/osf.io,sbt9uc/osf.io,hmoco/osf.io,jinluyuan/osf.io,reinaH/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,samanehsan/osf.io,felliott/osf.io,hmoco/osf.io,barbour-em/osf.io,TomBaxter/osf.io,cslzchen/osf.io,aaxelb/osf.io,KAsante95/osf.io,HarryRybacki/osf.io,amyshi188/osf.io,lyndsysimon/osf.io,RomanZWang/osf.io,amyshi188/osf.io,cosenal/osf.io,zachjanicki/osf.io,samanehsan/osf.io,acshi/osf.io,dplorimer/osf,mluke93/osf.io,jolene-esposito/osf.io,kushG/osf.io,TomBaxter/osf.io,SSJohns/osf.io,kwierman/osf.io,danielneis/osf.io,zamattiac/osf.io,doublebits/osf.io,Johnetordoff/osf.io,cosenal/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,jolene-esposito/osf.io,chennan47/osf.io,cosenal/osf.io,ticklemepierce/osf.io,cldershem/osf.io,billyhunt/osf.io,baylee-d/osf.io,brandonPurvis/osf.io,bdyetton/prettychart,caseyrollins/osf.io,KAsante95/osf.io,jeffreyliu3230/osf.io,aaxelb/osf.io,ticklemepierce/osf.io,zkraime/osf.io,lamdnhan/osf.io,petermalcolm/osf.io,acshi/osf.io,arpitar/osf.io,mluo613/osf.io,crcresearch/osf.io,ZobairAlijan/osf.io,bdyetton/prettychart,barbour-em/osf.io,ckc6cz/osf.io,MerlinZhang/osf.io,emetsger/osf.io,GaryKriebel/osf.io,felliott/osf.io,MerlinZhang/osf.io,jolene-esposito/osf.io,HarryRybacki/osf.io,kch8qx/osf.io,fabianvf/osf.io,billyhunt/osf.io,TomHeatwole/osf.io,rdhyee/osf.io,zachjanicki/osf.io,amyshi188/osf.io,mluo613/osf.io,kch8qx/osf.io,zachjanicki/osf.io,saradbowman/osf.io,caneruguz/osf.io,chennan47/osf.io,DanielSBrown/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,adlius/osf.io,samchrisinger/osf.io,reinaH/osf.io,haoyuchen1992/osf.io,acshi/osf.io,kwierman/osf.io,binoculars/osf.io,alexschiller/osf.io,erinspace/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,lyndsysimon/osf.io,jinluyuan/osf.io,reinaH/osf.io,rdhyee/osf.io,samanehsan/osf.io,felliott/osf.io,SSJohns/osf.io,fabianvf/osf.io,revanthkolli/osf.io,Ghalko/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,kch8qx/osf.io,lamdnhan/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,sloria/osf.io,alexschiller/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,jmcarp/osf.io,kushG/osf.io,amyshi188/osf.io,lamdnhan/osf.io,TomHeatwole/osf.io,dplorimer/osf,haoyuchen1992/osf.io,dplorimer/osf,caneruguz/osf.io,baylee-d/osf.io,alexschiller/osf.io,HarryRybacki/osf.io,reinaH/osf.io,ZobairAlijan/osf.io,brandonPurvis/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,monikagrabowska/osf.io,jeffreyliu3230/osf.io,TomBaxter/osf.io,pattisdr/osf.io,emetsger/osf.io,leb2dg/osf.io,alexschiller/osf.io,njantrania/osf.io,laurenrevere/osf.io,zamattiac/osf.io,lyndsysimon/osf.io,acshi/osf.io,monikagrabowska/osf.io,hmoco/osf.io,doublebits/osf.io,mattclark/osf.io,mattclark/osf.io,petermalcolm/osf.io,mluo613/osf.io,caneruguz/osf.io,zkraime/osf.io,DanielSBrown/osf.io,danielneis/osf.io,jinluyuan/osf.io,aaxelb/osf.io,jolene-esposito/osf.io,kch8qx/osf.io,cldershem/osf.io,crcresearch/osf.io,danielneis/osf.io,alexschiller/osf.io,mluke93/osf.io,caseyrygt/osf.io,icereval/osf.io,abought/osf.io,jnayak1/osf.io | #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': ['storageRubeusConfig.js'],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
Remove storageRubeusConfig.js from osfstorage init.py | #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': ['storageRubeusConfig.js'],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
<commit_msg>Remove storageRubeusConfig.js from osfstorage init.py<commit_after> | #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
| #!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': ['storageRubeusConfig.js'],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
Remove storageRubeusConfig.js from osfstorage init.py#!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': ['storageRubeusConfig.js'],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
<commit_msg>Remove storageRubeusConfig.js from osfstorage init.py<commit_after>#!/usr/bin/env python
# encoding: utf-8
from . import routes, views, model
MODELS = [
model.OsfStorageNodeSettings,
model.OsfStorageFileTree,
model.OsfStorageFileRecord,
model.OsfStorageFileVersion,
model.OsfStorageGuidFile,
]
NODE_SETTINGS_MODEL = model.OsfStorageNodeSettings
ROUTES = [
routes.web_routes,
routes.api_routes,
]
SHORT_NAME = 'osfstorage'
FULL_NAME = 'OSF Storage'
OWNERS = ['node']
ADDED_DEFAULT = ['node']
ADDED_MANDATORY = ['node']
VIEWS = []
CONFIGS = []
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.osf_storage_root
MAX_FILE_SIZE = 128
|
51e985119e3b62df69f806426b928053ddbac9d7 | db/base/templatetags/tags.py | db/base/templatetags/tags.py | from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = to_format / 1000
formatted = format(to_format / 1000000, '.3f')
if not prec.is_integer():
point = str(prec - int(prec))[2:]
formatted = format_html('{0}<small>{1}</small> MHz', formatted, point)
return formatted
| from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = int(to_format % 1000)
formatted = format((to_format // 1000) / 1000, '.3f')
if prec:
stripped = str(prec).rstrip('0')
formatted = format_html('{0}<small>{1}</small>', formatted, stripped)
response = format_html('{0} Mhz', formatted)
return response
| Fix frequency formating and handling | Fix frequency formating and handling
| Python | agpl-3.0 | Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db | from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = to_format / 1000
formatted = format(to_format / 1000000, '.3f')
if not prec.is_integer():
point = str(prec - int(prec))[2:]
formatted = format_html('{0}<small>{1}</small> MHz', formatted, point)
return formatted
Fix frequency formating and handling | from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = int(to_format % 1000)
formatted = format((to_format // 1000) / 1000, '.3f')
if prec:
stripped = str(prec).rstrip('0')
formatted = format_html('{0}<small>{1}</small>', formatted, stripped)
response = format_html('{0} Mhz', formatted)
return response
| <commit_before>from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = to_format / 1000
formatted = format(to_format / 1000000, '.3f')
if not prec.is_integer():
point = str(prec - int(prec))[2:]
formatted = format_html('{0}<small>{1}</small> MHz', formatted, point)
return formatted
<commit_msg>Fix frequency formating and handling<commit_after> | from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = int(to_format % 1000)
formatted = format((to_format // 1000) / 1000, '.3f')
if prec:
stripped = str(prec).rstrip('0')
formatted = format_html('{0}<small>{1}</small>', formatted, stripped)
response = format_html('{0} Mhz', formatted)
return response
| from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = to_format / 1000
formatted = format(to_format / 1000000, '.3f')
if not prec.is_integer():
point = str(prec - int(prec))[2:]
formatted = format_html('{0}<small>{1}</small> MHz', formatted, point)
return formatted
Fix frequency formating and handlingfrom django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = int(to_format % 1000)
formatted = format((to_format // 1000) / 1000, '.3f')
if prec:
stripped = str(prec).rstrip('0')
formatted = format_html('{0}<small>{1}</small>', formatted, stripped)
response = format_html('{0} Mhz', formatted)
return response
| <commit_before>from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = to_format / 1000
formatted = format(to_format / 1000000, '.3f')
if not prec.is_integer():
point = str(prec - int(prec))[2:]
formatted = format_html('{0}<small>{1}</small> MHz', formatted, point)
return formatted
<commit_msg>Fix frequency formating and handling<commit_after>from django import template
from django.core.urlresolvers import reverse
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def active(request, urls):
if request.path in (reverse(url) for url in urls.split()):
return 'active'
return None
@register.filter
def frq(value):
try:
to_format = float(value)
except (TypeError, ValueError):
return ''
prec = int(to_format % 1000)
formatted = format((to_format // 1000) / 1000, '.3f')
if prec:
stripped = str(prec).rstrip('0')
formatted = format_html('{0}<small>{1}</small>', formatted, stripped)
response = format_html('{0} Mhz', formatted)
return response
|
837a0e822905fa8c4e0dda33a03f8423b2f9cdb1 | nova/policies/hosts.py | nova/policies/hosts.py | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return hosts_policies
| # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
base.RULE_ADMIN_API,
"""List, Show and Manage physical hosts.
These APIs are all deprecated in favor of os-hypervisors and os-services.""",
[
{
'method': 'GET',
'path': '/os-hosts'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}'
},
{
'method': 'PUT',
'path': '/os-hosts/{host_name}'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/reboot'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/shutdown'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/startup'
}
]),
]
def list_rules():
return hosts_policies
| Add policy description for os-host | Add policy description for os-host
This commit adds policy doc for os-host policies.
Partial implement blueprint policy-docs
Change-Id: Ie15125f025dbb4982ff27cfed12047e8fce3a3cf
| Python | apache-2.0 | rahulunair/nova,mahak/nova,gooddata/openstack-nova,Juniper/nova,gooddata/openstack-nova,rahulunair/nova,klmitch/nova,phenoxim/nova,phenoxim/nova,openstack/nova,openstack/nova,Juniper/nova,rahulunair/nova,mikalstill/nova,mahak/nova,vmturbo/nova,vmturbo/nova,openstack/nova,klmitch/nova,vmturbo/nova,mikalstill/nova,klmitch/nova,jianghuaw/nova,vmturbo/nova,mahak/nova,mikalstill/nova,jianghuaw/nova,jianghuaw/nova,gooddata/openstack-nova,gooddata/openstack-nova,jianghuaw/nova,Juniper/nova,Juniper/nova,klmitch/nova | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return hosts_policies
Add policy description for os-host
This commit adds policy doc for os-host policies.
Partial implement blueprint policy-docs
Change-Id: Ie15125f025dbb4982ff27cfed12047e8fce3a3cf | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
base.RULE_ADMIN_API,
"""List, Show and Manage physical hosts.
These APIs are all deprecated in favor of os-hypervisors and os-services.""",
[
{
'method': 'GET',
'path': '/os-hosts'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}'
},
{
'method': 'PUT',
'path': '/os-hosts/{host_name}'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/reboot'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/shutdown'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/startup'
}
]),
]
def list_rules():
return hosts_policies
| <commit_before># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return hosts_policies
<commit_msg>Add policy description for os-host
This commit adds policy doc for os-host policies.
Partial implement blueprint policy-docs
Change-Id: Ie15125f025dbb4982ff27cfed12047e8fce3a3cf<commit_after> | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
base.RULE_ADMIN_API,
"""List, Show and Manage physical hosts.
These APIs are all deprecated in favor of os-hypervisors and os-services.""",
[
{
'method': 'GET',
'path': '/os-hosts'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}'
},
{
'method': 'PUT',
'path': '/os-hosts/{host_name}'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/reboot'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/shutdown'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/startup'
}
]),
]
def list_rules():
return hosts_policies
| # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return hosts_policies
Add policy description for os-host
This commit adds policy doc for os-host policies.
Partial implement blueprint policy-docs
Change-Id: Ie15125f025dbb4982ff27cfed12047e8fce3a3cf# Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
base.RULE_ADMIN_API,
"""List, Show and Manage physical hosts.
These APIs are all deprecated in favor of os-hypervisors and os-services.""",
[
{
'method': 'GET',
'path': '/os-hosts'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}'
},
{
'method': 'PUT',
'path': '/os-hosts/{host_name}'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/reboot'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/shutdown'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/startup'
}
]),
]
def list_rules():
return hosts_policies
| <commit_before># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return hosts_policies
<commit_msg>Add policy description for os-host
This commit adds policy doc for os-host policies.
Partial implement blueprint policy-docs
Change-Id: Ie15125f025dbb4982ff27cfed12047e8fce3a3cf<commit_after># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hosts'
hosts_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
base.RULE_ADMIN_API,
"""List, Show and Manage physical hosts.
These APIs are all deprecated in favor of os-hypervisors and os-services.""",
[
{
'method': 'GET',
'path': '/os-hosts'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}'
},
{
'method': 'PUT',
'path': '/os-hosts/{host_name}'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/reboot'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/shutdown'
},
{
'method': 'GET',
'path': '/os-hosts/{host_name}/startup'
}
]),
]
def list_rules():
return hosts_policies
|
d0fb729183f702711127b63b1e0898a9a601a7f4 | bitbucket/tests/private/private.py | bitbucket/tests/private/private.py | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
| # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_tags(repo_slug='azertyuiop')
self.assertFalse(success)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_branches(repo_slug='azertyuiop')
self.assertFalse(success)
| Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods. | Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com>
| Python | isc | robwilkerson/BitBucket-api,wadevries/BitBucket-api,chaiapodi/BitBucket-api,affinitic/BitBucket-api,Sheeprider/BitBucket-api,CBitLabs/BitBucket-api,Sheeprider/BitBucket-api,kubilayeksioglu/BitBucket-api,chaiapodi/BitBucket-api | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com> | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_tags(repo_slug='azertyuiop')
self.assertFalse(success)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_branches(repo_slug='azertyuiop')
self.assertFalse(success)
| <commit_before># -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
<commit_msg>Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com><commit_after> | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_tags(repo_slug='azertyuiop')
self.assertFalse(success)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_branches(repo_slug='azertyuiop')
self.assertFalse(success)
| # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com># -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_tags(repo_slug='azertyuiop')
self.assertFalse(success)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_branches(repo_slug='azertyuiop')
self.assertFalse(success)
| <commit_before># -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
<commit_msg>Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com><commit_after># -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
"""Creating a new authenticated Bitbucket..."""
self.bb = Bitbucket(USERNAME, PASSWORD)
# Create a repository.
success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
# Save repository's id
assert success
self.bb.repo_slug = result[u'slug']
def tearDown(self):
"""Destroying the Bitbucket..."""
# Delete the repository.
self.bb.repository.delete()
self.bb = None
class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
""" Testing Bitbucket annonymous methods."""
def test_get_tags(self):
""" Test get_tags."""
success, result = self.bb.get_tags()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_tags(repo_slug='azertyuiop')
self.assertFalse(success)
def test_get_branches(self):
""" Test get_branches."""
success, result = self.bb.get_branches()
self.assertTrue(success)
self.assertIsInstance(result, dict)
# test with invalid repository name
success, result = self.bb.get_branches(repo_slug='azertyuiop')
self.assertFalse(success)
|
c8db390195641c33f84ccd1f645a5af73debc2bd | xapi/tasks.py | xapi/tasks.py | from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
| from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
| Add a name to present task in djcelery options | Add a name to present task in djcelery options
| Python | agpl-3.0 | marcore/pok-eco,marcore/pok-eco | from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
Add a name to present task in djcelery options | from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
| <commit_before>from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
<commit_msg>Add a name to present task in djcelery options<commit_after> | from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
| from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
Add a name to present task in djcelery optionsfrom celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
| <commit_before>from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
<commit_msg>Add a name to present task in djcelery options<commit_after>from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
|
11b0608f2cab4f9c804d5a2e67edfc4270448b71 | ectoken.py | ectoken.py | from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
| from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if len(string) > 512:
raise ValueError(
'%r exceeds maximum length of 512 characters' % string)
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
| Add check for maximum length (taken from the original Edgecast ec_encrypt.c example) | Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)
| Python | bsd-3-clause | sebest/ectoken-py,sebest/ectoken-py | from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
Add check for maximum length (taken from the original Edgecast ec_encrypt.c example) | from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if len(string) > 512:
raise ValueError(
'%r exceeds maximum length of 512 characters' % string)
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
| <commit_before>from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
<commit_msg>Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)<commit_after> | from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if len(string) > 512:
raise ValueError(
'%r exceeds maximum length of 512 characters' % string)
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
| from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if len(string) > 512:
raise ValueError(
'%r exceeds maximum length of 512 characters' % string)
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
| <commit_before>from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
<commit_msg>Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)<commit_after>from ctypes import CDLL, create_string_buffer, byref
import pkg_resources
bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so'))
def ectoken_generate(key, string):
if len(string) > 512:
raise ValueError(
'%r exceeds maximum length of 512 characters' % string)
if isinstance(string, unicode):
string = string.encode('utf-8')
string = 'ec_secure=%03d&%s' % (len(string) + 14, string)
string_len = len(string)
output = create_string_buffer(string_len)
bf.bfencrypt(key, len(key), string, byref(output), string_len)
return output.raw.encode('hex_codec')
|
68e9015d846c08ed331cdca219648d60f6d65737 | ynr/apps/candidates/search_indexes.py | ynr/apps/candidates/search_indexes.py | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_model(self):
return Person
| from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_updated_field(self):
return 'updated_at'
def get_model(self):
return Person
| Add get_updated_field to search index | Add get_updated_field to search index
This will allow us to only update the search index for models updated in
a given timedelta.
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_model(self):
return Person
Add get_updated_field to search index
This will allow us to only update the search index for models updated in
a given timedelta. | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_updated_field(self):
return 'updated_at'
def get_model(self):
return Person
| <commit_before>from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_model(self):
return Person
<commit_msg>Add get_updated_field to search index
This will allow us to only update the search index for models updated in
a given timedelta.<commit_after> | from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_updated_field(self):
return 'updated_at'
def get_model(self):
return Person
| from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_model(self):
return Person
Add get_updated_field to search index
This will allow us to only update the search index for models updated in
a given timedelta.from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_updated_field(self):
return 'updated_at'
def get_model(self):
return Person
| <commit_before>from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_model(self):
return Person
<commit_msg>Add get_updated_field to search index
This will allow us to only update the search index for models updated in
a given timedelta.<commit_after>from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from popolo.models import Person
class PersonIndex(CelerySearchIndex, indexes.Indexable):
# FIXME: this doesn't seem to work for partial names despite what
# docs say
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
family_name = indexes.CharField(model_attr='family_name')
given_name = indexes.CharField(model_attr='given_name')
additional_name = indexes.CharField(model_attr='additional_name')
def get_updated_field(self):
return 'updated_at'
def get_model(self):
return Person
|
bb8506feb44eaa0b38a3d38956bf85c49f54bc5a | fabfile.py | fabfile.py | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| Switch to nose test runners - probably shouldn't use fabric in this project. | Switch to nose test runners - probably shouldn't use fabric in this project.
| Python | mit | peplin/trinity | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
Switch to nose test runners - probably shouldn't use fabric in this project. | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| <commit_before>#!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
<commit_msg>Switch to nose test runners - probably shouldn't use fabric in this project.<commit_after> | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
Switch to nose test runners - probably shouldn't use fabric in this project.#!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
| <commit_before>#!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, tornado_test_runner, tornado_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable,
disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = tornado_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
<commit_msg>Switch to nose test runners - probably shouldn't use fabric in this project.<commit_after>#!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, nose_test_runner, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
env.scm = "git@github.com:bueda/%(unit)s.git" % env
env.scm_http_url = "http://github.com/bueda/%(unit)s" % env
env.root_dir = os.path.abspath(os.path.dirname(__file__))
env.pip_requirements = ["requirements/common.txt",]
env.pip_requirements_dev = ["requirements/dev.txt",]
env.pip_requirements_production = ["requirements/production.txt",]
env.test_runner = nose_test_runner
env.campfire_subdomain = 'bueda'
env.campfire_room = 'Development'
env.campfire_token = '63768eee94d96b7b18e2091f3919b2a2a3dcd12a'
|
900b4c02a2ae1570083bb23e562208331ea2a651 | python/ecep/portal/widgets.py | python/ecep/portal/widgets.py | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
| from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
| Add comments to MapWidget class and MapWidget.render method | Add comments to MapWidget class and MapWidget.render method
| Python | mit | smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
Add comments to MapWidget class and MapWidget.render method | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
| <commit_before>from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
<commit_msg>Add comments to MapWidget class and MapWidget.render method<commit_after> | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
| from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
Add comments to MapWidget class and MapWidget.render methodfrom django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
| <commit_before>from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
<commit_msg>Add comments to MapWidget class and MapWidget.render method<commit_after>from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
|
53a6e81b6a269589df5c6ce199b6248d838f9180 | pythonpic/configs/run_wave.py | pythonpic/configs/run_wave.py | """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super.__init__(grid, [], filename=filename, category_type="wave", title=description)
| """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super().__init__(grid, [], filename=filename, category_type="wave", title=description)
| Fix super bug in wave | Fix super bug in wave
| Python | bsd-3-clause | StanczakDominik/PythonPIC | """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super.__init__(grid, [], filename=filename, category_type="wave", title=description)
Fix super bug in wave | """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super().__init__(grid, [], filename=filename, category_type="wave", title=description)
| <commit_before>""" Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super.__init__(grid, [], filename=filename, category_type="wave", title=description)
<commit_msg>Fix super bug in wave<commit_after> | """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super().__init__(grid, [], filename=filename, category_type="wave", title=description)
| """ Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super.__init__(grid, [], filename=filename, category_type="wave", title=description)
Fix super bug in wave""" Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super().__init__(grid, [], filename=filename, category_type="wave", title=description)
| <commit_before>""" Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super.__init__(grid, [], filename=filename, category_type="wave", title=description)
<commit_msg>Fix super bug in wave<commit_after>""" Run wave propagation"""
# coding=utf-8
import numpy as np
from ..algorithms import BoundaryCondition
from ..classes import Grid, Simulation
class wave_propagation(Simulation):
def __init__(self, filename,
bc = BoundaryCondition.Laser(1, 1, 10, 3).laser_pulse,
):
"""Implements wave propagation"""
T = 50
NG = 60
L = 2 * np.pi
epsilon_0 = 1
c = 1
grid = Grid(T=T, L=L, NG=NG, epsilon_0=epsilon_0, c=c, bc=bc, periodic=False)
description = "Electrostatic wave driven by boundary condition"
super().__init__(grid, [], filename=filename, category_type="wave", title=description)
|
f2c5210b771728ba60ffe81993617b8af07bbaeb | koans/about_none.py | koans/about_none.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(__, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(____, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(__, None is not 0)
self.assertEqual(__, None is not False)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(True, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(True, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(True, None is not 0)
self.assertEqual(True, None is not False)
| Add first pass at "none" koan. One test left. | Add first pass at "none" koan. One test left.
| Python | mit | javierjulio/python-koans-completed,javierjulio/python-koans-completed | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(__, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(____, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(__, None is not 0)
self.assertEqual(__, None is not False)
Add first pass at "none" koan. One test left. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(True, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(True, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(True, None is not 0)
self.assertEqual(True, None is not False)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(__, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(____, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(__, None is not 0)
self.assertEqual(__, None is not False)
<commit_msg>Add first pass at "none" koan. One test left.<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(True, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(True, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(True, None is not 0)
self.assertEqual(True, None is not False)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(__, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(____, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(__, None is not 0)
self.assertEqual(__, None is not False)
Add first pass at "none" koan. One test left.#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(True, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(True, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(True, None is not 0)
self.assertEqual(True, None is not False)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(__, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(____, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(__, None is not 0)
self.assertEqual(__, None is not False)
<commit_msg>Add first pass at "none" koan. One test left.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutNil in the Ruby Koans
#
from runner.koan import *
class AboutNone(Koan):
def test_none_is_an_object(self):
"Unlike NULL in a lot of languages"
self.assertEqual(True, isinstance(None, object))
def test_none_is_universal(self):
"There is only one None"
self.assertEqual(True, None is None)
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
"""
What is the Exception that is thrown when you call a method that does
not exist?
Hint: launch python command console and try the code in the block below.
Don't worry about what 'try' and 'except' do, we'll talk about this later
"""
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
# What exception has been caught?
#
# Need a recap on how to evaluate __class__ attributes?
#
# http://bit.ly/__class__
self.assertEqual(__, ex2.__class__)
# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
self.assertRegexpMatches(ex2.args[0], __)
def test_none_is_distinct(self):
"""
None is distinct from other things which are False.
"""
self.assertEqual(True, None is not 0)
self.assertEqual(True, None is not False)
|
54fc2329fa597739ed7d4e2efb859718f25b255d | pysat/_constellation.py | pysat/_constellation.py |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
|
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify '
'a list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty '
'constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
| Change line wrap to appease pycodestyle. | Change line wrap to appease pycodestyle.
| Python | bsd-3-clause | rstoneback/pysat,jklenzing/pysat |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
Change line wrap to appease pycodestyle. |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify '
'a list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty '
'constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
| <commit_before>
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
<commit_msg>Change line wrap to appease pycodestyle.<commit_after> |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify '
'a list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty '
'constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
|
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
Change line wrap to appease pycodestyle.
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify '
'a list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty '
'constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
| <commit_before>
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
<commit_msg>Change line wrap to appease pycodestyle.<commit_after>
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify '
'a list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty '
'constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
|
c57fd21ca62f9217a943cec5111b64403e968ab5 | kimochi/scripts/initializedb.py | kimochi/scripts/initializedb.py | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
| import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) | Add temporary default admin user | Add temporary default admin user
| Python | mit | matslindh/kimochi,matslindh/kimochi | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
Add temporary default admin user | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) | <commit_before>import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
<commit_msg>Add temporary default admin user<commit_after> | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
Add temporary default admin userimport os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) | <commit_before>import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
<commit_msg>Add temporary default admin user<commit_after>import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
)
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri> [var=value]\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
DBSession.add(User(email='test@example.com', password='test', admin=True)) |
884a06ea0bd2021bfc298a93495433a28a717a3e | reportlab/test/test_tools_pythonpoint.py | reportlab/test/test_tools_pythonpoint.py | """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outdir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
outDir = join(rlDir, 'test')
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
os.remove(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outDir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| Fix buglet in compact testing | Fix buglet in compact testing
| Python | bsd-3-clause | makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile | """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outdir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
outDir = join(rlDir, 'test')
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
os.remove(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
Fix buglet in compact testing | """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outDir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| <commit_before>"""Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outdir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
outDir = join(rlDir, 'test')
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
os.remove(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
<commit_msg>Fix buglet in compact testing<commit_after> | """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outDir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| """Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outdir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
outDir = join(rlDir, 'test')
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
os.remove(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
Fix buglet in compact testing"""Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outDir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
| <commit_before>"""Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outdir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
outDir = join(rlDir, 'test')
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
os.remove(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
<commit_msg>Fix buglet in compact testing<commit_after>"""Tests for the PythonPoint tool.
"""
import os, sys, string
from reportlab.test import unittest
from reportlab.test.utils import makeSuiteForClasses, outputfile
import reportlab
class PythonPointTestCase(unittest.TestCase):
"Some very crude tests on PythonPoint."
def test0(self):
"Test if pythonpoint.pdf can be created from pythonpoint.xml."
join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
rlDir = abspath(dirname(reportlab.__file__))
from reportlab.tools.pythonpoint import pythonpoint
from reportlab.lib.utils import isCompactDistro, open_for_read
ppDir = dirname(pythonpoint.__file__)
xml = join(ppDir, 'demos', 'pythonpoint.xml')
datafilename = 'pythonpoint.pdf'
outDir = outputfile('')
if isCompactDistro():
cwd = None
xml = open_for_read(xml)
else:
cwd = os.getcwd()
os.chdir(join(ppDir, 'demos'))
pdf = join(outDir, datafilename)
if isfile(pdf): os.remove(pdf)
pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename)
if cwd: os.chdir(cwd)
assert os.path.exists(pdf)
def makeSuite():
return makeSuiteForClasses(PythonPointTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
|
1da1000d7bade80a0f68dbacc93ad1e73463c605 | linkedevents/api.py | linkedevents/api.py | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
| import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
| Replace base_name with basename base_name is deprecated | Replace base_name with basename
base_name is deprecated
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
Replace base_name with basename
base_name is deprecated | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
| <commit_before>import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
<commit_msg>Replace base_name with basename
base_name is deprecated<commit_after> | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
| import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
Replace base_name with basename
base_name is deprecatedimport copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
| <commit_before>import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
<commit_msg>Replace base_name with basename
base_name is deprecated<commit_after>import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
|
07c2bdab605eb00bcc59a5540477819d1339e563 | examples/minimal/views.py | examples/minimal/views.py | from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
| from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
def get_breadcrumb(self):
return super().get_breadcrumb() + [{
'url': '/',
'title': 'Additional breadcrumb'
}, {
'title': 'Disabled item'
}]
| Add example for additional breadcrumb items. | Add example for additional breadcrumb items.
| Python | mit | moccu/django-cruditor,moccu/django-cruditor,moccu/django-cruditor | from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
Add example for additional breadcrumb items. | from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
def get_breadcrumb(self):
return super().get_breadcrumb() + [{
'url': '/',
'title': 'Additional breadcrumb'
}, {
'title': 'Disabled item'
}]
| <commit_before>from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
<commit_msg>Add example for additional breadcrumb items.<commit_after> | from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
def get_breadcrumb(self):
return super().get_breadcrumb() + [{
'url': '/',
'title': 'Additional breadcrumb'
}, {
'title': 'Disabled item'
}]
| from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
Add example for additional breadcrumb items.from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
def get_breadcrumb(self):
return super().get_breadcrumb() + [{
'url': '/',
'title': 'Additional breadcrumb'
}, {
'title': 'Disabled item'
}]
| <commit_before>from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
<commit_msg>Add example for additional breadcrumb items.<commit_after>from cruditor.mixins import CruditorMixin
from django.views.generic import TemplateView
from examples.mixins import ExamplesMixin
class DemoView(ExamplesMixin, CruditorMixin, TemplateView):
title = 'Demo view'
template_name = 'minimal/demo.html'
def get_breadcrumb(self):
return super().get_breadcrumb() + [{
'url': '/',
'title': 'Additional breadcrumb'
}, {
'title': 'Disabled item'
}]
|
2539b08770bb5cf5e7cb5dcab3aeef17b163de83 | resrc/utils/construct_body.py | resrc/utils/construct_body.py | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2ascii /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
| # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2txt /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
| Move from ps2ascii to ps2txt, for better results | Move from ps2ascii to ps2txt, for better results
| Python | mit | vhf/resrc,mrbitsdcf/resrc,janez-svetin/resrc,mrbitsdcf/resrc,janez-svetin/resrc,janez-svetin/resrc,mrbitsdcf/resrc,vhf/resrc,vhf/resrc,janez-svetin/resrc,mrbitsdcf/resrc,mrbitsdcf/resrc,vhf/resrc,vhf/resrc,janez-svetin/resrc | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2ascii /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
Move from ps2ascii to ps2txt, for better results | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2txt /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
| <commit_before># -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2ascii /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
<commit_msg>Move from ps2ascii to ps2txt, for better results<commit_after> | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2txt /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
| # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2ascii /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
Move from ps2ascii to ps2txt, for better results# -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2txt /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
| <commit_before># -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2ascii /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
<commit_msg>Move from ps2ascii to ps2txt, for better results<commit_after># -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agent', 'Mozilla/5.0')]
f = opener.open(link.url)
data = f.read()
f.close()
opener.close()
subtype = f.info().subtype
if subtype == 'pdf':
filename = hashlib.md5(link.url).hexdigest()
thefile = open('/tmp/%s.pdf' % filename, "wb")
thefile.write(data)
thefile.close()
os.system(("ps2txt /tmp/%s.pdf /tmp/%s.txt") %(filename , filename))
link.content = open("/tmp/%s.txt" % filename).read()
link.save()
elif subtype == 'html':
from readability.readability import Document
readable_article = Document(data).summary()
link.content = readable_article
link.save()
else:
link.content = u'˘'
link.save()
except:
link.content = u'˘'
link.save()
pass
|
78689cba80d507cc6706ebf5d1981b738837f767 | knox/crypto.py | knox/crypto.py | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| Document unhexlify requirements in hash_token() | Document unhexlify requirements in hash_token()
| Python | mit | James1345/django-rest-knox,James1345/django-rest-knox | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
Document unhexlify requirements in hash_token() | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| <commit_before>import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
<commit_msg>Document unhexlify requirements in hash_token()<commit_after> | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
Document unhexlify requirements in hash_token()import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| <commit_before>import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
<commit_msg>Document unhexlify requirements in hash_token()<commit_after>import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
|
ffd3d61f24a48048ddb562b731ff134a6fc0d924 | django/__init__.py | django/__init__.py | VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| Bump django.VERSION for RC 1. | Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | aparo/django-nonrel,FlaPer87/django-nonrel,aparo/django-nonrel,aparo/django-nonrel,FlaPer87/django-nonrel,FlaPer87/django-nonrel | VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| <commit_before>VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
<commit_msg>Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37<commit_after> | VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| <commit_before>VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
<commit_msg>Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37<commit_after>VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
c9e2c70e05ade220e5aa6a4790ee2a9b720cc46e | sorting_test.py | sorting_test.py | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len) | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1])) | Allow comparison within a fixed time period | Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.
| Python | mit | timpel/stanford-algs,timpel/stanford-algs | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period. | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1])) | <commit_before>import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)<commit_msg>Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.<commit_after> | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1])) | import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1])) | <commit_before>import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def main(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
if __name__ == '__main__':
try:
max_len = int(sys.argv[1])
except (IndexError, ValueError):
print 'Format: python sorting_test.py <log(max input)>'
main(max_len)<commit_msg>Allow comparison within a fixed time period
To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.<commit_after>import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint
def multi_size(max_len):
for n in [2**(n+1) for n in range(max_len)]:
print 'Array size: %d' % n
arr = [randint(0, 2**max_len) for n in range(n)]
current_time = time.time()
quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
print 'Merge sort: %f' % (time.time() - current_time)
current_time = time.time()
quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
print 'Quicksort: %f' % (time.time() - current_time)
print '-----------------'
def fixed_time(sec, length):
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
mergesort.merge_sort.sort(arr)
count += 1
print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)
count = 0
start = time.time()
end = start + sec
while time.time() < end:
arr = [randint(0, length) for n in range(length)]
quicksort.quicksort.sort(arr, 0, length)
count += 1
print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)
if __name__ == '__main__':
if len(sys.argv) > 2:
fixed_time(int(sys.argv[1]), int(sys.argv[2]))
else:
multi_size(int(sys.argv[1])) |
29a57097fb903f2849fe21647dd99e06509c364a | dmoj/utils/ansi.py | dmoj/utils/ansi.py | from collections import OrderedDict
from termcolor import colored
import re
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
try:
import ansi2html
def format_ansi(s):
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
except ImportError:
def format_ansi(s):
escape = OrderedDict([
('&', '&'),
('<', '<'),
('>', '>'),
])
for a, b in escape.items():
s = s.replace(a, b)
return strip_ansi(s)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
| import re
from termcolor import colored
import ansi2html
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
def format_ansi(s):
# TODO: supposedly, the decode isn't necessary https://github.com/ralphbean/ansi2html/issues/60
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s.decode('utf-8'), full=False)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
| Stop maintaining old code paths | Stop maintaining old code paths
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | from collections import OrderedDict
from termcolor import colored
import re
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
try:
import ansi2html
def format_ansi(s):
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
except ImportError:
def format_ansi(s):
escape = OrderedDict([
('&', '&'),
('<', '<'),
('>', '>'),
])
for a, b in escape.items():
s = s.replace(a, b)
return strip_ansi(s)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
Stop maintaining old code paths | import re
from termcolor import colored
import ansi2html
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
def format_ansi(s):
# TODO: supposedly, the decode isn't necessary https://github.com/ralphbean/ansi2html/issues/60
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s.decode('utf-8'), full=False)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
| <commit_before>from collections import OrderedDict
from termcolor import colored
import re
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
try:
import ansi2html
def format_ansi(s):
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
except ImportError:
def format_ansi(s):
escape = OrderedDict([
('&', '&'),
('<', '<'),
('>', '>'),
])
for a, b in escape.items():
s = s.replace(a, b)
return strip_ansi(s)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
<commit_msg>Stop maintaining old code paths<commit_after> | import re
from termcolor import colored
import ansi2html
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
def format_ansi(s):
# TODO: supposedly, the decode isn't necessary https://github.com/ralphbean/ansi2html/issues/60
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s.decode('utf-8'), full=False)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
| from collections import OrderedDict
from termcolor import colored
import re
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
try:
import ansi2html
def format_ansi(s):
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
except ImportError:
def format_ansi(s):
escape = OrderedDict([
('&', '&'),
('<', '<'),
('>', '>'),
])
for a, b in escape.items():
s = s.replace(a, b)
return strip_ansi(s)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
Stop maintaining old code pathsimport re
from termcolor import colored
import ansi2html
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
def format_ansi(s):
# TODO: supposedly, the decode isn't necessary https://github.com/ralphbean/ansi2html/issues/60
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s.decode('utf-8'), full=False)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
| <commit_before>from collections import OrderedDict
from termcolor import colored
import re
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
try:
import ansi2html
def format_ansi(s):
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s, full=False)
except ImportError:
def format_ansi(s):
escape = OrderedDict([
('&', '&'),
('<', '<'),
('>', '>'),
])
for a, b in escape.items():
s = s.replace(a, b)
return strip_ansi(s)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
<commit_msg>Stop maintaining old code paths<commit_after>import re
from termcolor import colored
import ansi2html
def strip_ansi(s):
# http://stackoverflow.com/questions/13506033/filtering-out-ansi-escape-sequences
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)
def format_ansi(s):
# TODO: supposedly, the decode isn't necessary https://github.com/ralphbean/ansi2html/issues/60
return ansi2html.Ansi2HTMLConverter(inline=True).convert(s.decode('utf-8'), full=False)
def ansi_style(text):
from dmoj.judgeenv import no_ansi
def format_inline(text, attrs):
data = attrs.split('|')
colors = data[0].split(',')
if not colors[0]:
colors[0] = None
attrs = data[1].split(',') if len(data) > 1 else []
return colored(text, *colors, attrs=attrs)
return re.sub(r'#ansi\[(.*?)\]\((.*?)\)',
lambda x: format_inline(x.group(1), x.group(2)) if not no_ansi else x.group(1), text)
|
c1e5e6a5c34f1d4617be3053d87af8e95045ad77 | query/views.py | query/views.py | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| Remove raw results from IPWhois object. | Remove raw results from IPWhois object.
| Python | mit | cdubz/rdap-explorer,cdubz/rdap-explorer | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
Remove raw results from IPWhois object. | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| <commit_before>"""
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
<commit_msg>Remove raw results from IPWhois object.<commit_after> | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
Remove raw results from IPWhois object."""
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| <commit_before>"""
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
<commit_msg>Remove raw results from IPWhois object.<commit_after>"""
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
@csrf_protect
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
|
16c457faae6ace57afdc9c11c6f76c6d11a53764 | moksha/lib/utils.py | moksha/lib/utils.py | from decorator import decorator
@decorator
def trace(f, *args, **kw):
r = f(*args, **kw)
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
| from decorator import decorator
@decorator
def trace(f, *args, **kw):
try:
r = f(*args, **kw)
finally:
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
| Make our trace decorator a bit more robust | Make our trace decorator a bit more robust
| Python | apache-2.0 | pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,ralphbean/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,ralphbean/moksha,mokshaproject/moksha,lmacken/moksha,pombredanne/moksha | from decorator import decorator
@decorator
def trace(f, *args, **kw):
r = f(*args, **kw)
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
Make our trace decorator a bit more robust | from decorator import decorator
@decorator
def trace(f, *args, **kw):
try:
r = f(*args, **kw)
finally:
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
| <commit_before>from decorator import decorator
@decorator
def trace(f, *args, **kw):
r = f(*args, **kw)
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
<commit_msg>Make our trace decorator a bit more robust<commit_after> | from decorator import decorator
@decorator
def trace(f, *args, **kw):
try:
r = f(*args, **kw)
finally:
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
| from decorator import decorator
@decorator
def trace(f, *args, **kw):
r = f(*args, **kw)
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
Make our trace decorator a bit more robustfrom decorator import decorator
@decorator
def trace(f, *args, **kw):
try:
r = f(*args, **kw)
finally:
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
| <commit_before>from decorator import decorator
@decorator
def trace(f, *args, **kw):
r = f(*args, **kw)
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
<commit_msg>Make our trace decorator a bit more robust<commit_after>from decorator import decorator
@decorator
def trace(f, *args, **kw):
try:
r = f(*args, **kw)
finally:
print "%s(%s, %s) = %s" % (f.func_name, args, kw, r)
return r
|
6afb6134b24f233cac3dd5fe44599eb95cc4cc33 | bika/lims/upgrade/to1115.py | bika/lims/upgrade/to1115.py | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
for o in bc():
o.reindexObject(idxs=['getSampleTypeTitle', 'getSamplePointTitle'])
| from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
bc.clearFindAndRebuild()
| Fix upgrade step 1115: rebuild catalog | Fix upgrade step 1115: rebuild catalog
| Python | agpl-3.0 | DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,rockfruit/bika.lims,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
for o in bc():
o.reindexObject(idxs=['getSampleTypeTitle', 'getSamplePointTitle'])
Fix upgrade step 1115: rebuild catalog | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
bc.clearFindAndRebuild()
| <commit_before>from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
for o in bc():
o.reindexObject(idxs=['getSampleTypeTitle', 'getSamplePointTitle'])
<commit_msg>Fix upgrade step 1115: rebuild catalog<commit_after> | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
bc.clearFindAndRebuild()
| from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
for o in bc():
o.reindexObject(idxs=['getSampleTypeTitle', 'getSamplePointTitle'])
Fix upgrade step 1115: rebuild catalogfrom Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
bc.clearFindAndRebuild()
| <commit_before>from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
for o in bc():
o.reindexObject(idxs=['getSampleTypeTitle', 'getSamplePointTitle'])
<commit_msg>Fix upgrade step 1115: rebuild catalog<commit_after>from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
""" Just some catalog indexes to update
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
typestool = getToolByName(portal, 'portal_types')
setup = portal.portal_setup
bc = getToolByName(portal, 'bika_catalog')
bc.delIndex('getSampleTypeTitle')
bc.delIndex('getSamplePointTitle')
bc.addIndex('getSampleTypeTitle', 'KeywordIndex')
bc.addIndex('getSamplePointTitle', 'KeywordIndex')
bc.clearFindAndRebuild()
|
1e6e1eae154008a1dddf12a9c7225054ddcf3d15 | corehq/apps/app_manager/xpath_validator/wrapper.py | corehq/apps/app_manager/xpath_validator/wrapper.py | from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| Revert "Added comment and used more generic code in xpath validator" | Revert "Added comment and used more generic code in xpath validator"
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
Revert "Added comment and used more generic code in xpath validator" | from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| <commit_before>from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
<commit_msg>Revert "Added comment and used more generic code in xpath validator"<commit_after> | from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
Revert "Added comment and used more generic code in xpath validator"from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
| <commit_before>from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Collapse whitespace. '\r' mysteriously causes the process to hang in python 3.
stdout, stderr = p.communicate(xpath.replace('\s+', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
<commit_msg>Revert "Added comment and used more generic code in xpath validator"<commit_after>from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import get_xpath_validator_path
from corehq.apps.app_manager.xpath_validator.exceptions import XpathValidationError
from dimagi.utils.subprocess_manager import subprocess_context
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_valid', 'message'])
def validate_xpath(xpath, allow_case_hashtags=False):
with subprocess_context() as subprocess:
path = get_xpath_validator_path()
if allow_case_hashtags:
cmd = ['node', path, '--allow-case-hashtags']
else:
cmd = ['node', path]
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate(xpath.replace('\r', ' ').encode('utf-8'))
exit_code = p.wait()
if exit_code == 0:
return XpathValidationResponse(is_valid=True, message=None)
elif exit_code == 1:
return XpathValidationResponse(is_valid=False, message=stdout)
else:
raise XpathValidationError(
"{path} failed with exit code {exit_code}:\n{stderr}"
.format(path=path, exit_code=exit_code, stderr=stderr))
|
638901243c060b243ebf046304c06ea14a98dbe8 | dynochemy/errors.py | dynochemy/errors.py | # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| Handle updated boto exception format. | Handle updated boto exception format.
See https://github.com/boto/boto/issues/625
| Python | isc | rhettg/Dynochemy | # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
Handle updated boto exception format.
See https://github.com/boto/boto/issues/625 | # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| <commit_before># -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
<commit_msg>Handle updated boto exception format.
See https://github.com/boto/boto/issues/625<commit_after> | # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| # -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
Handle updated boto exception format.
See https://github.com/boto/boto/issues/625# -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| <commit_before># -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
<commit_msg>Handle updated boto exception format.
See https://github.com/boto/boto/issues/625<commit_after># -*- coding: utf-8 -*-
"""
This module contains the set of Dynochemy's exceptions
:copyright: (c) 2012 by Rhett Garber.
:license: ISC, see LICENSE for more details.
"""
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
|
4761d359a28630d0fe378d50e52aad66e88d3a36 | DeepFried2/utils.py | DeepFried2/utils.py | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| Make the compression optional, as it slows down. | Make the compression optional, as it slows down.
| Python | mit | elPistolero/DeepFried2,lucasb-eyer/DeepFried2,Pandoro/DeepFried2,yobibyte/DeepFried2 | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
Make the compression optional, as it slows down. | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| <commit_before>import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
<commit_msg>Make the compression optional, as it slows down.<commit_after> | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
Make the compression optional, as it slows down.import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| <commit_before>import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
<commit_msg>Make the compression optional, as it slows down.<commit_after>import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
7d54cf820a76340f47f2b55ae1b7ff474810ce2b | openelex/tests/test_transform_registry.py | openelex/tests/test_transform_registry.py | from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators, validators)
transform()
mock_transform.assert_called_once_with()
| from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators.values(), validators)
transform()
mock_transform.assert_called_once_with()
| Fix test for transform registry. | Fix test for transform registry.
In 24016ce74afc83b18197c89f95d260b388e6e309, the value of
transform.validators was changed from a list to an OrderedDict.
Update the tests to reflect this change.
| Python | mit | datamade/openelections-core,datamade/openelections-core,openelections/openelections-core,cathydeng/openelections-core,openelections/openelections-core,cathydeng/openelections-core | from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators, validators)
transform()
mock_transform.assert_called_once_with()
Fix test for transform registry.
In 24016ce74afc83b18197c89f95d260b388e6e309, the value of
transform.validators was changed from a list to an OrderedDict.
Update the tests to reflect this change. | from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators.values(), validators)
transform()
mock_transform.assert_called_once_with()
| <commit_before>from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators, validators)
transform()
mock_transform.assert_called_once_with()
<commit_msg>Fix test for transform registry.
In 24016ce74afc83b18197c89f95d260b388e6e309, the value of
transform.validators was changed from a list to an OrderedDict.
Update the tests to reflect this change.<commit_after> | from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators.values(), validators)
transform()
mock_transform.assert_called_once_with()
| from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators, validators)
transform()
mock_transform.assert_called_once_with()
Fix test for transform registry.
In 24016ce74afc83b18197c89f95d260b388e6e309, the value of
transform.validators was changed from a list to an OrderedDict.
Update the tests to reflect this change.from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators.values(), validators)
transform()
mock_transform.assert_called_once_with()
| <commit_before>from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators, validators)
transform()
mock_transform.assert_called_once_with()
<commit_msg>Fix test for transform registry.
In 24016ce74afc83b18197c89f95d260b388e6e309, the value of
transform.validators was changed from a list to an OrderedDict.
Update the tests to reflect this change.<commit_after>from unittest import TestCase
from mock import Mock
from openelex.base.transform import registry
class TestTransformRegistry(TestCase):
def test_register_with_validators(self):
mock_transform = Mock(return_value=None)
mock_transform.__name__ = 'mock_transform'
mock_validator1 = Mock(return_value=None)
mock_validator1.__name__ = 'mock_validator1'
mock_validator2 = Mock(return_value=None)
mock_validator2.__name__ = 'mock_validator2'
validators = [mock_validator1, mock_validator2]
registry.register("XX", mock_transform, validators)
transform = registry.get("XX", "mock_transform")
self.assertEqual(transform.validators.values(), validators)
transform()
mock_transform.assert_called_once_with()
|
220953f4f8136e9c5eff21426421e6ac7f6f502d | tssim/functions/wrapper.py | tssim/functions/wrapper.py | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| Fix bug due to wrong arguments order. | Fix bug due to wrong arguments order.
| Python | mit | mansenfranzen/tssim | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
Fix bug due to wrong arguments order. | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| <commit_before>"""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
<commit_msg>Fix bug due to wrong arguments order.<commit_after> | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
Fix bug due to wrong arguments order."""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| <commit_before>"""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
<commit_msg>Fix bug due to wrong arguments order.<commit_after>"""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
|
c95085fd43825a57476f8a962563561b42385bd8 | ImgProcessingCLI/setup.py | ImgProcessingCLI/setup.py | # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib'],
keywords = ['SUAS'],
)
| # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib', 'sklearn'],
keywords = ['SUAS'],
)
| Add sklearn as a dependency for ImgProcessingCLI | Add sklearn as a dependency for ImgProcessingCLI
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib'],
keywords = ['SUAS'],
)
Add sklearn as a dependency for ImgProcessingCLI | # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib', 'sklearn'],
keywords = ['SUAS'],
)
| <commit_before># This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib'],
keywords = ['SUAS'],
)
<commit_msg>Add sklearn as a dependency for ImgProcessingCLI<commit_after> | # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib', 'sklearn'],
keywords = ['SUAS'],
)
| # This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib'],
keywords = ['SUAS'],
)
Add sklearn as a dependency for ImgProcessingCLI# This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib', 'sklearn'],
keywords = ['SUAS'],
)
| <commit_before># This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib'],
keywords = ['SUAS'],
)
<commit_msg>Add sklearn as a dependency for ImgProcessingCLI<commit_after># This is the setup file for pip
from setuptools import setup, find_packages
import os, sys
from os import path
setup(
name = 'ImgProcessingCLI',
version = '0.0.1',
description = 'Image Processing for SUAS Competition',
url = 'https://github.com/FlintHill/SUAS-Competition',
author = 'Peter Husisian',
author_email = 'phusisian@flinthill.org',
license = 'MIT',
classifiers = [
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
"Operating System :: OS Independent",
],
packages = find_packages(),
install_requires = ['numpy', 'EigenFit', 'pillow', 'matplotlib', 'sklearn'],
keywords = ['SUAS'],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.