commit
stringlengths 40
40
| old_file
stringlengths 4
106
| new_file
stringlengths 4
106
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
2.95k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 7
43k
| ndiff
stringlengths 52
3.31k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| diff
stringlengths 49
3.61k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79bb94f51cd2dca65479cb39f6c365c4c372b0ca
|
forumuser/models.py
|
forumuser/models.py
|
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
|
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
items_per_page = models.PositiveSmallIntegerField(blank=True, null=True)
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
|
Add items per page as a preference to the forumm user model
|
Add items per page as a preference to the forumm user model
|
Python
|
mit
|
hellsgate1001/thatforum_django,hellsgate1001/thatforum_django,hellsgate1001/thatforum_django
|
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
+ items_per_page = models.PositiveSmallIntegerField(blank=True, null=True)
+
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
|
Add items per page as a preference to the forumm user model
|
## Code Before:
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
## Instruction:
Add items per page as a preference to the forumm user model
## Code After:
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
items_per_page = models.PositiveSmallIntegerField(blank=True, null=True)
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
|
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class ForumUser(AbstractUser):
+ items_per_page = models.PositiveSmallIntegerField(blank=True, null=True)
+
def __unicode__(self):
return '%(username)s (%(email)s)' % {
'username': self.username,
'email': self.email
}
|
f574e19b14ff861c45f6c66c64a2570bdb0e3a3c
|
crawl_comments.py
|
crawl_comments.py
|
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
|
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
|
Apply change of file name
|
Apply change of file name
|
Python
|
mit
|
tosh1ki/NicoCrawler
|
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
- main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
+ crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
|
Apply change of file name
|
## Code Before:
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
## Instruction:
Apply change of file name
## Code After:
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
|
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
- main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
? -----
+ crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
? +++++++++
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv]
'''
from docopt import docopt
from nicocrawler.nicocrawler import NicoCrawler
if __name__ == '__main__':
# コマンドライン引数の取得
args = docopt(__doc__)
sqlite_path = args['--sqlite']
csv_path = args['--csv']
ncrawler = NicoCrawler()
ncrawler.connect_sqlite(sqlite_path)
url = 'http://ch.nicovideo.jp/2016winter_anime'
df = ncrawler.get_all_video_url_of_season(url)
ncrawler.initialize_csv_from_db(csv_path)
# # デイリーランキング1~300位の動画を取得する
# url = 'http://www.nicovideo.jp/ranking/fav/daily/all'
# ncrawler.initialize_csv_from_url(url, csv_path, max_page=3)
# ncrawler.get_all_comments_of_csv(csv_path, max_n_iter=1)
|
1a18bfed90f6423a0c52b3f3fe523b4ed77188af
|
examples/example_windows.py
|
examples/example_windows.py
|
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print response
window.add_buttons('One', 'Two', 'Three')
print window.run()
print response
|
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print (response)
window.add_buttons('One', 'Two', 'Three')
print (window.run())
|
Update example for Python 3
|
Update example for Python 3
|
Python
|
bsd-3-clause
|
jaredks/rumps,cbenhagen/rumps
|
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
- print response
+ print (response)
window.add_buttons('One', 'Two', 'Three')
- print window.run()
+ print (window.run())
- print response
|
Update example for Python 3
|
## Code Before:
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print response
window.add_buttons('One', 'Two', 'Three')
print window.run()
print response
## Instruction:
Update example for Python 3
## Code After:
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
print (response)
window.add_buttons('One', 'Two', 'Three')
print (window.run())
|
import rumps
window = rumps.Window('Nothing...', 'ALERTZ')
window.title = 'WINDOWS jk'
window.message = 'Something.'
window.default_text = 'eh'
response = window.run()
- print response
+ print (response)
? + +
window.add_buttons('One', 'Two', 'Three')
- print window.run()
+ print (window.run())
? + +
- print response
|
c8cbd2c660a2e10cc021bdc0a2fead872f77967d
|
ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py
|
ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py
|
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
|
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.iterator():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
|
Use iterator in resultset data migration
|
Use iterator in resultset data migration
|
Python
|
agpl-3.0
|
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
|
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.iterator():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
|
Use iterator in resultset data migration
|
## Code Before:
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
## Instruction:
Use iterator in resultset data migration
## Code After:
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
for result in ResultSet.objects.iterator():
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
|
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyError:
continue
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.all().iterator():
? +++++++++++
update_versions(
versions=result.versions, current_key="is_winner", new_key="elected"
)
result.save()
def backwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
? ^^
+ for result in ResultSet.objects.iterator():
? ++++ ^^^
update_versions(
versions=result.versions, current_key="elected", new_key="is_winner"
)
result.save()
class Migration(migrations.Migration):
dependencies = [("uk_results", "0053_auto_20210928_1007")]
operations = [migrations.RunPython(code=forwards, reverse_code=backwards)]
|
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':
+ 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)
|
## Code 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()
## Instruction:
Allow static files to go through (for now)
## Code 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':
? ^^
+ 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()
|
a116b22a76b0f833aa9f7f2e2ce4b36a95bc9ba0
|
freight/tasks/send_pending_notifications.py
|
freight/tasks/send_pending_notifications.py
|
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
Add logging when no notifications due
|
Add logging when no notifications due
|
Python
|
apache-2.0
|
getsentry/freight,klynton/freight,rshk/freight,rshk/freight,rshk/freight,klynton/freight,rshk/freight,getsentry/freight,klynton/freight,klynton/freight,getsentry/freight,getsentry/freight,getsentry/freight
|
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
+ logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
Add logging when no notifications due
|
## Code Before:
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
## Instruction:
Add logging when no notifications due
## Code After:
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
+ logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
a6dfc5c5f256acd78d806cc8d4ddac9bd1ac34b5
|
barbicanclient/osc_plugin.py
|
barbicanclient/osc_plugin.py
|
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
|
"""OpenStackClient plugin for Key Manager service."""
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
|
Add plug-in summary for osc doc
|
Add plug-in summary for osc doc
Stevedore Sphinx extension handles this comment.
http://docs.openstack.org/developer/python-openstackclient/plugin-commands.html
Change-Id: Id6339d11b900a644647c8c25bbd630ef52a60aab
|
Python
|
apache-2.0
|
openstack/python-barbicanclient
|
+
+ """OpenStackClient plugin for Key Manager service."""
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
|
Add plug-in summary for osc doc
|
## Code Before:
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
## Instruction:
Add plug-in summary for osc doc
## Code After:
"""OpenStackClient plugin for Key Manager service."""
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
|
+
+ """OpenStackClient plugin for Key Manager service."""
from barbicanclient import client
DEFAULT_API_VERSION = '1'
API_VERSION_OPTION = 'os_key_manager_api_version'
API_NAME = 'key_manager'
API_VERSIONS = {
'1': 'barbicanclient.client.Client',
}
def make_client(instance):
"""Returns a Barbican service client."""
return client.Client(session=instance.session,
region_name=instance._region_name)
def build_option_parser(parser):
"""Hook to add global options."""
parser.add_argument('--os-key-manager-api-version',
metavar='<key-manager-api-version>',
default=client.env(
'OS_KEY_MANAGER_API_VERSION',
default=DEFAULT_API_VERSION),
help=('Barbican API version, default=' +
DEFAULT_API_VERSION +
' (Env: OS_KEY_MANAGER_API_VERSION)'))
return parser
|
2febb2e53a7f0b1a0a6952e4ea31c077f45b89f8
|
hooks/post_gen_project.py
|
hooks/post_gen_project.py
|
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
hooks_dir = os.path.join(project_dir, '.git/hooks')
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
dst = os.path.join(hooks_dir, 'prepare-commit-msg')
process = subprocess.call(['git', 'init', project_dir])
os.mkdir('{{cookiecutter.repo_name}}/.git/hooks')
os.symlink(src, dst)
|
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
dst = os.path.join(project_dir, '.git/hooks/prepare-commit-msg')
process = subprocess.call(['git', 'init', project_dir])
os.symlink(src, dst)
|
Remove creation of hooks directory
|
Remove creation of hooks directory
|
Python
|
mit
|
Empiria/matador-cookiecutter
|
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
- hooks_dir = os.path.join(project_dir, '.git/hooks')
-
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
- dst = os.path.join(hooks_dir, 'prepare-commit-msg')
+ dst = os.path.join(project_dir, '.git/hooks/prepare-commit-msg')
process = subprocess.call(['git', 'init', project_dir])
-
- os.mkdir('{{cookiecutter.repo_name}}/.git/hooks')
os.symlink(src, dst)
|
Remove creation of hooks directory
|
## Code Before:
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
hooks_dir = os.path.join(project_dir, '.git/hooks')
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
dst = os.path.join(hooks_dir, 'prepare-commit-msg')
process = subprocess.call(['git', 'init', project_dir])
os.mkdir('{{cookiecutter.repo_name}}/.git/hooks')
os.symlink(src, dst)
## Instruction:
Remove creation of hooks directory
## Code After:
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
dst = os.path.join(project_dir, '.git/hooks/prepare-commit-msg')
process = subprocess.call(['git', 'init', project_dir])
os.symlink(src, dst)
|
import os
import subprocess
project_dir = '{{cookiecutter.repo_name}}'
- hooks_dir = os.path.join(project_dir, '.git/hooks')
-
src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py')
- dst = os.path.join(hooks_dir, 'prepare-commit-msg')
? ^ ^^^
+ dst = os.path.join(project_dir, '.git/hooks/prepare-commit-msg')
? ^^ ^^^^ +++++++++++
process = subprocess.call(['git', 'init', project_dir])
-
- os.mkdir('{{cookiecutter.repo_name}}/.git/hooks')
os.symlink(src, dst)
|
1915cde046c1817c45317ad8ce882e807671fca3
|
oauth_api/permissions.py
|
oauth_api/permissions.py
|
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
return False
def get_scopes(self, request, view):
return {
'required': getattr(view, 'required_scopes', None),
'read': getattr(view, 'read_scopes', None),
'write': getattr(view, 'write_scopes', None),
}
|
from django.core.exceptions import ImproperlyConfigured
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
assert False, ('OAuth2ScopePermission requires the '
'`oauth_api.authentication.OAuth2Authentication` '
'class to be used.')
def get_scopes(self, request, view):
required = getattr(view, 'required_scopes', None)
read = getattr(view, 'read_scopes', None)
write = getattr(view, 'write_scopes', None)
if not required and not read and not write:
raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.')
return {
'required': required,
'read': read,
'write': write,
}
|
Raise ImproperlyConfigured if resource has no scopes defined
|
Raise ImproperlyConfigured if resource has no scopes defined
|
Python
|
bsd-2-clause
|
eofs/django-oauth-api,eofs/django-oauth-api
|
+ from django.core.exceptions import ImproperlyConfigured
+
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
+
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
- return False
+ assert False, ('OAuth2ScopePermission requires the '
+ '`oauth_api.authentication.OAuth2Authentication` '
+ 'class to be used.')
def get_scopes(self, request, view):
+ required = getattr(view, 'required_scopes', None)
+ read = getattr(view, 'read_scopes', None)
+ write = getattr(view, 'write_scopes', None)
+
+ if not required and not read and not write:
+ raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.')
+
return {
- 'required': getattr(view, 'required_scopes', None),
- 'read': getattr(view, 'read_scopes', None),
- 'write': getattr(view, 'write_scopes', None),
+ 'required': required,
+ 'read': read,
+ 'write': write,
}
|
Raise ImproperlyConfigured if resource has no scopes defined
|
## Code Before:
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
return False
def get_scopes(self, request, view):
return {
'required': getattr(view, 'required_scopes', None),
'read': getattr(view, 'read_scopes', None),
'write': getattr(view, 'write_scopes', None),
}
## Instruction:
Raise ImproperlyConfigured if resource has no scopes defined
## Code After:
from django.core.exceptions import ImproperlyConfigured
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
assert False, ('OAuth2ScopePermission requires the '
'`oauth_api.authentication.OAuth2Authentication` '
'class to be used.')
def get_scopes(self, request, view):
required = getattr(view, 'required_scopes', None)
read = getattr(view, 'read_scopes', None)
write = getattr(view, 'write_scopes', None)
if not required and not read and not write:
raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.')
return {
'required': required,
'read': read,
'write': write,
}
|
+ from django.core.exceptions import ImproperlyConfigured
+
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
+
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
- return False
+ assert False, ('OAuth2ScopePermission requires the '
+ '`oauth_api.authentication.OAuth2Authentication` '
+ 'class to be used.')
def get_scopes(self, request, view):
+ required = getattr(view, 'required_scopes', None)
+ read = getattr(view, 'read_scopes', None)
+ write = getattr(view, 'write_scopes', None)
+
+ if not required and not read and not write:
+ raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.')
+
return {
- 'required': getattr(view, 'required_scopes', None),
- 'read': getattr(view, 'read_scopes', None),
- 'write': getattr(view, 'write_scopes', None),
+ 'required': required,
+ 'read': read,
+ 'write': write,
}
|
e25f085025f881ccf0a0da2e620b09787819507a
|
sub.py
|
sub.py
|
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
unpacked.update({'datetime': str(datetime.now())})
if firsttime:
writer = csv.DictWriter(csvfile, fieldnames=list(unpacked.keys()))
writer.writeheader()
firsttime = False
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
|
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
if firsttime:
headers = ['datetime'] + list(unpacked.keys())
writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
firsttime = False
unpacked.update({'datetime': str(datetime.now())})
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
|
Move date/time to the first csv column.
|
Move date/time to the first csv column.
|
Python
|
isc
|
jaj42/hsmedstream,jaj42/phystream
|
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
- unpacked.update({'datetime': str(datetime.now())})
if firsttime:
+ headers = ['datetime'] + list(unpacked.keys())
- writer = csv.DictWriter(csvfile, fieldnames=list(unpacked.keys()))
+ writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
firsttime = False
+ unpacked.update({'datetime': str(datetime.now())})
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
|
Move date/time to the first csv column.
|
## Code Before:
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
unpacked.update({'datetime': str(datetime.now())})
if firsttime:
writer = csv.DictWriter(csvfile, fieldnames=list(unpacked.keys()))
writer.writeheader()
firsttime = False
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
## Instruction:
Move date/time to the first csv column.
## Code After:
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
if firsttime:
headers = ['datetime'] + list(unpacked.keys())
writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
firsttime = False
unpacked.update({'datetime': str(datetime.now())})
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
|
import csv
import sys
import threading
from time import sleep
from datetime import datetime
import msgpack
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b'')
socket.bind("tcp://*:4200")
terminate = threading.Event()
def go():
global terminate
writer = None
firsttime = True
with open('ani.csv', 'w', newline='') as csvfile:
while not terminate.is_set():
try:
msg = socket.recv(flags=zmq.NOBLOCK)
except zmq.Again as e:
# No message received
continue
orig, msgpackdata = msg.split(b' ', 1)
unpacked = msgpack.unpackb(msgpackdata, encoding='utf-8')
if not isinstance(unpacked, dict):
print("Message garbled: {}", unpacked)
continue
- unpacked.update({'datetime': str(datetime.now())})
if firsttime:
+ headers = ['datetime'] + list(unpacked.keys())
- writer = csv.DictWriter(csvfile, fieldnames=list(unpacked.keys()))
? ^^ ---------------- --
+ writer = csv.DictWriter(csvfile, fieldnames=headers)
? ^^^^^^
writer.writeheader()
firsttime = False
+ unpacked.update({'datetime': str(datetime.now())})
writer.writerow(unpacked)
print(msgpackdata, unpacked)
anithread = threading.Thread(target=go)
anithread.start()
while True:
try:
sleep(1)
except KeyboardInterrupt:
terminate.set()
anithread.join()
break
|
2c1673930a40fc94c3d7c7d4f764ea423b638d26
|
mccurse/cli.py
|
mccurse/cli.py
|
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
|
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
if not text:
raise SystemExit('No text to search for!')
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
|
Raise error when there is no term to search for
|
Raise error when there is no term to search for
|
Python
|
agpl-3.0
|
khardix/mccurse
|
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
+ if not text:
+ raise SystemExit('No text to search for!')
+
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
|
Raise error when there is no term to search for
|
## Code Before:
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
## Instruction:
Raise error when there is no term to search for
## Code After:
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
if not text:
raise SystemExit('No text to search for!')
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
|
"""Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
+ if not text:
+ raise SystemExit('No text to search for!')
+
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
|
3577007a2b48ca410a0a34a10f64adcdb3537912
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
|
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
|
Update the classification to production/stable.
|
Update the classification to production/stable.
|
Python
|
bsd-3-clause
|
benspaulding/django-gcframe
|
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
- 'Development Status :: 4 - Beta',
+ 'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
|
Update the classification to production/stable.
|
## Code Before:
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
## Instruction:
Update the classification to production/stable.
## Code After:
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
|
import os
from distutils.core import setup
here = os.path.dirname(__file__)
def get_long_desc():
return open(os.path.join(here, 'README.rst')).read()
# Function borrowed from carljm.
def get_version():
fh = open(os.path.join(here, "gcframe", "__init__.py"))
try:
for line in fh.readlines():
if line.startswith("__version__ ="):
return line.split("=")[1].strip().strip("'")
finally:
fh.close()
setup(
name='django-gcframe',
version=get_version(),
description='Django middleware and decorators for working with Google Chrome Frame.',
url='https://github.com/benspaulding/django-gcframe/',
author='Ben Spaulding',
author_email='[email protected]',
license='BSD',
download_url='https://github.com/benspaulding/django-gcframe/tarball/v%s' % get_version(),
long_description = get_long_desc(),
packages = [
'gcframe',
'gcframe.tests',
],
classifiers=[
- 'Development Status :: 4 - Beta',
? ^ ^^
+ 'Development Status :: 5 - Production/Stable',
? ^ ^^^^^^^^^^^^ +++
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Browsers',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
)
|
2df61655cc99678e7e7db9d0cf1883c702fdc300
|
python/servo/devenv_commands.py
|
python/servo/devenv_commands.py
|
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
|
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
@Command('rustc',
description='Run the Rust compiler',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to rustc")
def run(self, params):
return subprocess.call(["rustc"] + params, env=self.build_env())
|
Add a `mach rustc` command
|
Add a `mach rustc` command
|
Python
|
mpl-2.0
|
youprofit/servo,indykish/servo,evilpie/servo,samfoo/servo,hyowon/servo,Shraddha512/servo,dhananjay92/servo,g-k/servo,aweinstock314/servo,steveklabnik/servo,pyfisch/servo,DominoTree/servo,nerith/servo,WriterOfAlicrow/servo,saratang/servo,CJ8664/servo,nick-thompson/servo,huonw/servo,SimonSapin/servo,tschneidereit/servo,SimonSapin/servo,fiji-flo/servo,runarberg/servo,zentner-kyle/servo,rixrix/servo,avadacatavra/servo,pgonda/servo,dmarcos/servo,nrc/servo,CJ8664/servo,A-deLuna/servo,kindersung/servo,akosel/servo,rnestler/servo,pgonda/servo,rnestler/servo,larsbergstrom/servo,KiChjang/servo,jlegendary/servo,mdibaiee/servo,rentongzhang/servo,thiagopnts/servo,aweinstock314/servo,steveklabnik/servo,tempbottle/servo,srbhklkrn/SERVOENGINE,wartman4404/servo,peterjoel/servo,ryancanhelpyou/servo,tempbottle/servo,emilio/servo,caldwell/servo,pyecs/servo,mdibaiee/servo,nick-thompson/servo,rnestler/servo,wpgallih/servo,bfrohs/servo,dmarcos/servo,saneyuki/servo,tafia/servo,ConnorGBrewster/servo,nick-thompson/servo,aidanhs/servo,nrc/servo,luniv/servo,youprofit/servo,ryancanhelpyou/servo,szeged/servo,akosel/servo,sadmansk/servo,nerith/servo,larsbergstrom/servo,dagnir/servo,nnethercote/servo,WriterOfAlicrow/servo,boghison/servo,aweinstock314/servo,thiagopnts/servo,vks/servo,kindersung/servo,dvberkel/servo,jdramani/servo,aidanhs/servo,wartman4404/servo,g-k/servo,anthgur/servo,fiji-flo/servo,cbrewster/servo,zhangjunlei26/servo,jimberlage/servo,akosel/servo,splav/servo,juzer10/servo,s142857/servo,dati91/servo,Adenilson/prototype-viewing-distance,meh/servo,Adenilson/prototype-viewing-distance,CJ8664/servo,eddyb/servo,hyowon/servo,j3parker/servo,paulrouget/servo,emilio/servo,jdramani/servo,brendandahl/servo,splav/servo,avadacatavra/servo,j3parker/servo,rnestler/servo,brendandahl/servo,dmarcos/servo,sadmansk/servo,g-k/servo,rnestler/servo,aweinstock314/servo,avadacatavra/servo,larsbergstrom/servo,indykish/servo,zhangjunlei26/servo,youprofit/servo,peterjoel/servo,chotchki/servo,Adenilson/prototype-viewing-distance,luniv/servo,rentongzhang/servo,deokjinkim/servo,rnestler/servo,luniv/servo,nnethercote/servo,notriddle/servo,bjwbell/servo,karlito40/servo,tempbottle/servo,saneyuki/servo,sadmansk/servo,CJ8664/servo,runarberg/servo,tschneidereit/servo,brendandahl/servo,deokjinkim/servo,ryancanhelpyou/servo,GreenRecycleBin/servo,nick-thompson/servo,g-k/servo,eddyb/servo,larsbergstrom/servo,youprofit/servo,juzer10/servo,pyecs/servo,caldwell/servo,emilio/servo,froydnj/servo,wpgallih/servo,michaelwu/servo,brendandahl/servo,juzer10/servo,jimberlage/servo,indykish/servo,bfrohs/servo,saneyuki/servo,rixrix/servo,mt2d2/servo,anthgur/servo,mbrubeck/servo,canaltinova/servo,upsuper/servo,srbhklkrn/SERVOENGINE,g-k/servo,nerith/servo,dvberkel/servo,j3parker/servo,Shraddha512/servo,wartman4404/servo,fiji-flo/servo,deokjinkim/servo,mdibaiee/servo,tafia/servo,nnethercote/servo,canaltinova/servo,wpgallih/servo,Adenilson/prototype-viewing-distance,AnthonyBroadCrawford/servo,hyowon/servo,avadacatavra/servo,karlito40/servo,peterjoel/servo,bjwbell/servo,CJ8664/servo,huonw/servo,zhangjunlei26/servo,dhananjay92/servo,AnthonyBroadCrawford/servo,boghison/servo,dsandeephegde/servo,larsbergstrom/servo,shrenikgala/servo,aidanhs/servo,youprofit/servo,echochamber/servo,vks/servo,thiagopnts/servo,ryancanhelpyou/servo,dati91/servo,srbhklkrn/SERVOENGINE,pyfisch/servo,jimberlage/servo,splav/servo,nnethercote/servo,tempbottle/servo,jlegendary/servo,dsandeephegde/servo,ruud-v-a/servo,AnthonyBroadCrawford/servo,luniv/servo,GreenRecycleBin/servo,cbrewster/servo,pyfisch/servo,bfrohs/servo,saneyuki/servo,nick-thompson/servo,ruud-v-a/servo,hyowon/servo,pyfisch/servo,akosel/servo,ryancanhelpyou/servo,kindersung/servo,zentner-kyle/servo,tschneidereit/servo,canaltinova/servo,samfoo/servo,notriddle/servo,splav/servo,saratang/servo,aidanhs/servo,ryancanhelpyou/servo,saneyuki/servo,nick-thompson/servo,notriddle/servo,mattnenterprise/servo,dvberkel/servo,szeged/servo,dmarcos/servo,jimberlage/servo,SimonSapin/servo,WriterOfAlicrow/servo,mt2d2/servo,aidanhs/servo,runarberg/servo,hyowon/servo,GyrosOfWar/servo,jgraham/servo,dati91/servo,samfoo/servo,KiChjang/servo,youprofit/servo,kindersung/servo,nerith/servo,GreenRecycleBin/servo,emilio/servo,deokjinkim/servo,paulrouget/servo,dhananjay92/servo,nnethercote/servo,emilio/servo,j3parker/servo,pyfisch/servo,jimberlage/servo,caldwell/servo,DominoTree/servo,notriddle/servo,mattnenterprise/servo,snf/servo,cbrewster/servo,mdibaiee/servo,mattnenterprise/servo,dvberkel/servo,anthgur/servo,tempbottle/servo,pgonda/servo,deokjinkim/servo,szeged/servo,wartman4404/servo,A-deLuna/servo,rixrix/servo,meh/servo,jimberlage/servo,Adenilson/prototype-viewing-distance,snf/servo,dsandeephegde/servo,ConnorGBrewster/servo,karlito40/servo,chotchki/servo,dati91/servo,pyecs/servo,zhangjunlei26/servo,mattnenterprise/servo,fiji-flo/servo,notriddle/servo,aweinstock314/servo,emilio/servo,rixrix/servo,jlegendary/servo,jlegendary/servo,nrc/servo,s142857/servo,cbrewster/servo,zhangjunlei26/servo,indykish/servo,j3parker/servo,akosel/servo,DominoTree/servo,AnthonyBroadCrawford/servo,kindersung/servo,akosel/servo,CJ8664/servo,dvberkel/servo,mattnenterprise/servo,tschneidereit/servo,caldwell/servo,AnthonyBroadCrawford/servo,brendandahl/servo,srbhklkrn/SERVOENGINE,anthgur/servo,jimberlage/servo,boghison/servo,wartman4404/servo,rnestler/servo,srbhklkrn/SERVOENGINE,SimonSapin/servo,rixrix/servo,aweinstock314/servo,srbhklkrn/SERVOENGINE,jdramani/servo,walac/servo,sadmansk/servo,thiagopnts/servo,KiChjang/servo,dmarcos/servo,dmarcos/servo,hyowon/servo,avadacatavra/servo,szeged/servo,mbrubeck/servo,pgonda/servo,mt2d2/servo,saratang/servo,juzer10/servo,szeged/servo,nrc/servo,michaelwu/servo,codemac/servo,shrenikgala/servo,rentongzhang/servo,mbrubeck/servo,eddyb/servo,shrenikgala/servo,ryancanhelpyou/servo,mattnenterprise/servo,larsbergstrom/servo,cbrewster/servo,tempbottle/servo,WriterOfAlicrow/servo,tafia/servo,wpgallih/servo,walac/servo,CJ8664/servo,snf/servo,paulrouget/servo,snf/servo,evilpie/servo,eddyb/servo,codemac/servo,ConnorGBrewster/servo,bjwbell/servo,codemac/servo,fiji-flo/servo,runarberg/servo,shrenikgala/servo,rentongzhang/servo,srbhklkrn/SERVOENGINE,akosel/servo,DominoTree/servo,jlegendary/servo,mt2d2/servo,nrc/servo,kindersung/servo,GyrosOfWar/servo,mukilan/servo,dati91/servo,bjwbell/servo,fiji-flo/servo,kindersung/servo,fiji-flo/servo,j3parker/servo,Adenilson/prototype-viewing-distance,dvberkel/servo,canaltinova/servo,evilpie/servo,RenaudParis/servo,runarberg/servo,indykish/servo,pyecs/servo,brendandahl/servo,caldwell/servo,rnestler/servo,codemac/servo,tschneidereit/servo,notriddle/servo,evilpie/servo,meh/servo,nrc/servo,evilpie/servo,RenaudParis/servo,mt2d2/servo,splav/servo,A-deLuna/servo,GreenRecycleBin/servo,emilio/servo,michaelwu/servo,mukilan/servo,sadmansk/servo,dagnir/servo,larsbergstrom/servo,nerith/servo,saneyuki/servo,dagnir/servo,wpgallih/servo,echochamber/servo,caldwell/servo,bfrohs/servo,KiChjang/servo,luniv/servo,steveklabnik/servo,michaelwu/servo,hyowon/servo,luniv/servo,jgraham/servo,vks/servo,juzer10/servo,shrenikgala/servo,zhangjunlei26/servo,indykish/servo,A-deLuna/servo,pyfisch/servo,peterjoel/servo,walac/servo,mukilan/servo,karlito40/servo,walac/servo,RenaudParis/servo,nrc/servo,mdibaiee/servo,codemac/servo,huonw/servo,upsuper/servo,paulrouget/servo,froydnj/servo,meh/servo,vks/servo,caldwell/servo,zentner-kyle/servo,avadacatavra/servo,DominoTree/servo,anthgur/servo,zentner-kyle/servo,rentongzhang/servo,jdramani/servo,dvberkel/servo,emilio/servo,paulrouget/servo,mbrubeck/servo,mdibaiee/servo,jgraham/servo,sadmansk/servo,RenaudParis/servo,AnthonyBroadCrawford/servo,saneyuki/servo,GreenRecycleBin/servo,larsbergstrom/servo,nnethercote/servo,jgraham/servo,echochamber/servo,mdibaiee/servo,chotchki/servo,saneyuki/servo,nick-thompson/servo,wartman4404/servo,walac/servo,wpgallih/servo,thiagopnts/servo,WriterOfAlicrow/servo,boghison/servo,canaltinova/servo,wpgallih/servo,evilpie/servo,walac/servo,dsandeephegde/servo,SimonSapin/servo,echochamber/servo,ConnorGBrewster/servo,zhangjunlei26/servo,mukilan/servo,g-k/servo,steveklabnik/servo,saratang/servo,g-k/servo,dati91/servo,emilio/servo,tafia/servo,GyrosOfWar/servo,SimonSapin/servo,karlito40/servo,huonw/servo,thiagopnts/servo,upsuper/servo,dsandeephegde/servo,bfrohs/servo,sadmansk/servo,wpgallih/servo,pyecs/servo,dagnir/servo,bjwbell/servo,splav/servo,canaltinova/servo,cbrewster/servo,bjwbell/servo,larsbergstrom/servo,nerith/servo,Shraddha512/servo,brendandahl/servo,DominoTree/servo,dsandeephegde/servo,szeged/servo,upsuper/servo,mbrubeck/servo,jgraham/servo,dhananjay92/servo,KiChjang/servo,anthgur/servo,snf/servo,peterjoel/servo,karlito40/servo,zentner-kyle/servo,pyecs/servo,jdramani/servo,aidanhs/servo,dhananjay92/servo,saratang/servo,KiChjang/servo,karlito40/servo,paulrouget/servo,paulrouget/servo,ruud-v-a/servo,froydnj/servo,ConnorGBrewster/servo,rentongzhang/servo,jimberlage/servo,indykish/servo,pyecs/servo,peterjoel/servo,A-deLuna/servo,vks/servo,pyfisch/servo,upsuper/servo,Shraddha512/servo,szeged/servo,wpgallih/servo,Shraddha512/servo,evilpie/servo,mbrubeck/servo,peterjoel/servo,zentner-kyle/servo,GreenRecycleBin/servo,meh/servo,aweinstock314/servo,mbrubeck/servo,tschneidereit/servo,shrenikgala/servo,chotchki/servo,luniv/servo,eddyb/servo,fiji-flo/servo,runarberg/servo,pgonda/servo,evilpie/servo,GyrosOfWar/servo,splav/servo,echochamber/servo,notriddle/servo,paulrouget/servo,steveklabnik/servo,saneyuki/servo,GreenRecycleBin/servo,canaltinova/servo,mattnenterprise/servo,dmarcos/servo,DominoTree/servo,mt2d2/servo,RenaudParis/servo,froydnj/servo,chotchki/servo,meh/servo,peterjoel/servo,szeged/servo,SimonSapin/servo,canaltinova/servo,sadmansk/servo,KiChjang/servo,samfoo/servo,ruud-v-a/servo,tafia/servo,rixrix/servo,zhangjunlei26/servo,RenaudParis/servo,saneyuki/servo,michaelwu/servo,upsuper/servo,zentner-kyle/servo,DominoTree/servo,rixrix/servo,mattnenterprise/servo,tafia/servo,SimonSapin/servo,jdramani/servo,GyrosOfWar/servo,bfrohs/servo,steveklabnik/servo,boghison/servo,jgraham/servo,ruud-v-a/servo,huonw/servo,cbrewster/servo,DominoTree/servo,RenaudParis/servo,avadacatavra/servo,emilio/servo,paulrouget/servo,notriddle/servo,dhananjay92/servo,paulrouget/servo,pgonda/servo,tschneidereit/servo,s142857/servo,GyrosOfWar/servo,A-deLuna/servo,jgraham/servo,deokjinkim/servo,peterjoel/servo,dagnir/servo,dsandeephegde/servo,GreenRecycleBin/servo,s142857/servo,KiChjang/servo,saratang/servo,dagnir/servo,DominoTree/servo,vks/servo,eddyb/servo,GreenRecycleBin/servo,dati91/servo,upsuper/servo,juzer10/servo,notriddle/servo,dati91/servo,wartman4404/servo,samfoo/servo,Adenilson/prototype-viewing-distance,rixrix/servo,Shraddha512/servo,A-deLuna/servo,codemac/servo,bjwbell/servo,nnethercote/servo,froydnj/servo,s142857/servo,nnethercote/servo,larsbergstrom/servo,aidanhs/servo,meh/servo,jimberlage/servo,szeged/servo,ConnorGBrewster/servo,upsuper/servo,ruud-v-a/servo,jlegendary/servo,huonw/servo,KiChjang/servo,avadacatavra/servo,dagnir/servo,ConnorGBrewster/servo,cbrewster/servo,eddyb/servo,mt2d2/servo,splav/servo,deokjinkim/servo,boghison/servo,Shraddha512/servo,indykish/servo,anthgur/servo,ConnorGBrewster/servo,s142857/servo,pgonda/servo,s142857/servo,nnethercote/servo,walac/servo,thiagopnts/servo,juzer10/servo,mbrubeck/servo,thiagopnts/servo,jdramani/servo,codemac/servo,WriterOfAlicrow/servo,jlegendary/servo,peterjoel/servo,echochamber/servo,szeged/servo,mukilan/servo,steveklabnik/servo,splav/servo,pyfisch/servo,indykish/servo,youprofit/servo,dsandeephegde/servo,nerith/servo,WriterOfAlicrow/servo,notriddle/servo,CJ8664/servo,j3parker/servo,saratang/servo,tafia/servo,pyfisch/servo,GyrosOfWar/servo,snf/servo,echochamber/servo,boghison/servo,evilpie/servo,samfoo/servo,rixrix/servo,snf/servo,anthgur/servo,chotchki/servo,mukilan/servo,AnthonyBroadCrawford/servo,vks/servo,splav/servo,nnethercote/servo,froydnj/servo,zhangjunlei26/servo,samfoo/servo,KiChjang/servo,pyfisch/servo,michaelwu/servo,dhananjay92/servo,tempbottle/servo,runarberg/servo,eddyb/servo,huonw/servo,shrenikgala/servo,rentongzhang/servo
|
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
+ @Command('rustc',
+ description='Run the Rust compiler',
+ category='devenv',
+ allow_all_args=True)
+ @CommandArgument('params', default=None, nargs='...',
+ help="Command-line arguments to be passed through to rustc")
+ def run(self, params):
+ return subprocess.call(["rustc"] + params, env=self.build_env())
+
|
Add a `mach rustc` command
|
## Code Before:
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
## Instruction:
Add a `mach rustc` command
## Code After:
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
@Command('rustc',
description='Run the Rust compiler',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to rustc")
def run(self, params):
return subprocess.call(["rustc"] + params, env=self.build_env())
|
from __future__ import print_function, unicode_literals
import json
import os
import os.path as path
import shutil
import subprocess
import sys
import tarfile
from time import time
import urllib
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import CommandBase
@CommandProvider
class MachCommands(CommandBase):
@Command('cargo',
description='Run Cargo',
category='devenv',
allow_all_args=True)
@CommandArgument('params', default=None, nargs='...',
help="Command-line arguments to be passed through to Cargo")
def run(self, params):
return subprocess.call(["cargo"] + params,
env=self.build_env())
+
+ @Command('rustc',
+ description='Run the Rust compiler',
+ category='devenv',
+ allow_all_args=True)
+ @CommandArgument('params', default=None, nargs='...',
+ help="Command-line arguments to be passed through to rustc")
+ def run(self, params):
+ return subprocess.call(["rustc"] + params, env=self.build_env())
|
22aaf754eb04e9f345c55f73ffb0f549d83c68df
|
apps/explorer/tests/test_templatetags.py
|
apps/explorer/tests/test_templatetags.py
|
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
|
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
class ConcatTestCase(TestCase):
def test_concat(self):
expected = 'foo-bar'
assert explorer.concat('foo-', 'bar') == expected
|
Add test for concat template tag
|
Add test for concat template tag
|
Python
|
bsd-3-clause
|
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
|
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
+
+ class ConcatTestCase(TestCase):
+
+ def test_concat(self):
+
+ expected = 'foo-bar'
+ assert explorer.concat('foo-', 'bar') == expected
+
|
Add test for concat template tag
|
## Code Before:
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
## Instruction:
Add test for concat template tag
## Code After:
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
class ConcatTestCase(TestCase):
def test_concat(self):
expected = 'foo-bar'
assert explorer.concat('foo-', 'bar') == expected
|
from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
+
+
+ class ConcatTestCase(TestCase):
+
+ def test_concat(self):
+
+ expected = 'foo-bar'
+ assert explorer.concat('foo-', 'bar') == expected
|
7dd0c64b4503ab32cf79864f4c23016518b1cdbd
|
electionleaflets/apps/api/tests/test_create_leaflet.py
|
electionleaflets/apps/api/tests/test_create_leaflet.py
|
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('leaflet-list')
leaflet_image_url = reverse('leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
# Upload some images
for name, path in IMAGES:
data = {
'image': open(path),
'leaflet': leaflet_id
}
response = self.client.post(leaflet_image_url,
data, format='multipart')
response = self.client.get(leaflet_url+"1/", format='json')
self.assertEqual(len(response.data['images']), 6)
|
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('api:leaflet-list')
leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
self.assertEqual(leaflet_id, 1)
# import ipdb
# ipdb.set_trace()
# # Upload some images
# for name, path in IMAGES:
# data = {
# 'image': open(path),
# 'leaflet_id': leaflet_id
# }
#
# response = self.client.post(leaflet_image_url,
# data, format='multipart')
# response = self.client.get(leaflet_url+"1/", format='json')
# self.assertEqual(len(response.data['images']), 6)
|
Remove some API tests for now
|
Remove some API tests for now
|
Python
|
mit
|
JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets
|
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
- leaflet_url = reverse('leaflet-list')
+ leaflet_url = reverse('api:leaflet-list')
- leaflet_image_url = reverse('leafletimage-list')
+ leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
+ self.assertEqual(leaflet_id, 1)
+ # import ipdb
+ # ipdb.set_trace()
+ # # Upload some images
+ # for name, path in IMAGES:
+ # data = {
+ # 'image': open(path),
+ # 'leaflet_id': leaflet_id
+ # }
+ #
+ # response = self.client.post(leaflet_image_url,
+ # data, format='multipart')
+ # response = self.client.get(leaflet_url+"1/", format='json')
+ # self.assertEqual(len(response.data['images']), 6)
- # Upload some images
- for name, path in IMAGES:
- data = {
- 'image': open(path),
- 'leaflet': leaflet_id
- }
- response = self.client.post(leaflet_image_url,
- data, format='multipart')
- response = self.client.get(leaflet_url+"1/", format='json')
- self.assertEqual(len(response.data['images']), 6)
-
|
Remove some API tests for now
|
## Code Before:
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('leaflet-list')
leaflet_image_url = reverse('leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
# Upload some images
for name, path in IMAGES:
data = {
'image': open(path),
'leaflet': leaflet_id
}
response = self.client.post(leaflet_image_url,
data, format='multipart')
response = self.client.get(leaflet_url+"1/", format='json')
self.assertEqual(len(response.data['images']), 6)
## Instruction:
Remove some API tests for now
## Code After:
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('api:leaflet-list')
leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
self.assertEqual(leaflet_id, 1)
# import ipdb
# ipdb.set_trace()
# # Upload some images
# for name, path in IMAGES:
# data = {
# 'image': open(path),
# 'leaflet_id': leaflet_id
# }
#
# response = self.client.post(leaflet_image_url,
# data, format='multipart')
# response = self.client.get(leaflet_url+"1/", format='json')
# self.assertEqual(len(response.data['images']), 6)
|
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
- leaflet_url = reverse('leaflet-list')
+ leaflet_url = reverse('api:leaflet-list')
? ++++
- leaflet_image_url = reverse('leafletimage-list')
+ leaflet_image_url = reverse('api:leafletimage-list')
? ++++
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
-
+ self.assertEqual(leaflet_id, 1)
+ # import ipdb
+ # ipdb.set_trace()
- # Upload some images
+ # # Upload some images
? ++
- for name, path in IMAGES:
+ # for name, path in IMAGES:
? ++
- data = {
+ # data = {
? ++
- 'image': open(path),
+ # 'image': open(path),
? ++
- 'leaflet': leaflet_id
+ # 'leaflet_id': leaflet_id
? ++ +++
- }
+ # }
? ++
+ #
- response = self.client.post(leaflet_image_url,
+ # response = self.client.post(leaflet_image_url,
? ++
- data, format='multipart')
+ # data, format='multipart')
? ++
- response = self.client.get(leaflet_url+"1/", format='json')
+ # response = self.client.get(leaflet_url+"1/", format='json')
? ++
- self.assertEqual(len(response.data['images']), 6)
+ # self.assertEqual(len(response.data['images']), 6)
? ++
|
610c979d00b3b89f3f2b16d58e4b2a797b380d41
|
tests/fixtures/postgres.py
|
tests/fixtures/postgres.py
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
Add connection string for connecting to virtool database in order to create a test database
|
Add connection string for connecting to virtool database in order to create a test database
|
Python
|
mit
|
igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
- engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
+ pg_connection_string = test_pg_connection_string.split('/')
+ pg_connection_string[-1] = 'virtool'
+ engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
Add connection string for connecting to virtool database in order to create a test database
|
## Code Before:
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
## Instruction:
Add connection string for connecting to virtool database in order to create a test database
## Code After:
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
- engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
+ pg_connection_string = test_pg_connection_string.split('/')
+ pg_connection_string[-1] = 'virtool'
+ engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
540bffe17ede75bc6afd9b2d45e343e0eac4552b
|
rna-transcription/rna_transcription.py
|
rna-transcription/rna_transcription.py
|
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
|
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna_old(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
|
Add an exception based version
|
Add an exception based version
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
- DNA = {"A", "C", "T", "G"}
-
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
+ try:
+ return "".join([TRANS[n] for n in dna])
+ except KeyError:
+ return ""
+
+
+ # Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
+
+ DNA = {"A", "C", "T", "G"}
+ TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
+
+
+ def to_rna_old(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
|
Add an exception based version
|
## Code Before:
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
## Instruction:
Add an exception based version
## Code After:
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna_old(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
|
- DNA = {"A", "C", "T", "G"}
-
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
+ try:
+ return "".join([TRANS[n] for n in dna])
+ except KeyError:
+ return ""
+
+
+ # Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
+
+ DNA = {"A", "C", "T", "G"}
+ TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
+
+
+ def to_rna_old(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
|
023109283545141dc0ed88a8a7f67d7c21da2a89
|
oauth/api/serializers.py
|
oauth/api/serializers.py
|
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=255)
email = serializers.CharField(max_length=255)
id = serializers.IntegerField()
|
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=200)
id = serializers.IntegerField()
|
Revert "Try to add email to OAuth response"
|
Revert "Try to add email to OAuth response"
This reverts commit 91a047755a66dc2cf0e029b1de606b94925dd297.
|
Python
|
mit
|
ZeusWPI/oauth,ZeusWPI/oauth
|
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
- username = serializers.CharField(max_length=255)
+ username = serializers.CharField(max_length=200)
- email = serializers.CharField(max_length=255)
id = serializers.IntegerField()
|
Revert "Try to add email to OAuth response"
|
## Code Before:
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=255)
email = serializers.CharField(max_length=255)
id = serializers.IntegerField()
## Instruction:
Revert "Try to add email to OAuth response"
## Code After:
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=200)
id = serializers.IntegerField()
|
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
- username = serializers.CharField(max_length=255)
? ^^
+ username = serializers.CharField(max_length=200)
? ^^
- email = serializers.CharField(max_length=255)
id = serializers.IntegerField()
|
1c482edbc29d008a8de9a0762c1a85027de083cc
|
src/spz/test/test_views.py
|
src/spz/test/test_views.py
|
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
from util.build_assets import build_assets
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
build_assets()
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
|
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
|
Remove build_assets from test since test client will neither interprete css nor javascript
|
Remove build_assets from test since test client will neither interprete css nor javascript
|
Python
|
mit
|
spz-signup/spz-signup
|
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
- from util.build_assets import build_assets
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
- build_assets()
-
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
|
Remove build_assets from test since test client will neither interprete css nor javascript
|
## Code Before:
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
from util.build_assets import build_assets
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
build_assets()
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
## Instruction:
Remove build_assets from test since test client will neither interprete css nor javascript
## Code After:
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
|
import pytest
from spz import app
from util.init_db import recreate_tables, insert_resources
- from util.build_assets import build_assets
@pytest.fixture
def client():
client = app.test_client()
recreate_tables()
insert_resources()
- build_assets()
-
yield client
def test_startpage(client):
assert client.get('/').status_code == 200
|
e04123ce0b368b19015270b1fc1bd1f706c765cf
|
pwm/_compat.py
|
pwm/_compat.py
|
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
|
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
input = input
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
|
Fix python 3 input compatiblity
|
Fix python 3 input compatiblity
|
Python
|
mit
|
thusoy/pwm,thusoy/pwm
|
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
+ input = input
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
|
Fix python 3 input compatiblity
|
## Code Before:
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
## Instruction:
Fix python 3 input compatiblity
## Code After:
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
input = input
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
|
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection
input = raw_input
def ord_byte(char):
''' convert a single character into integer representation '''
return ord(char)
else: # pragma: no cover
from configparser import RawConfigParser
from http.client import HTTPConnection
+ input = input
def ord_byte(byte):
''' convert a single byte into integer representation '''
return byte
|
dc884cfd49133a9a25cc5ba6276b94dd44d18729
|
test/test_general.py
|
test/test_general.py
|
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
apiary.instruct_queen('A1', jobs, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
assert i == "Exit code: 6"
print i
sys.exit(0)
|
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
apiary.instruct_queen('A1', job1, ErrWorker)
job2 = ["ls -l ~", "date", "cal"]
apiary.instruct_queen('A2', job2)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
assert i != '' and i != None
|
Add jobs to second test queen, add assertions
|
Add jobs to second test queen, add assertions
|
Python
|
bsd-3-clause
|
iansmcf/busybees
|
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
- jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110",
+ job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
- apiary.instruct_queen('A1', jobs, ErrWorker)
+ apiary.instruct_queen('A1', job1, ErrWorker)
+
+ job2 = ["ls -l ~", "date", "cal"]
+ apiary.instruct_queen('A2', job2)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
+ assert i != '' and i != None
- assert i == "Exit code: 6"
- print i
- sys.exit(0)
|
Add jobs to second test queen, add assertions
|
## Code Before:
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
apiary.instruct_queen('A1', jobs, ErrWorker)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
assert i == "Exit code: 6"
print i
sys.exit(0)
## Instruction:
Add jobs to second test queen, add assertions
## Code After:
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110",
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
apiary.instruct_queen('A1', job1, ErrWorker)
job2 = ["ls -l ~", "date", "cal"]
apiary.instruct_queen('A2', job2)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
assert i != '' and i != None
|
import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hive.Hive()
apiary.create_queen('A1')
apiary.create_queen('A2')
apiary.start_queen('A1')
apiary.start_queen('A2')
- jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110",
? ^
+ job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110",
? ^
"iscsiadm -m discovery -t st -p 192.168.90.110",
"iscsiadm -m discovery -t st -p 192.168.88.110"]
- apiary.instruct_queen('A1', jobs, ErrWorker)
? ^
+ apiary.instruct_queen('A1', job1, ErrWorker)
? ^
+
+ job2 = ["ls -l ~", "date", "cal"]
+ apiary.instruct_queen('A2', job2)
apiary.kill_queen('A1')
time.sleep(3)
this = apiary.die()
for key in this.keys():
for i in this[key]:
+ assert i != '' and i != None
- assert i == "Exit code: 6"
- print i
- sys.exit(0)
|
7e88739d91cd7db35ffb36804ae59d1878eb2da3
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
Use py_modules and not packages
|
Use py_modules and not packages
|
Python
|
bsd-3-clause
|
agoragames/py-eventsocket
|
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
- packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
+ py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
Use py_modules and not packages
|
## Code Before:
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
## Instruction:
Use py_modules and not packages
## Code After:
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
- packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
+ py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
1dd863336641b3e9172c9a08018386bb133960bf
|
whitenoise/__init__.py
|
whitenoise/__init__.py
|
from .base import WhiteNoise
__version__ = '2.0.6'
__all__ = ['WhiteNoise']
|
from .base import WhiteNoise
__version__ = 'development'
__all__ = ['WhiteNoise']
|
Change version until ready for release
|
Change version until ready for release
|
Python
|
mit
|
evansd/whitenoise,evansd/whitenoise,evansd/whitenoise
|
from .base import WhiteNoise
- __version__ = '2.0.6'
+ __version__ = 'development'
__all__ = ['WhiteNoise']
|
Change version until ready for release
|
## Code Before:
from .base import WhiteNoise
__version__ = '2.0.6'
__all__ = ['WhiteNoise']
## Instruction:
Change version until ready for release
## Code After:
from .base import WhiteNoise
__version__ = 'development'
__all__ = ['WhiteNoise']
|
from .base import WhiteNoise
- __version__ = '2.0.6'
+ __version__ = 'development'
__all__ = ['WhiteNoise']
|
39309bb0b8fe088b6576cfbf4d744f58ca6b1b0b
|
tests/test_quiz1.py
|
tests/test_quiz1.py
|
from playwright.sync_api import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False, slow_mo=100)
context = browser.new_context()
# Open new page
page = context.new_page()
page.goto("http://pyar.github.io/PyZombis/master/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
|
def test_quiz1_2(page):
page.goto("/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
|
Convert sample test to pytest
|
Convert sample test to pytest
|
Python
|
agpl-3.0
|
PyAr/PyZombis,PyAr/PyZombis,PyAr/PyZombis
|
+ def test_quiz1_2(page):
+ page.goto("/quiz/Quiz1.html")
- from playwright.sync_api import sync_playwright
-
- def run(playwright):
- browser = playwright.chromium.launch(headless=False, slow_mo=100)
- context = browser.new_context()
-
- # Open new page
- page = context.new_page()
-
- page.goto("http://pyar.github.io/PyZombis/master/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
+
-
- # ---------------------
- context.close()
- browser.close()
-
- with sync_playwright() as playwright:
- run(playwright)
|
Convert sample test to pytest
|
## Code Before:
from playwright.sync_api import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False, slow_mo=100)
context = browser.new_context()
# Open new page
page = context.new_page()
page.goto("http://pyar.github.io/PyZombis/master/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
## Instruction:
Convert sample test to pytest
## Code After:
def test_quiz1_2(page):
page.goto("/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
|
+ def test_quiz1_2(page):
+ page.goto("/quiz/Quiz1.html")
- from playwright.sync_api import sync_playwright
-
- def run(playwright):
- browser = playwright.chromium.launch(headless=False, slow_mo=100)
- context = browser.new_context()
-
- # Open new page
- page = context.new_page()
-
- page.goto("http://pyar.github.io/PyZombis/master/quiz/Quiz1.html")
page.click("text=def metros_a_milimetros(n):")
page.press("text=def metros_a_milimetros(n):", "ArrowDown")
page.press("text=def metros_a_milimetros(n):", "Tab")
page.type("text=def metros_a_milimetros(n):", "return n * 1000")
page.click("#q1_2 >> *css=button >> text=Run")
page.hover("#q1_2 >> text=You passed:")
assert page.inner_text("#q1_2 >> text=You passed:") == "You passed: 100.0% of the tests"
element_handle = page.query_selector("[data-childcomponent='q1_2']")
element_handle.screenshot(path="screenshot.png")
-
- # ---------------------
- context.close()
- browser.close()
-
- with sync_playwright() as playwright:
- run(playwright)
|
0a9f378784e8c30cdf16d4d1caaf3b98f112bb90
|
nap/meta.py
|
nap/meta.py
|
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
if not name[0] == '_'
)
return object.__new__(type(str('Meta'), (cls,), attrs))
|
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
if not name[0] == '_' and hasattr(cls, name)
)
return object.__new__(type(str('Meta'), (cls,), attrs))
|
Make Meta class enforce only known properties
|
Make Meta class enforce only known properties
|
Python
|
bsd-3-clause
|
MarkusH/django-nap,limbera/django-nap
|
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
- if not name[0] == '_'
+ if not name[0] == '_' and hasattr(cls, name)
)
return object.__new__(type(str('Meta'), (cls,), attrs))
|
Make Meta class enforce only known properties
|
## Code Before:
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
if not name[0] == '_'
)
return object.__new__(type(str('Meta'), (cls,), attrs))
## Instruction:
Make Meta class enforce only known properties
## Code After:
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
if not name[0] == '_' and hasattr(cls, name)
)
return object.__new__(type(str('Meta'), (cls,), attrs))
|
from __future__ import unicode_literals
class Meta(object):
'''Generic container for Meta classes'''
def __new__(cls, meta=None):
# Return a new class base on ourselves
attrs = dict(
(name, getattr(meta, name))
for name in dir(meta)
- if not name[0] == '_'
+ if not name[0] == '_' and hasattr(cls, name)
)
return object.__new__(type(str('Meta'), (cls,), attrs))
|
733d48510c4d6d8f4b9f07b6e33075cc20d1720a
|
gewebehaken/app.py
|
gewebehaken/app.py
|
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
Remove default route for serving static files from URL map.
|
Remove default route for serving static files from URL map.
|
Python
|
mit
|
homeworkprod/gewebehaken
|
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
- app = Flask(__name__)
+ app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
Remove default route for serving static files from URL map.
|
## Code Before:
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
## Instruction:
Remove default route for serving static files from URL map.
## Code After:
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
- app = Flask(__name__)
+ app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
ce39e4a5573e7b3a882ee4a327b3c9eb088d1d07
|
senlin/profiles/container/docker.py
|
senlin/profiles/container/docker.py
|
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
CONTEXT, IMAGE, NAME, COMMAND,
) = (
'context', 'image', 'name', 'command',
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
|
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
CONTEXT, IMAGE, NAME, COMMAND, HOST_NODE, HOST_CLUSTER
) = (
'context', 'image', 'name', 'command', 'host_node', 'host_cluster',
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
HOST_NODE: schema.String(
_('The node on which container will be launched.')
),
HOST_CLUSTER: schema.String(
_('The cluster on which container cluster will be launched.')
),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
|
Add 'host_node' and 'host_cluster' properties to container profile
|
Add 'host_node' and 'host_cluster' properties to container profile
Add 'host_node' and 'host_cluster' properties to container profile,
in a container profile, either 'host_node' or 'host_cluster' will
be assigned a value for a container node creation or a container
cluster creation.
blueprint container-profile-support
Change-Id: Ief464375bf651ebe1770c3fcf0488f29b25a94f4
|
Python
|
apache-2.0
|
stackforge/senlin,openstack/senlin,stackforge/senlin,openstack/senlin,openstack/senlin
|
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
- CONTEXT, IMAGE, NAME, COMMAND,
+ CONTEXT, IMAGE, NAME, COMMAND, HOST_NODE, HOST_CLUSTER
) = (
- 'context', 'image', 'name', 'command',
+ 'context', 'image', 'name', 'command', 'host_node', 'host_cluster',
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
+ HOST_NODE: schema.String(
+ _('The node on which container will be launched.')
+ ),
+ HOST_CLUSTER: schema.String(
+ _('The cluster on which container cluster will be launched.')
+ ),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
|
Add 'host_node' and 'host_cluster' properties to container profile
|
## Code Before:
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
CONTEXT, IMAGE, NAME, COMMAND,
) = (
'context', 'image', 'name', 'command',
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
## Instruction:
Add 'host_node' and 'host_cluster' properties to container profile
## Code After:
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
CONTEXT, IMAGE, NAME, COMMAND, HOST_NODE, HOST_CLUSTER
) = (
'context', 'image', 'name', 'command', 'host_node', 'host_cluster',
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
HOST_NODE: schema.String(
_('The node on which container will be launched.')
),
HOST_CLUSTER: schema.String(
_('The cluster on which container cluster will be launched.')
),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
|
from senlin.common.i18n import _
from senlin.common import schema
from senlin.profiles import base
class DockerProfile(base.Profile):
"""Profile for a docker container."""
KEYS = (
- CONTEXT, IMAGE, NAME, COMMAND,
+ CONTEXT, IMAGE, NAME, COMMAND, HOST_NODE, HOST_CLUSTER
? ++++++++++++++++++++++++
) = (
- 'context', 'image', 'name', 'command',
+ 'context', 'image', 'name', 'command', 'host_node', 'host_cluster',
? +++++++++++++++++++++++++++++
)
properties_schema = {
CONTEXT: schema.Map(
_('Customized security context for operationg containers.')
),
IMAGE: schema.String(
_('The image used to create a container')
),
NAME: schema.String(
_('The name of the container.')
),
COMMAND: schema.String(
_('The command to run when container is started.')
),
+ HOST_NODE: schema.String(
+ _('The node on which container will be launched.')
+ ),
+ HOST_CLUSTER: schema.String(
+ _('The cluster on which container cluster will be launched.')
+ ),
}
def __init__(self, type_name, name, **kwargs):
super(DockerProfile, self).__init__(type_name, name, **kwargs)
self._dockerclient = None
|
9c83b5b064a50b6813bb3819927c9d268f89aaa1
|
ninja/files.py
|
ninja/files.py
|
from typing import Any, Callable, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema, field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
Add missing type hint for field_schema parameter
|
Add missing type hint for field_schema parameter
|
Python
|
mit
|
vitalik/django-ninja,vitalik/django-ninja,vitalik/django-ninja
|
- from typing import Any, Callable, Iterable, Optional, Type
+ from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
- def __modify_schema__(cls, field_schema, field: Optional[ModelField]):
+ def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
Add missing type hint for field_schema parameter
|
## Code Before:
from typing import Any, Callable, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema, field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
## Instruction:
Add missing type hint for field_schema parameter
## Code After:
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
- from typing import Any, Callable, Iterable, Optional, Type
+ from typing import Any, Callable, Dict, Iterable, Optional, Type
? ++++++
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
- def __modify_schema__(cls, field_schema, field: Optional[ModelField]):
+ def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
? ++++++++++++++++
field_schema.update(type="string", format="binary")
|
8541737b5a3a50188162349727a0d0230613e630
|
test/features/test_create_pages.py
|
test/features/test_create_pages.py
|
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending")
assert_that(self.browser.find_by_css('h1').text, is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
assert_that(services, contains_string('654'))
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
|
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/"
"by-transactions-per-year/descending")
assert_that(self.browser.find_by_css('h1').text,
is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
assert_that(services, contains_string('658'))
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
assert_that(self.browser.find_by_css('#navigation .current').text,
is_("All services"))
|
Change services number in test
|
Change services number in test
|
Python
|
mit
|
alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer
|
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
- self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending")
+ self.browser.visit("http://0.0.0.0:8000/high-volume-services/"
+ "by-transactions-per-year/descending")
- assert_that(self.browser.find_by_css('h1').text, is_('High-volume services'))
+ assert_that(self.browser.find_by_css('h1').text,
+ is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
- assert_that(services, contains_string('654'))
+ assert_that(services, contains_string('658'))
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
- assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
+ assert_that(self.browser.find_by_css('#navigation .current').text,
+ is_("All services"))
|
Change services number in test
|
## Code Before:
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending")
assert_that(self.browser.find_by_css('h1').text, is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
assert_that(services, contains_string('654'))
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
## Instruction:
Change services number in test
## Code After:
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
self.browser.visit("http://0.0.0.0:8000/high-volume-services/"
"by-transactions-per-year/descending")
assert_that(self.browser.find_by_css('h1').text,
is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
assert_that(services, contains_string('658'))
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
assert_that(self.browser.find_by_css('#navigation .current').text,
is_("All services"))
|
from hamcrest import *
from nose.tools import nottest
from test.features import BrowserTest
class test_create_pages(BrowserTest):
def test_about_page(self):
- self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending")
? ----------------------------------- -
+ self.browser.visit("http://0.0.0.0:8000/high-volume-services/"
+ "by-transactions-per-year/descending")
- assert_that(self.browser.find_by_css('h1').text, is_('High-volume services'))
? -----------------------------
+ assert_that(self.browser.find_by_css('h1').text,
+ is_('High-volume services'))
def test_home_page(self):
self.browser.visit("http://0.0.0.0:8000/home")
headlines = self.browser.find_by_css('.headline')
departments = headlines[0].text
services = headlines[1].text
transactions = headlines[2].text
assert_that(departments, contains_string('16'))
- assert_that(services, contains_string('654'))
? ^
+ assert_that(services, contains_string('658'))
? ^
assert_that(transactions, contains_string('1.31bn'))
@nottest
def test_all_services(self):
self.browser.visit("http://0.0.0.0:8000/all-services")
assert_that(self.browser.find_by_css('h1').text, is_("All Services"))
- assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
? ---------------------
+ assert_that(self.browser.find_by_css('#navigation .current').text,
+ is_("All services"))
|
dc981dbd1b29d9586453f325f99b1c413c494800
|
account/managers.py
|
account/managers.py
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address = self.create(user=user, email=email, **kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address, __ = self.get_or_create(user=user, email=email, default=kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
Use get_or_create instead of just create
|
Use get_or_create instead of just create
|
Python
|
mit
|
gem/geonode-user-accounts,gem/geonode-user-accounts,gem/geonode-user-accounts
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
- email_address = self.create(user=user, email=email, **kwargs)
+ email_address, __ = self.get_or_create(user=user, email=email, default=kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
Use get_or_create instead of just create
|
## Code Before:
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address = self.create(user=user, email=email, **kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
## Instruction:
Use get_or_create instead of just create
## Code After:
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address, __ = self.get_or_create(user=user, email=email, default=kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
- email_address = self.create(user=user, email=email, **kwargs)
? ^^
+ email_address, __ = self.get_or_create(user=user, email=email, default=kwargs)
? ++++ +++++++ ^^^^^^^^
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
6d25dcdb5eaca6d0d0404b4104017a18076174f8
|
mass/utils.py
|
mass/utils.py
|
# built-in modules
import json
# local modules
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
def submit(job, protocol=None, priority=1):
"""Submit mass job to SWF with specific priority.
"""
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
# built-in modules
import json
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
|
Raise UnsupportedScheduler if specific scheduler for submit is not
supported (Now just swf is supported).
|
Python
|
apache-2.0
|
KKBOX/mass,badboy99tw/mass,KKBOX/mass,badboy99tw/mass,badboy99tw/mass,KKBOX/mass
|
# built-in modules
import json
# local modules
+ from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
- def submit(job, protocol=None, priority=1):
+ def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
+ if scheduler != 'swf':
+ raise UnsupportedScheduler(scheduler)
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
|
## Code Before:
# built-in modules
import json
# local modules
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
def submit(job, protocol=None, priority=1):
"""Submit mass job to SWF with specific priority.
"""
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
## Instruction:
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
## Code After:
# built-in modules
import json
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
# built-in modules
import json
# local modules
+ from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
from mass.scheduler.swf import config
- def submit(job, protocol=None, priority=1):
+ def submit(job, protocol=None, priority=1, scheduler='swf'):
? +++++++++++++++++
"""Submit mass job to SWF with specific priority.
"""
+ if scheduler != 'swf':
+ raise UnsupportedScheduler(scheduler)
import boto3
client = boto3.client('swf', region_name=config.REGION)
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
499add1d29847490141cda4625d9a4199e386283
|
ncdc_download/download_mapper2.py
|
ncdc_download/download_mapper2.py
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
Remove downloaded file before updating counter
|
Remove downloaded file before updating counter
|
Python
|
mit
|
simonbrady/cat,simonbrady/cat
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
+ os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
- os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
Remove downloaded file before updating counter
|
## Code Before:
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
## Instruction:
Remove downloaded file before updating counter
## Code After:
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
+ os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
- os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
198d1d8827ffc04bf7f33e99bc929a33c8a7ba8c
|
src/sana/core/models/__init__.py
|
src/sana/core/models/__init__.py
|
from sana.core.models.concept import Concept, Relationship, RelationshipCategory
from sana.core.models.device import Device
from sana.core.models.encounter import Encounter
from sana.core.models.events import Event
from sana.core.models.notification import Notification
from sana.core.models.observation import Observation
from sana.core.models.observer import Observer
from sana.core.models.procedure import Procedure
from sana.core.models.subject import Subject
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
'Subject',]
|
from .concept import Concept, Relationship, RelationshipCategory
from .device import Device
from .encounter import Encounter
from .events import Event
from .notification import Notification
from .observation import Observation
from .observer import Observer
from .procedure import Procedure
from .subject import Patient
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
'Patient',]
|
Update to use relative imports.
|
Update to use relative imports.
|
Python
|
bsd-3-clause
|
SanaMobile/sana.mds,rryan/sana.mds,SanaMobile/sana.mds,SanaMobile/sana.mds,rryan/sana.mds,SanaMobile/sana.mds
|
- from sana.core.models.concept import Concept, Relationship, RelationshipCategory
+ from .concept import Concept, Relationship, RelationshipCategory
- from sana.core.models.device import Device
+ from .device import Device
- from sana.core.models.encounter import Encounter
+ from .encounter import Encounter
- from sana.core.models.events import Event
+ from .events import Event
- from sana.core.models.notification import Notification
+ from .notification import Notification
- from sana.core.models.observation import Observation
+ from .observation import Observation
- from sana.core.models.observer import Observer
+ from .observer import Observer
- from sana.core.models.procedure import Procedure
+ from .procedure import Procedure
- from sana.core.models.subject import Subject
+ from .subject import Patient
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
- 'Subject',]
+ 'Patient',]
|
Update to use relative imports.
|
## Code Before:
from sana.core.models.concept import Concept, Relationship, RelationshipCategory
from sana.core.models.device import Device
from sana.core.models.encounter import Encounter
from sana.core.models.events import Event
from sana.core.models.notification import Notification
from sana.core.models.observation import Observation
from sana.core.models.observer import Observer
from sana.core.models.procedure import Procedure
from sana.core.models.subject import Subject
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
'Subject',]
## Instruction:
Update to use relative imports.
## Code After:
from .concept import Concept, Relationship, RelationshipCategory
from .device import Device
from .encounter import Encounter
from .events import Event
from .notification import Notification
from .observation import Observation
from .observer import Observer
from .procedure import Procedure
from .subject import Patient
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
'Patient',]
|
- from sana.core.models.concept import Concept, Relationship, RelationshipCategory
? ----------------
+ from .concept import Concept, Relationship, RelationshipCategory
- from sana.core.models.device import Device
? ----------------
+ from .device import Device
- from sana.core.models.encounter import Encounter
? ----------------
+ from .encounter import Encounter
- from sana.core.models.events import Event
? ----------------
+ from .events import Event
- from sana.core.models.notification import Notification
? ----------------
+ from .notification import Notification
- from sana.core.models.observation import Observation
? ----------------
+ from .observation import Observation
- from sana.core.models.observer import Observer
? ----------------
+ from .observer import Observer
- from sana.core.models.procedure import Procedure
? ----------------
+ from .procedure import Procedure
- from sana.core.models.subject import Subject
+ from .subject import Patient
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Notification',
'Observation',
'Observer',
'Procedure',
- 'Subject',]
? ^^^^ ^
+ 'Patient',]
? ^^^^ ^
|
b9fbc9ba6ab2c379e26d6e599fcaaf6ab9b84473
|
server/slack.py
|
server/slack.py
|
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
|
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
Add Slack token validation to handler
|
Add Slack token validation to handler
|
Python
|
mit
|
groppe/mario
|
- import json
import kartlogic.rank
- import logging
import prettytable
- import util.web
- import util.slack
+ import util.web as webutil
+ import util.slack as slackutil
def handler(event, context):
- logging.warning(event['body'])
- logging.warning(json.dumps(util.slack.parse_input(event['body'])))
+ input_data = slackutil.slack.parse_input(event['body'])
+
+ if slackutil.validate_slack_token(input_data) is False:
+ return webutil.respond_unauthorized("Invalid Slack token")
+
- return util.web.respond_success("Successful")
+ return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
- slack_response = util.slack.in_channel_response(table_string)
+ slack_response = slackutil.in_channel_response(table_string)
- return util.web.respond_success_json(slack_response)
+ return webutil.respond_success_json(slack_response)
|
Add Slack token validation to handler
|
## Code Before:
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
## Instruction:
Add Slack token validation to handler
## Code After:
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
- import json
import kartlogic.rank
- import logging
import prettytable
- import util.web
- import util.slack
+ import util.web as webutil
+ import util.slack as slackutil
def handler(event, context):
- logging.warning(event['body'])
- logging.warning(json.dumps(util.slack.parse_input(event['body'])))
+ input_data = slackutil.slack.parse_input(event['body'])
+
+ if slackutil.validate_slack_token(input_data) is False:
+ return webutil.respond_unauthorized("Invalid Slack token")
+
- return util.web.respond_success("Successful")
? ----
+ return webutil.respond_success("Successful")
? +++
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
- slack_response = util.slack.in_channel_response(table_string)
? -----
+ slack_response = slackutil.in_channel_response(table_string)
? ++++
- return util.web.respond_success_json(slack_response)
? ----
+ return webutil.respond_success_json(slack_response)
? +++
|
64086acee22cfc2dde2fec9da1ea1b7745ce3d85
|
tests/misc/test_base_model.py
|
tests/misc/test_base_model.py
|
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project %s>" % self.project.name)
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
Remove useless test about model representation
|
Remove useless test about model representation
|
Python
|
agpl-3.0
|
cgwire/zou
|
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
-
- def test_repr(self):
- self.generate_fixture_project_status()
- self.generate_fixture_project()
- self.assertEqual(str(self.project), "<Project %s>" % self.project.name)
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
Remove useless test about model representation
|
## Code Before:
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project %s>" % self.project.name)
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
## Instruction:
Remove useless test about model representation
## Code After:
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
-
- def test_repr(self):
- self.generate_fixture_project_status()
- self.generate_fixture_project()
- self.assertEqual(str(self.project), "<Project %s>" % self.project.name)
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
91865fc50b66dc261cf05bba21a371e1130b25f5
|
integration-test/605-crosswalk-sidewalk.py
|
integration-test/605-crosswalk-sidewalk.py
|
assert_has_feature(
16, 10471, 25331, 'roads',
{ 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
assert_has_feature(
16, 10475, 25332, 'roads',
{ 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
Update osm way used due to data change
|
Update osm way used due to data change
|
Python
|
mit
|
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
|
assert_has_feature(
- 16, 10471, 25331, 'roads',
+ 16, 10475, 25332, 'roads',
- { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
+ { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
Update osm way used due to data change
|
## Code Before:
assert_has_feature(
16, 10471, 25331, 'roads',
{ 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
## Instruction:
Update osm way used due to data change
## Code After:
assert_has_feature(
16, 10475, 25332, 'roads',
{ 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
assert_has_feature(
- 16, 10471, 25331, 'roads',
? ^ ^
+ 16, 10475, 25332, 'roads',
? ^ ^
- { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
? - ----- ^^^
+ { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
? ++++++ ^ ++++++++++++
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
1af3111e4f2422c1d6484c237700013386d4638d
|
minutes/forms.py
|
minutes/forms.py
|
from django.forms import ModelForm, Textarea, ChoiceField
from django.urls import reverse_lazy
from .models import Meeting, Folder
MD_INPUT = {
'class': 'markdown-input',
'data-endpoint': reverse_lazy('utilities:preview_safe')
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
|
from django.forms import ModelForm, Textarea, ChoiceField
from django.utils.functional import lazy
from .models import Meeting, Folder
MD_INPUT = {
'class': 'markdown-input'
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
|
Revert "Allow admin preview in minutes as well"
|
Revert "Allow admin preview in minutes as well"
This reverts commit f4806655
|
Python
|
isc
|
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
|
from django.forms import ModelForm, Textarea, ChoiceField
- from django.urls import reverse_lazy
+ from django.utils.functional import lazy
from .models import Meeting, Folder
MD_INPUT = {
- 'class': 'markdown-input',
+ 'class': 'markdown-input'
- 'data-endpoint': reverse_lazy('utilities:preview_safe')
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
|
Revert "Allow admin preview in minutes as well"
|
## Code Before:
from django.forms import ModelForm, Textarea, ChoiceField
from django.urls import reverse_lazy
from .models import Meeting, Folder
MD_INPUT = {
'class': 'markdown-input',
'data-endpoint': reverse_lazy('utilities:preview_safe')
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
## Instruction:
Revert "Allow admin preview in minutes as well"
## Code After:
from django.forms import ModelForm, Textarea, ChoiceField
from django.utils.functional import lazy
from .models import Meeting, Folder
MD_INPUT = {
'class': 'markdown-input'
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
|
from django.forms import ModelForm, Textarea, ChoiceField
- from django.urls import reverse_lazy
+ from django.utils.functional import lazy
from .models import Meeting, Folder
MD_INPUT = {
- 'class': 'markdown-input',
? -
+ 'class': 'markdown-input'
- 'data-endpoint': reverse_lazy('utilities:preview_safe')
}
def sorted_folders():
return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1])
class MeetingForm(ModelForm):
folder = ChoiceField(choices=sorted_folders)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Meeting
fields = ['name', 'folder', 'title', 'body', 'date']
widgets = {
'body': Textarea(attrs=MD_INPUT),
}
def clean_folder(self):
return Folder.objects.get(pk=self.cleaned_data['folder'])
|
727f221767c662e95585f54e06c0c8b4e4a77d88
|
smartfile/exceptions.py
|
smartfile/exceptions.py
|
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = '{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
self.detail = response.json.get('detail', 'Check response for errors')
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = u'{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
if not response.json or not 'detail' in response.json:
self.detail = u'Check response for errors'
else:
self.detail = response.json['detail']
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
Handle responses without JSON or detail field
|
Handle responses without JSON or detail field
Check the response for JSON and a detail field before trying to access
them within SmartFileResponseException. This could occur if the server
returns a 500.
|
Python
|
mit
|
smartfile/client-python
|
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
- self.detail = '{0}: {1}'.format(exc.__class__, exc)
+ self.detail = u'{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
- self.detail = response.json.get('detail', 'Check response for errors')
+ if not response.json or not 'detail' in response.json:
+ self.detail = u'Check response for errors'
+ else:
+ self.detail = response.json['detail']
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
Handle responses without JSON or detail field
|
## Code Before:
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = '{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
self.detail = response.json.get('detail', 'Check response for errors')
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
## Instruction:
Handle responses without JSON or detail field
## Code After:
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = u'{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
if not response.json or not 'detail' in response.json:
self.detail = u'Check response for errors'
else:
self.detail = response.json['detail']
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
- self.detail = '{0}: {1}'.format(exc.__class__, exc)
+ self.detail = u'{0}: {1}'.format(exc.__class__, exc)
? +
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
- self.detail = response.json.get('detail', 'Check response for errors')
+ if not response.json or not 'detail' in response.json:
+ self.detail = u'Check response for errors'
+ else:
+ self.detail = response.json['detail']
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
97a1c4979f8c46833b4ac89f6920138551ed2ee6
|
pyuvdata/__init__.py
|
pyuvdata/__init__.py
|
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from .utils import *
from . import version
__version__ = version.version
|
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from .utils import * # consider removing this import
from . import version
__version__ = version.version
|
Add comment about utils import
|
Add comment about utils import
|
Python
|
bsd-2-clause
|
HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata
|
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
- from .utils import *
+ from .utils import * # consider removing this import
from . import version
__version__ = version.version
|
Add comment about utils import
|
## Code Before:
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from .utils import *
from . import version
__version__ = version.version
## Instruction:
Add comment about utils import
## Code After:
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from .utils import * # consider removing this import
from . import version
__version__ = version.version
|
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
- from .utils import *
+ from .utils import * # consider removing this import
from . import version
__version__ = version.version
|
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a
|
deen/main.py
|
deen/main.py
|
import sys
import logging
import pathlib
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
|
import sys
import logging
import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
|
Use os.path instead of pathlib
|
Use os.path instead of pathlib
|
Python
|
apache-2.0
|
takeshixx/deen,takeshixx/deen
|
import sys
import logging
- import pathlib
+ import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
- ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
+ ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
|
Use os.path instead of pathlib
|
## Code Before:
import sys
import logging
import pathlib
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
## Instruction:
Use os.path instead of pathlib
## Code After:
import sys
import logging
import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
|
import sys
import logging
- import pathlib
? ---
+ import os.path
? +++
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
- ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
+ ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
|
5a3935caab0bf720db6707bb7974eec2400f3701
|
prompt_toolkit/key_binding/bindings/auto_suggest.py
|
prompt_toolkit/key_binding/bindings/auto_suggest.py
|
from __future__ import unicode_literals
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return key_bindings
|
from __future__ import unicode_literals
import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition, emacs_mode
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
@handle('escape', 'f', filter=suggestion_available & emacs_mode)
def _(event):
" Fill partial suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
t = re.split(r'(\S+\s+)', suggestion.text)
b.insert_text(next(x for x in t if x))
return key_bindings
|
Add alt-f binding for auto-suggestion.
|
Add alt-f binding for auto-suggestion.
|
Python
|
bsd-3-clause
|
jonathanslenders/python-prompt-toolkit
|
from __future__ import unicode_literals
+ import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
- from prompt_toolkit.filters import Condition
+ from prompt_toolkit.filters import Condition, emacs_mode
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
+ @handle('escape', 'f', filter=suggestion_available & emacs_mode)
+ def _(event):
+ " Fill partial suggestion. "
+ b = event.current_buffer
+ suggestion = b.suggestion
+
+ if suggestion:
+ t = re.split(r'(\S+\s+)', suggestion.text)
+ b.insert_text(next(x for x in t if x))
+
return key_bindings
|
Add alt-f binding for auto-suggestion.
|
## Code Before:
from __future__ import unicode_literals
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return key_bindings
## Instruction:
Add alt-f binding for auto-suggestion.
## Code After:
from __future__ import unicode_literals
import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition, emacs_mode
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
@handle('escape', 'f', filter=suggestion_available & emacs_mode)
def _(event):
" Fill partial suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
t = re.split(r'(\S+\s+)', suggestion.text)
b.insert_text(next(x for x in t if x))
return key_bindings
|
from __future__ import unicode_literals
+ import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
- from prompt_toolkit.filters import Condition
+ from prompt_toolkit.filters import Condition, emacs_mode
? ++++++++++++
__all__ = [
'load_auto_suggest_bindings',
]
def load_auto_suggest_bindings():
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available():
app = get_app()
return (app.current_buffer.suggestion is not None and
app.current_buffer.document.is_cursor_at_the_end)
@handle('c-f', filter=suggestion_available)
@handle('c-e', filter=suggestion_available)
@handle('right', filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
+ @handle('escape', 'f', filter=suggestion_available & emacs_mode)
+ def _(event):
+ " Fill partial suggestion. "
+ b = event.current_buffer
+ suggestion = b.suggestion
+
+ if suggestion:
+ t = re.split(r'(\S+\s+)', suggestion.text)
+ b.insert_text(next(x for x in t if x))
+
return key_bindings
|
b858b2640b8e509c1262644eda02afb05d90ff18
|
project/slacksync/management/commands/sync_slack_users.py
|
project/slacksync/management/commands/sync_slack_users.py
|
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync(autoremove)
tbd = sync.sync_members()
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync()
tbd = sync.sync_members(autoremove)
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
Fix autoremove in wrong place
|
Fix autoremove in wrong place
|
Python
|
mit
|
HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
|
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
- sync = SlackMemberSync(autoremove)
+ sync = SlackMemberSync()
- tbd = sync.sync_members()
+ tbd = sync.sync_members(autoremove)
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
Fix autoremove in wrong place
|
## Code Before:
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync(autoremove)
tbd = sync.sync_members()
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
## Instruction:
Fix autoremove in wrong place
## Code After:
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync()
tbd = sync.sync_members(autoremove)
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
- sync = SlackMemberSync(autoremove)
? ----------
+ sync = SlackMemberSync()
- tbd = sync.sync_members()
+ tbd = sync.sync_members(autoremove)
? ++++++++++
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
62bbc01940e85e6017b4b5d4e757437b05c81f71
|
evaluation_system/reports/views.py
|
evaluation_system/reports/views.py
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
Fix evaluation query on report
|
Fix evaluation query on report
|
Python
|
mit
|
carlosa54/evaluation_system,carlosa54/evaluation_system,carlosa54/evaluation_system
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
- context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
+ context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
Fix evaluation query on report
|
## Code Before:
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
## Instruction:
Fix evaluation query on report
## Code After:
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
- context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
+ context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
? ++++++++++++++++++++++++++++++
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
46e20cb4ac6571b922968674f2127318eef68821
|
common/utilities/throttling.py
|
common/utilities/throttling.py
|
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
if request.user.is_authenticated():
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
else:
return None
|
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
else:
return None
|
Remove is_autheticated check as by default all the endpoints are authenticated
|
Remove is_autheticated check as by default all the endpoints are authenticated
|
Python
|
mit
|
MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api
|
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
-
- if request.user.is_authenticated():
- return self.cache_format % {
+ return self.cache_format % {
- 'scope': self.scope,
+ 'scope': self.scope,
- 'ident': ident
+ 'ident': ident
- }
+ }
else:
return None
|
Remove is_autheticated check as by default all the endpoints are authenticated
|
## Code Before:
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
if request.user.is_authenticated():
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
else:
return None
## Instruction:
Remove is_autheticated check as by default all the endpoints are authenticated
## Code After:
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
else:
return None
|
from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated users.
"""
scope = 'rating'
scope_attr = 'throttle_scope'
def get_cache_key(self, request, view):
"""
Override this method in order to have an ip based cache key
for authenticated users instead of the usual user.pk based cache key.
"""
fs_identity = request.DATA.get('facility_service', None)
if fs_identity:
machine = self.get_ident(request)
ident = machine + fs_identity
-
- if request.user.is_authenticated():
- return self.cache_format % {
? ----
+ return self.cache_format % {
- 'scope': self.scope,
? ----
+ 'scope': self.scope,
- 'ident': ident
? ----
+ 'ident': ident
- }
? ----
+ }
else:
return None
|
8f2ca07286bd0950e17c410fc27297775934ba21
|
vispy/visuals/graphs/layouts/circular.py
|
vispy/visuals/graphs/layouts/circular.py
|
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
Use T attribute to get transpose
|
Use T attribute to get transpose
|
Python
|
bsd-3-clause
|
drufat/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy,Eric89GXL/vispy,Eric89GXL/vispy,ghisvail/vispy,michaelaye/vispy,Eric89GXL/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy
|
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
- node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
+ node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
Use T attribute to get transpose
|
## Code Before:
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
## Instruction:
Use T attribute to get transpose
## Code After:
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
- node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
? ------------
+ node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
? ++
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
|
35f2838d1451681f1cc49fba3b4466389bf2cf68
|
test/test_allocator.py
|
test/test_allocator.py
|
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
|
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
def test_init_values(self):
self.assertNotEqual(ffi.NULL, lib.arenas)
for i in range(lib.qcgc_small_free_lists):
l = lib.small_free_list(i)
self.assertNotEqual(ffi.NULL, l)
for i in range(lib.qcgc_large_free_lists):
l = lib.large_free_list(i)
self.assertNotEqual(ffi.NULL, l)
|
Add testcase for allocator initialization
|
Add testcase for allocator initialization
|
Python
|
mit
|
ntruessel/qcgc,ntruessel/qcgc,ntruessel/qcgc
|
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
+ def test_init_values(self):
+ self.assertNotEqual(ffi.NULL, lib.arenas)
+ for i in range(lib.qcgc_small_free_lists):
+ l = lib.small_free_list(i)
+ self.assertNotEqual(ffi.NULL, l)
+ for i in range(lib.qcgc_large_free_lists):
+ l = lib.large_free_list(i)
+ self.assertNotEqual(ffi.NULL, l)
+
|
Add testcase for allocator initialization
|
## Code Before:
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
## Instruction:
Add testcase for allocator initialization
## Code After:
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
def test_init_values(self):
self.assertNotEqual(ffi.NULL, lib.arenas)
for i in range(lib.qcgc_small_free_lists):
l = lib.small_free_list(i)
self.assertNotEqual(ffi.NULL, l)
for i in range(lib.qcgc_large_free_lists):
l = lib.large_free_list(i)
self.assertNotEqual(ffi.NULL, l)
|
from support import lib,ffi
from qcgc_test import QCGCTest
class AllocatorTest(QCGCTest):
def test_cells_to_bytes(self):
for i in range(1,17):
self.assertEqual(1, lib.bytes_to_cells(i))
self.assertEqual(2, lib.bytes_to_cells(17))
+
+ def test_init_values(self):
+ self.assertNotEqual(ffi.NULL, lib.arenas)
+ for i in range(lib.qcgc_small_free_lists):
+ l = lib.small_free_list(i)
+ self.assertNotEqual(ffi.NULL, l)
+ for i in range(lib.qcgc_large_free_lists):
+ l = lib.large_free_list(i)
+ self.assertNotEqual(ffi.NULL, l)
|
f4c989567fa77002541c5e5199f2fc3f8e53d6da
|
test_htmlgen/image.py
|
test_htmlgen/image.py
|
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image._attributes["src"])
assert_equal("Alternate text", image._attributes["alt"])
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image._attributes["src"])
assert_equal("", image._attributes["alt"])
|
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image.get_attribute("src"))
assert_equal("Alternate text", image.get_attribute("alt"))
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image.get_attribute("src"))
assert_equal("", image.get_attribute("alt"))
|
Use public API in tests
|
[tests] Use public API in tests
|
Python
|
mit
|
srittau/python-htmlgen
|
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
- assert_equal("my-image.png", image._attributes["src"])
+ assert_equal("my-image.png", image.get_attribute("src"))
- assert_equal("Alternate text", image._attributes["alt"])
+ assert_equal("Alternate text", image.get_attribute("alt"))
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
- assert_equal("my-image.png", image._attributes["src"])
+ assert_equal("my-image.png", image.get_attribute("src"))
- assert_equal("", image._attributes["alt"])
+ assert_equal("", image.get_attribute("alt"))
|
Use public API in tests
|
## Code Before:
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image._attributes["src"])
assert_equal("Alternate text", image._attributes["alt"])
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image._attributes["src"])
assert_equal("", image._attributes["alt"])
## Instruction:
Use public API in tests
## Code After:
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image.get_attribute("src"))
assert_equal("Alternate text", image.get_attribute("alt"))
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
assert_equal("my-image.png", image.get_attribute("src"))
assert_equal("", image.get_attribute("alt"))
|
from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_equal("Alternate text", image.alternate_text)
def test_attributes_default_alt(self):
image = Image("my-image.png")
assert_equal("", image.alternate_text)
def test_with_alt(self):
image = Image("my-image.png", "Alternate text")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
- assert_equal("my-image.png", image._attributes["src"])
? ^^ -
+ assert_equal("my-image.png", image.get_attribute("src"))
? +++ ^ +
- assert_equal("Alternate text", image._attributes["alt"])
? ^^ -
+ assert_equal("Alternate text", image.get_attribute("alt"))
? +++ ^ +
def test_without_alt(self):
image = Image("my-image.png")
tag = parse_short_tag(str(image))
assert_equal("img", tag.name)
- assert_equal("my-image.png", image._attributes["src"])
? ^^ -
+ assert_equal("my-image.png", image.get_attribute("src"))
? +++ ^ +
- assert_equal("", image._attributes["alt"])
? ^^ -
+ assert_equal("", image.get_attribute("alt"))
? +++ ^ +
|
0e807b46ba044e1accb8fb767f6f2ed4ffb2d0ba
|
dataportal/tests/test_broker.py
|
dataportal/tests/test_broker.py
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..examples.sample_data import temperature_ramp
from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=True, filestore=True)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
temperature_ramp.run()
def test_basic_usage(self):
header = db[-1]
events = db.fetch_events(header)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
Add coverage for basic broker usage.
|
TST: Add coverage for basic broker usage.
|
Python
|
bsd-3-clause
|
danielballan/dataportal,ericdill/datamuxer,danielballan/dataportal,NSLS-II/dataportal,NSLS-II/datamuxer,ericdill/datamuxer,tacaswell/dataportal,ericdill/databroker,danielballan/datamuxer,tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,ericdill/databroker
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
+ from ..examples.sample_data import temperature_ramp
+ from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
- switch(channelarchiver=False, metadatastore=False, filestore=False)
+ switch(channelarchiver=False, metadatastore=True, filestore=True)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
+ temperature_ramp.run()
+
+ def test_basic_usage(self):
+ header = db[-1]
+ events = db.fetch_events(header)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
Add coverage for basic broker usage.
|
## Code Before:
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
## Instruction:
Add coverage for basic broker usage.
## Code After:
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..examples.sample_data import temperature_ramp
from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=True, filestore=True)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
temperature_ramp.run()
def test_basic_usage(self):
header = db[-1]
events = db.fetch_events(header)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
+ from ..examples.sample_data import temperature_ramp
+ from ..broker import DataBroker as db
class TestBroker(unittest.TestCase):
def setUp(self):
- switch(channelarchiver=False, metadatastore=False, filestore=False)
? ^^^^ ^^^^
+ switch(channelarchiver=False, metadatastore=True, filestore=True)
? ^^^ ^^^
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
+ temperature_ramp.run()
+
+ def test_basic_usage(self):
+ header = db[-1]
+ events = db.fetch_events(header)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
4f8a84171bdbe24701351a54230768069a5f27fc
|
deployments/prob140/image/ipython_config.py
|
deployments/prob140/image/ipython_config.py
|
c.Historymanager.enabled = False
|
c.Historymanager.enabled = False
# Use memory for notebook notary file to workaround corrupted files on nfs
# https://www.sqlite.org/inmemorydb.html
# https://github.com/jupyter/jupyter/issues/174
# https://github.com/ipython/ipython/issues/9163
c.NotebookNotary.db_file = ":memory:"
|
Use memory for notebook notary file.
|
Use memory for notebook notary file.
Workaround possible file integrity issues.
|
Python
|
bsd-3-clause
|
ryanlovett/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub,ryanlovett/datahub
|
c.Historymanager.enabled = False
+ # Use memory for notebook notary file to workaround corrupted files on nfs
+ # https://www.sqlite.org/inmemorydb.html
+ # https://github.com/jupyter/jupyter/issues/174
+ # https://github.com/ipython/ipython/issues/9163
+ c.NotebookNotary.db_file = ":memory:"
+
|
Use memory for notebook notary file.
|
## Code Before:
c.Historymanager.enabled = False
## Instruction:
Use memory for notebook notary file.
## Code After:
c.Historymanager.enabled = False
# Use memory for notebook notary file to workaround corrupted files on nfs
# https://www.sqlite.org/inmemorydb.html
# https://github.com/jupyter/jupyter/issues/174
# https://github.com/ipython/ipython/issues/9163
c.NotebookNotary.db_file = ":memory:"
|
c.Historymanager.enabled = False
+
+ # Use memory for notebook notary file to workaround corrupted files on nfs
+ # https://www.sqlite.org/inmemorydb.html
+ # https://github.com/jupyter/jupyter/issues/174
+ # https://github.com/ipython/ipython/issues/9163
+ c.NotebookNotary.db_file = ":memory:"
|
334e794be7514c032e6db4c39761d67820c405ff
|
oscar/management/commands/oscar_update_product_ratings.py
|
oscar/management/commands/oscar_update_product_ratings.py
|
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
ProductReview = get_model('reviews', 'ProductReview')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
ProductReview.update_product_rating(product)
self.stdout.write('Successfully updated %s products\n'
% products.count())
|
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
product.update_rating()
self.stdout.write(
'Successfully updated %s products\n' % products.count())
|
Fix bug in management command for updating ratings
|
Fix bug in management command for updating ratings
|
Python
|
bsd-3-clause
|
kapt/django-oscar,pasqualguerrero/django-oscar,jmt4/django-oscar,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,dongguangming/django-oscar,nickpack/django-oscar,WillisXChen/django-oscar,jmt4/django-oscar,manevant/django-oscar,jinnykoo/wuyisj,eddiep1101/django-oscar,pdonadeo/django-oscar,taedori81/django-oscar,mexeniz/django-oscar,ka7eh/django-oscar,jinnykoo/wuyisj.com,QLGu/django-oscar,amirrpp/django-oscar,anentropic/django-oscar,okfish/django-oscar,bnprk/django-oscar,marcoantoniooliveira/labweb,michaelkuty/django-oscar,Bogh/django-oscar,makielab/django-oscar,adamend/django-oscar,bschuon/django-oscar,bschuon/django-oscar,faratro/django-oscar,manevant/django-oscar,thechampanurag/django-oscar,pdonadeo/django-oscar,manevant/django-oscar,jinnykoo/christmas,Idematica/django-oscar,itbabu/django-oscar,faratro/django-oscar,john-parton/django-oscar,Jannes123/django-oscar,thechampanurag/django-oscar,mexeniz/django-oscar,mexeniz/django-oscar,ademuk/django-oscar,taedori81/django-oscar,ahmetdaglarbas/e-commerce,nickpack/django-oscar,john-parton/django-oscar,kapari/django-oscar,nickpack/django-oscar,pasqualguerrero/django-oscar,taedori81/django-oscar,solarissmoke/django-oscar,jinnykoo/christmas,spartonia/django-oscar,adamend/django-oscar,dongguangming/django-oscar,solarissmoke/django-oscar,josesanch/django-oscar,WadeYuChen/django-oscar,ademuk/django-oscar,monikasulik/django-oscar,monikasulik/django-oscar,dongguangming/django-oscar,pasqualguerrero/django-oscar,faratro/django-oscar,WillisXChen/django-oscar,ademuk/django-oscar,sonofatailor/django-oscar,WillisXChen/django-oscar,jinnykoo/christmas,marcoantoniooliveira/labweb,amirrpp/django-oscar,ka7eh/django-oscar,QLGu/django-oscar,QLGu/django-oscar,vovanbo/django-oscar,thechampanurag/django-oscar,Idematica/django-oscar,rocopartners/django-oscar,eddiep1101/django-oscar,jinnykoo/wuyisj.com,nickpack/django-oscar,vovanbo/django-oscar,jlmadurga/django-oscar,elliotthill/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,WillisXChen/django-oscar,jlmadurga/django-oscar,jlmadurga/django-oscar,makielab/django-oscar,DrOctogon/unwash_ecom,Bogh/django-oscar,WadeYuChen/django-oscar,saadatqadri/django-oscar,ka7eh/django-oscar,itbabu/django-oscar,eddiep1101/django-oscar,adamend/django-oscar,jinnykoo/wuyisj.com,rocopartners/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,adamend/django-oscar,machtfit/django-oscar,django-oscar/django-oscar,spartonia/django-oscar,MatthewWilkes/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,faratro/django-oscar,DrOctogon/unwash_ecom,jinnykoo/wuyisj,amirrpp/django-oscar,Jannes123/django-oscar,manevant/django-oscar,eddiep1101/django-oscar,mexeniz/django-oscar,saadatqadri/django-oscar,kapt/django-oscar,spartonia/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,Bogh/django-oscar,MatthewWilkes/django-oscar,jmt4/django-oscar,MatthewWilkes/django-oscar,michaelkuty/django-oscar,ahmetdaglarbas/e-commerce,okfish/django-oscar,ahmetdaglarbas/e-commerce,thechampanurag/django-oscar,elliotthill/django-oscar,elliotthill/django-oscar,monikasulik/django-oscar,jinnykoo/wuyisj.com,django-oscar/django-oscar,michaelkuty/django-oscar,kapari/django-oscar,marcoantoniooliveira/labweb,MatthewWilkes/django-oscar,WadeYuChen/django-oscar,django-oscar/django-oscar,lijoantony/django-oscar,okfish/django-oscar,monikasulik/django-oscar,lijoantony/django-oscar,ka7eh/django-oscar,solarissmoke/django-oscar,sonofatailor/django-oscar,pasqualguerrero/django-oscar,spartonia/django-oscar,Idematica/django-oscar,binarydud/django-oscar,binarydud/django-oscar,jmt4/django-oscar,machtfit/django-oscar,sasha0/django-oscar,vovanbo/django-oscar,pdonadeo/django-oscar,Jannes123/django-oscar,rocopartners/django-oscar,okfish/django-oscar,anentropic/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,jinnykoo/wuyisj,anentropic/django-oscar,nfletton/django-oscar,bnprk/django-oscar,saadatqadri/django-oscar,john-parton/django-oscar,Jannes123/django-oscar,john-parton/django-oscar,michaelkuty/django-oscar,sasha0/django-oscar,vovanbo/django-oscar,makielab/django-oscar,kapari/django-oscar,jinnykoo/wuyisj,nfletton/django-oscar,bnprk/django-oscar,QLGu/django-oscar,josesanch/django-oscar,bschuon/django-oscar,nfletton/django-oscar,dongguangming/django-oscar,saadatqadri/django-oscar,itbabu/django-oscar,lijoantony/django-oscar,kapari/django-oscar,kapt/django-oscar,Bogh/django-oscar,bnprk/django-oscar,sasha0/django-oscar,bschuon/django-oscar,amirrpp/django-oscar,ademuk/django-oscar,josesanch/django-oscar,makielab/django-oscar,sasha0/django-oscar,machtfit/django-oscar,WadeYuChen/django-oscar,binarydud/django-oscar,binarydud/django-oscar,WillisXChen/django-oscar,taedori81/django-oscar,marcoantoniooliveira/labweb,itbabu/django-oscar,pdonadeo/django-oscar
|
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
- ProductReview = get_model('reviews', 'ProductReview')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
- ProductReview.update_product_rating(product)
- self.stdout.write('Successfully updated %s products\n'
- % products.count())
+ product.update_rating()
+ self.stdout.write(
+ 'Successfully updated %s products\n' % products.count())
|
Fix bug in management command for updating ratings
|
## Code Before:
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
ProductReview = get_model('reviews', 'ProductReview')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
ProductReview.update_product_rating(product)
self.stdout.write('Successfully updated %s products\n'
% products.count())
## Instruction:
Fix bug in management command for updating ratings
## Code After:
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
product.update_rating()
self.stdout.write(
'Successfully updated %s products\n' % products.count())
|
from django.core.management.base import BaseCommand
from django.db.models import get_model
Product = get_model('catalogue', 'Product')
- ProductReview = get_model('reviews', 'ProductReview')
class Command(BaseCommand):
help = """Update the denormalised reviews average on all Product instances.
Should only be necessary when changing to e.g. a weight-based
rating."""
def handle(self, *args, **options):
# Iterate over all Products (not just ones with reviews)
products = Product.objects.all()
for product in products:
- ProductReview.update_product_rating(product)
- self.stdout.write('Successfully updated %s products\n'
- % products.count())
+ product.update_rating()
+ self.stdout.write(
+ 'Successfully updated %s products\n' % products.count())
|
b30d02bd077f1b7785c41e567aa4c4b44bba6a29
|
backend/unimeet/mail/__init__.py
|
backend/unimeet/mail/__init__.py
|
__all__ = ['mail']
from .mail import send_mail, SUBJECTS
|
__all__ = ['mail']
from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
|
Add send_contact_{form,response} functions to mail init
|
Add send_contact_{form,response} functions to mail init
|
Python
|
mit
|
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
|
__all__ = ['mail']
- from .mail import send_mail, SUBJECTS
+ from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
|
Add send_contact_{form,response} functions to mail init
|
## Code Before:
__all__ = ['mail']
from .mail import send_mail, SUBJECTS
## Instruction:
Add send_contact_{form,response} functions to mail init
## Code After:
__all__ = ['mail']
from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
|
__all__ = ['mail']
- from .mail import send_mail, SUBJECTS
+ from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
|
77fac3732f1baae9f3c3be7b38f8837459fee163
|
src/markdown/makrdown.py
|
src/markdown/makrdown.py
|
from markdown import markdown
from markdown.extensions.tables import TableExtension
from .my_codehilite import CodeHiliteExtension
from .my_fenced_code import FencedCodeExtension
from .my_headerid import HeaderIdExtension
def customized_markdown(text):
return markdown(text, extensions=[FencedCodeExtension(),
CodeHiliteExtension(css_class="code", guess_lang=False),
HeaderIdExtension(),
TableExtension()])
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
return customized_markdown(template.render(template_context))
|
import subprocess
from xml.etree import ElementTree
import pygments
from bs4 import BeautifulSoup
from pygments.formatters import get_formatter_by_name
from pygments.lexers import get_lexer_by_name
def customized_markdown(text):
kramdown = subprocess.Popen(
["kramdown",
"--input", "GFM",
"--no-hard-wrap",
"--smart-quotes", "apos,apos,quot,quot",
"--no-enable-coderay"
], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8"))
return stdout_data.decode("utf8")
def highlight_code(text):
tree = BeautifulSoup(text, 'html.parser')
code_elements = tree.select('pre > code')
for element in code_elements:
class_names = element.get("class")
lang = None
if class_names is not None:
for class_name in class_names:
if class_name.startswith("language-"):
lang = class_name[len("language-"):]
if lang is not None:
lexer = get_lexer_by_name(lang)
formatter = get_formatter_by_name('html',
# linenos=self.linenums,
cssclass="code _highlighted",
# style=self.style,
# noclasses=self.noclasses,
# hl_lines=self.hl_lines
)
highlighted = pygments.highlight(element.text, lexer, formatter)
element.parent.replaceWith(BeautifulSoup(highlighted))
return unicode(str(tree.prettify(encoding="utf8")), "utf8")
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
page_html = customized_markdown(template.render(template_context))
return highlight_code(page_html)
|
Use kramdown for markdown convertion.
|
Use kramdown for markdown convertion.
|
Python
|
apache-2.0
|
belovrv/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,madvirus/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,meilalina/kotlin-web-site,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,madvirus/kotlin-web-site,belovrv/kotlin-web-site,TeamKotl/kotlin-web-site,meilalina/kotlin-web-site,voddan/kotlin-web-site,hltj/kotlin-web-site-cn,voddan/kotlin-web-site,JetBrains/kotlin-web-site,belovrv/kotlin-web-site,madvirus/kotlin-web-site,TeamKotl/kotlin-web-site,JetBrains/kotlin-web-site,voddan/kotlin-web-site,TeamKotl/kotlin-web-site,meilalina/kotlin-web-site
|
- from markdown import markdown
- from markdown.extensions.tables import TableExtension
+ import subprocess
+ from xml.etree import ElementTree
- from .my_codehilite import CodeHiliteExtension
- from .my_fenced_code import FencedCodeExtension
- from .my_headerid import HeaderIdExtension
+ import pygments
+ from bs4 import BeautifulSoup
+ from pygments.formatters import get_formatter_by_name
+ from pygments.lexers import get_lexer_by_name
def customized_markdown(text):
- return markdown(text, extensions=[FencedCodeExtension(),
- CodeHiliteExtension(css_class="code", guess_lang=False),
- HeaderIdExtension(),
+ kramdown = subprocess.Popen(
+ ["kramdown",
+ "--input", "GFM",
+ "--no-hard-wrap",
+ "--smart-quotes", "apos,apos,quot,quot",
+ "--no-enable-coderay"
+ ], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8"))
+ return stdout_data.decode("utf8")
+
+
+ def highlight_code(text):
+ tree = BeautifulSoup(text, 'html.parser')
+ code_elements = tree.select('pre > code')
+ for element in code_elements:
+ class_names = element.get("class")
+ lang = None
+ if class_names is not None:
+ for class_name in class_names:
+ if class_name.startswith("language-"):
+ lang = class_name[len("language-"):]
+ if lang is not None:
+ lexer = get_lexer_by_name(lang)
+ formatter = get_formatter_by_name('html',
+ # linenos=self.linenums,
+ cssclass="code _highlighted",
+ # style=self.style,
+ # noclasses=self.noclasses,
+ # hl_lines=self.hl_lines
- TableExtension()])
+ )
+ highlighted = pygments.highlight(element.text, lexer, formatter)
+ element.parent.replaceWith(BeautifulSoup(highlighted))
+ return unicode(str(tree.prettify(encoding="utf8")), "utf8")
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
- return customized_markdown(template.render(template_context))
+ page_html = customized_markdown(template.render(template_context))
+ return highlight_code(page_html)
|
Use kramdown for markdown convertion.
|
## Code Before:
from markdown import markdown
from markdown.extensions.tables import TableExtension
from .my_codehilite import CodeHiliteExtension
from .my_fenced_code import FencedCodeExtension
from .my_headerid import HeaderIdExtension
def customized_markdown(text):
return markdown(text, extensions=[FencedCodeExtension(),
CodeHiliteExtension(css_class="code", guess_lang=False),
HeaderIdExtension(),
TableExtension()])
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
return customized_markdown(template.render(template_context))
## Instruction:
Use kramdown for markdown convertion.
## Code After:
import subprocess
from xml.etree import ElementTree
import pygments
from bs4 import BeautifulSoup
from pygments.formatters import get_formatter_by_name
from pygments.lexers import get_lexer_by_name
def customized_markdown(text):
kramdown = subprocess.Popen(
["kramdown",
"--input", "GFM",
"--no-hard-wrap",
"--smart-quotes", "apos,apos,quot,quot",
"--no-enable-coderay"
], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8"))
return stdout_data.decode("utf8")
def highlight_code(text):
tree = BeautifulSoup(text, 'html.parser')
code_elements = tree.select('pre > code')
for element in code_elements:
class_names = element.get("class")
lang = None
if class_names is not None:
for class_name in class_names:
if class_name.startswith("language-"):
lang = class_name[len("language-"):]
if lang is not None:
lexer = get_lexer_by_name(lang)
formatter = get_formatter_by_name('html',
# linenos=self.linenums,
cssclass="code _highlighted",
# style=self.style,
# noclasses=self.noclasses,
# hl_lines=self.hl_lines
)
highlighted = pygments.highlight(element.text, lexer, formatter)
element.parent.replaceWith(BeautifulSoup(highlighted))
return unicode(str(tree.prettify(encoding="utf8")), "utf8")
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
page_html = customized_markdown(template.render(template_context))
return highlight_code(page_html)
|
- from markdown import markdown
- from markdown.extensions.tables import TableExtension
+ import subprocess
+ from xml.etree import ElementTree
- from .my_codehilite import CodeHiliteExtension
- from .my_fenced_code import FencedCodeExtension
- from .my_headerid import HeaderIdExtension
+ import pygments
+ from bs4 import BeautifulSoup
+ from pygments.formatters import get_formatter_by_name
+ from pygments.lexers import get_lexer_by_name
def customized_markdown(text):
- return markdown(text, extensions=[FencedCodeExtension(),
- CodeHiliteExtension(css_class="code", guess_lang=False),
- HeaderIdExtension(),
+ kramdown = subprocess.Popen(
+ ["kramdown",
+ "--input", "GFM",
+ "--no-hard-wrap",
+ "--smart-quotes", "apos,apos,quot,quot",
+ "--no-enable-coderay"
+ ], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8"))
+ return stdout_data.decode("utf8")
+
+
+ def highlight_code(text):
+ tree = BeautifulSoup(text, 'html.parser')
+ code_elements = tree.select('pre > code')
+ for element in code_elements:
+ class_names = element.get("class")
+ lang = None
+ if class_names is not None:
+ for class_name in class_names:
+ if class_name.startswith("language-"):
+ lang = class_name[len("language-"):]
+ if lang is not None:
+ lexer = get_lexer_by_name(lang)
+ formatter = get_formatter_by_name('html',
+ # linenos=self.linenums,
+ cssclass="code _highlighted",
+ # style=self.style,
+ # noclasses=self.noclasses,
+ # hl_lines=self.hl_lines
- TableExtension()])
? ^^^^^^^^^^^^^^^ --
+ )
? ^^^^^^^^
+ highlighted = pygments.highlight(element.text, lexer, formatter)
+ element.parent.replaceWith(BeautifulSoup(highlighted))
+ return unicode(str(tree.prettify(encoding="utf8")), "utf8")
def jinja_aware_markdown(text, flatPages):
app = flatPages.app
template_context = {}
app.update_template_context(template_context)
env = app.jinja_env
template = env.from_string(text)
- return customized_markdown(template.render(template_context))
? ^ ^^^
+ page_html = customized_markdown(template.render(template_context))
? ^^^ ++ ^^^^
+ return highlight_code(page_html)
|
61427695c0abb3c9385610a13c78cb21eec388d3
|
moa/factory_registers.py
|
moa/factory_registers.py
|
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
|
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('DigitalGateStage', module='moa.stage.gate')
r('AnalogGateStage', module='moa.stage.gate')
|
Update factory registers with new classes.
|
Update factory registers with new classes.
|
Python
|
mit
|
matham/moa
|
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
+ r('DigitalGateStage', module='moa.stage.gate')
+ r('AnalogGateStage', module='moa.stage.gate')
|
Update factory registers with new classes.
|
## Code Before:
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
## Instruction:
Update factory registers with new classes.
## Code After:
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('DigitalGateStage', module='moa.stage.gate')
r('AnalogGateStage', module='moa.stage.gate')
|
from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('DigitalPort', module='moa.device.digital')
r('ButtonChannel', module='moa.device.digital')
r('ButtonPort', module='moa.device.digital')
r('AnalogChannel', module='moa.device.analog')
r('AnalogPort', module='moa.device.analog')
r('NumericPropertyChannel', module='moa.device.analog')
r('NumericPropertyPort', module='moa.device.analog')
# ---------------------- stages --------------------------------
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
+ r('DigitalGateStage', module='moa.stage.gate')
+ r('AnalogGateStage', module='moa.stage.gate')
|
ff5eccb59efd09cfdeb64150440de35215e1b77d
|
gevent_tasks/utils.py
|
gevent_tasks/utils.py
|
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
# type: (int) -> str
""" Generate a random ID of a given length. """
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
|
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
""" Generate a random ID of a given length.
Args:
length (int): length of the returned string.
Returns:
`str` of length ``length``.
Example::
>>> gen_uuid()
aB6z
>>> gen_uuid(10)
aAzZ0123mN
>>> gen_uuid(None)
9
"""
if not length or length < 1:
length = 1
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
|
Fix `gen_uuid` logic and documentation
|
Fix `gen_uuid` logic and documentation
|
Python
|
mit
|
blakev/gevent-tasks
|
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
- # type: (int) -> str
- """ Generate a random ID of a given length. """
+ """ Generate a random ID of a given length.
+
+ Args:
+ length (int): length of the returned string.
+
+ Returns:
+ `str` of length ``length``.
+
+ Example::
+
+ >>> gen_uuid()
+ aB6z
+ >>> gen_uuid(10)
+ aAzZ0123mN
+ >>> gen_uuid(None)
+ 9
+ """
+ if not length or length < 1:
+ length = 1
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
|
Fix `gen_uuid` logic and documentation
|
## Code Before:
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
# type: (int) -> str
""" Generate a random ID of a given length. """
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
## Instruction:
Fix `gen_uuid` logic and documentation
## Code After:
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
""" Generate a random ID of a given length.
Args:
length (int): length of the returned string.
Returns:
`str` of length ``length``.
Example::
>>> gen_uuid()
aB6z
>>> gen_uuid(10)
aAzZ0123mN
>>> gen_uuid(None)
9
"""
if not length or length < 1:
length = 1
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
|
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
- # type: (int) -> str
- """ Generate a random ID of a given length. """
? ----
+ """ Generate a random ID of a given length.
+
+ Args:
+ length (int): length of the returned string.
+
+ Returns:
+ `str` of length ``length``.
+
+ Example::
+
+ >>> gen_uuid()
+ aB6z
+ >>> gen_uuid(10)
+ aAzZ0123mN
+ >>> gen_uuid(None)
+ 9
+ """
+ if not length or length < 1:
+ length = 1
return ''.join(map(lambda c: random.choice(ch_choices), range(length)))
|
3a312dc4134d28d8c8fb0020444a1bbf1277a4cb
|
lib/automatic_timestamps/models.py
|
lib/automatic_timestamps/models.py
|
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
def save(self):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
|
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
|
Add *args/**kwargs to save() as per the Django docs
|
Add *args/**kwargs to save() as per the Django docs
|
Python
|
mit
|
tofumatt/quotes,tofumatt/quotes
|
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
- def save(self):
+ def save(self, *args, **kwargs):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
|
Add *args/**kwargs to save() as per the Django docs
|
## Code Before:
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
def save(self):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
## Instruction:
Add *args/**kwargs to save() as per the Django docs
## Code After:
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
|
from django.db import models
import datetime
class TimestampModel(models.Model):
"""
Extend the default Django model to add timestamps to all objects.
"""
class Meta:
abstract = True
# Timestamps!
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
- def save(self):
+ def save(self, *args, **kwargs):
"""
Override the save method to automatically set the created_at and
updated_at fields with current date info.
"""
if self.created_at == None:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
super(TimestampModel, self).save()
|
7980c2e38d388ec78fd94ee13272934988dfa0f7
|
swingtime/__init__.py
|
swingtime/__init__.py
|
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
verbose_name = 'Calendar Configuration'
default_app_config = 'swingtime.SwingtimeAppConfig'
|
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
_zero_width_space = u'\u200B' # used to make it last alphabetically, better option: http://stackoverflow.com/questions/398163/ordering-admin-modeladmin-objects-in-django-admin
verbose_name = _zero_width_space + 'Calendar Configuration'
default_app_config = 'swingtime.SwingtimeAppConfig'
|
Make calendar config show up at bottom of main admin
|
Make calendar config show up at bottom of main admin
|
Python
|
mit
|
thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee
|
+
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
+ _zero_width_space = u'\u200B' # used to make it last alphabetically, better option: http://stackoverflow.com/questions/398163/ordering-admin-modeladmin-objects-in-django-admin
- verbose_name = 'Calendar Configuration'
+ verbose_name = _zero_width_space + 'Calendar Configuration'
default_app_config = 'swingtime.SwingtimeAppConfig'
|
Make calendar config show up at bottom of main admin
|
## Code Before:
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
verbose_name = 'Calendar Configuration'
default_app_config = 'swingtime.SwingtimeAppConfig'
## Instruction:
Make calendar config show up at bottom of main admin
## Code After:
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
_zero_width_space = u'\u200B' # used to make it last alphabetically, better option: http://stackoverflow.com/questions/398163/ordering-admin-modeladmin-objects-in-django-admin
verbose_name = _zero_width_space + 'Calendar Configuration'
default_app_config = 'swingtime.SwingtimeAppConfig'
|
+
from django.apps import AppConfig
VERSION = (0, 3, 0, 'beta', 0)
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])
return version
class SwingtimeAppConfig(AppConfig):
name = 'swingtime'
+ _zero_width_space = u'\u200B' # used to make it last alphabetically, better option: http://stackoverflow.com/questions/398163/ordering-admin-modeladmin-objects-in-django-admin
- verbose_name = 'Calendar Configuration'
+ verbose_name = _zero_width_space + 'Calendar Configuration'
? ++++++++++++++++++++
default_app_config = 'swingtime.SwingtimeAppConfig'
|
0f9cb6eb32ce014cb6ae8d24aefed2347efe68d9
|
src/python/cargo/condor/host.py
|
src/python/cargo/condor/host.py
|
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
job = pickle.load(sys.stdin)
job.run()
if __name__ == "__main__":
main()
|
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
with open("job.pickle") as job_file:
job = pickle.load(job_file)
job.run()
if __name__ == "__main__":
main()
|
Load job from a job file instead of stdin.
|
Load job from a job file instead of stdin.
|
Python
|
mit
|
borg-project/cargo,borg-project/cargo
|
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
- job = pickle.load(sys.stdin)
+ with open("job.pickle") as job_file:
+ job = pickle.load(job_file)
job.run()
if __name__ == "__main__":
main()
|
Load job from a job file instead of stdin.
|
## Code Before:
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
job = pickle.load(sys.stdin)
job.run()
if __name__ == "__main__":
main()
## Instruction:
Load job from a job file instead of stdin.
## Code After:
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
with open("job.pickle") as job_file:
job = pickle.load(job_file)
job.run()
if __name__ == "__main__":
main()
|
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_number = int(os.environ["CONDOR_CLUSTER"])
identifier_path = "JOB_IS_%i.%i" % (cluster_number, process_number)
open(identifier_path, "w").close()
# load and run the job
- job = pickle.load(sys.stdin)
+ with open("job.pickle") as job_file:
+ job = pickle.load(job_file)
job.run()
if __name__ == "__main__":
main()
|
d02e021a68333c52adff38cc869bf217deebfc5c
|
run.py
|
run.py
|
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
|
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# We only use pygame for drawing, and mixer will hog cpu otherwise
# https://github.com/pygame/pygame/issues/331
pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
|
Fix pygame mixer init hogging cpu
|
Fix pygame mixer init hogging cpu
|
Python
|
mit
|
kenanbit/loopsichord
|
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
+
+ # We only use pygame for drawing, and mixer will hog cpu otherwise
+ # https://github.com/pygame/pygame/issues/331
+ pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
|
Fix pygame mixer init hogging cpu
|
## Code Before:
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
## Instruction:
Fix pygame mixer init hogging cpu
## Code After:
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# We only use pygame for drawing, and mixer will hog cpu otherwise
# https://github.com/pygame/pygame/issues/331
pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
|
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
+
+ # We only use pygame for drawing, and mixer will hog cpu otherwise
+ # https://github.com/pygame/pygame/issues/331
+ pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
|
e00ad93c1a769a920c7f61eeccec582272766b26
|
badgify/templatetags/badgify_tags.py
|
badgify/templatetags/badgify_tags.py
|
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user)
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
|
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
|
Add missing select_related to badgify_badges
|
Add missing select_related to badgify_badges
|
Python
|
mit
|
ulule/django-badgify,ulule/django-badgify
|
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
- awards = Award.objects.filter(user=user)
+ awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
|
Add missing select_related to badgify_badges
|
## Code Before:
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user)
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
## Instruction:
Add missing select_related to badgify_badges
## Code After:
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
|
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
- awards = Award.objects.filter(user=user)
+ awards = Award.objects.filter(user=user).select_related('badge')
? ++++++++++++++++++++++++
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
|
d43a08706f3072a0b97d01526ffd0de0d4a4110c
|
niworkflows/conftest.py
|
niworkflows/conftest.py
|
"""py.test configuration"""
import os
from pathlib import Path
import numpy
import pytest
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace['np'] = numpy
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
@pytest.fixture
def testdata_dir():
return data_dir
|
"""py.test configuration"""
import os
from pathlib import Path
import numpy as np
import nibabel as nb
import pytest
import tempfile
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace['np'] = np
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
tmpdir = tempfile.TemporaryDirectory()
nifti_fname = str(Path(tmpdir.name) / 'test.nii.gz')
nb.Nifti1Image(np.random.random((5, 5)).astype('f4'), np.eye(4)).to_filename(nifti_fname)
doctest_namespace['nifti_fname'] = nifti_fname
yield
tmpdir.cleanup()
@pytest.fixture
def testdata_dir():
return data_dir
|
Make nifti_fname available to doctests
|
DOCTEST: Make nifti_fname available to doctests
|
Python
|
apache-2.0
|
oesteban/niworkflows,oesteban/niworkflows,poldracklab/niworkflows,oesteban/niworkflows,poldracklab/niworkflows
|
"""py.test configuration"""
import os
from pathlib import Path
- import numpy
+ import numpy as np
+ import nibabel as nb
import pytest
+ import tempfile
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
- doctest_namespace['np'] = numpy
+ doctest_namespace['np'] = np
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
+
+ tmpdir = tempfile.TemporaryDirectory()
+ nifti_fname = str(Path(tmpdir.name) / 'test.nii.gz')
+ nb.Nifti1Image(np.random.random((5, 5)).astype('f4'), np.eye(4)).to_filename(nifti_fname)
+ doctest_namespace['nifti_fname'] = nifti_fname
+ yield
+ tmpdir.cleanup()
@pytest.fixture
def testdata_dir():
return data_dir
|
Make nifti_fname available to doctests
|
## Code Before:
"""py.test configuration"""
import os
from pathlib import Path
import numpy
import pytest
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace['np'] = numpy
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
@pytest.fixture
def testdata_dir():
return data_dir
## Instruction:
Make nifti_fname available to doctests
## Code After:
"""py.test configuration"""
import os
from pathlib import Path
import numpy as np
import nibabel as nb
import pytest
import tempfile
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace['np'] = np
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
tmpdir = tempfile.TemporaryDirectory()
nifti_fname = str(Path(tmpdir.name) / 'test.nii.gz')
nb.Nifti1Image(np.random.random((5, 5)).astype('f4'), np.eye(4)).to_filename(nifti_fname)
doctest_namespace['nifti_fname'] = nifti_fname
yield
tmpdir.cleanup()
@pytest.fixture
def testdata_dir():
return data_dir
|
"""py.test configuration"""
import os
from pathlib import Path
- import numpy
+ import numpy as np
? ++++++
+ import nibabel as nb
import pytest
+ import tempfile
from .utils.bids import collect_data
test_data_env = os.getenv('TEST_DATA_HOME',
str(Path.home() / '.cache' / 'stanford-crn'))
data_dir = Path(test_data_env) / 'BIDS-examples-1-enh-ds054'
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
- doctest_namespace['np'] = numpy
? -- -
+ doctest_namespace['np'] = np
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = data_dir
doctest_namespace['bids_collect_data'] = collect_data
+ tmpdir = tempfile.TemporaryDirectory()
+ nifti_fname = str(Path(tmpdir.name) / 'test.nii.gz')
+ nb.Nifti1Image(np.random.random((5, 5)).astype('f4'), np.eye(4)).to_filename(nifti_fname)
+ doctest_namespace['nifti_fname'] = nifti_fname
+ yield
+ tmpdir.cleanup()
+
@pytest.fixture
def testdata_dir():
return data_dir
|
a42b6d1faa38f92b21d74c1cf258f4b0e9800401
|
search/urls.py
|
search/urls.py
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'),
url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'),
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'),
url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'),
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
|
Allow any logged-in user to perform image searches.
|
Allow any logged-in user to perform image searches.
|
Python
|
mit
|
occrp/id-backend
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
- url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'),
+ url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'),
- url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'),
+ url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'),
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
|
Allow any logged-in user to perform image searches.
|
## Code Before:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'),
url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'),
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
## Instruction:
Allow any logged-in user to perform image searches.
## Code After:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'),
url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'),
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from core.auth import perm
import search.views
urlpatterns = patterns('',
url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'),
url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'),
- url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'),
? ^^ ^
+ url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'),
? ^^^^ ^^^
- url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'),
? ^^ ^
+ url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'),
? ^^^^ ^^^
url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'),
url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'),
)
|
638d7f38a0e22f72680437372b873d69ead973b1
|
config/run_distutils/__init__.py
|
config/run_distutils/__init__.py
|
from SCons.Script import *
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
env['RUN_DISTUTILS'] = 'python'
env['RUN_DISTUTILSOPTS'] = 'build'
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
|
from SCons.Script import *
import os
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
if 'RUN_DISTUTILS' in os.environ:
env['RUN_DISTUTILS'] = os.environ['RUN_DISTUTILS']
if 'RUN_DISTUTILSOPTS' in os.environ:
env['RUN_DISTUTILSOPTS'] = os.environ['RUN_DISTUTILSOPTS']
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
|
Allow env vars for RUN_DISTUTILS
|
Allow env vars for RUN_DISTUTILS
Allow use of env vars RUN_DISTUTILS, RUN_DISTUTILOPTS as defaults.
With this, on macos, macports doesn't need to be in PATH to build FAHControl. One just needs
export RUN_DISTUTILS="/opt/local/bin/python"
or the equivalent in dockbot.json env.
|
Python
|
lgpl-2.1
|
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
|
from SCons.Script import *
+ import os
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
- env['RUN_DISTUTILS'] = 'python'
- env['RUN_DISTUTILSOPTS'] = 'build'
+ if 'RUN_DISTUTILS' in os.environ:
+ env['RUN_DISTUTILS'] = os.environ['RUN_DISTUTILS']
+ if 'RUN_DISTUTILSOPTS' in os.environ:
+ env['RUN_DISTUTILSOPTS'] = os.environ['RUN_DISTUTILSOPTS']
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
|
Allow env vars for RUN_DISTUTILS
|
## Code Before:
from SCons.Script import *
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
env['RUN_DISTUTILS'] = 'python'
env['RUN_DISTUTILSOPTS'] = 'build'
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
## Instruction:
Allow env vars for RUN_DISTUTILS
## Code After:
from SCons.Script import *
import os
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
if 'RUN_DISTUTILS' in os.environ:
env['RUN_DISTUTILS'] = os.environ['RUN_DISTUTILS']
if 'RUN_DISTUTILSOPTS' in os.environ:
env['RUN_DISTUTILSOPTS'] = os.environ['RUN_DISTUTILSOPTS']
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
|
from SCons.Script import *
+ import os
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
- env['RUN_DISTUTILS'] = 'python'
- env['RUN_DISTUTILSOPTS'] = 'build'
+ if 'RUN_DISTUTILS' in os.environ:
+ env['RUN_DISTUTILS'] = os.environ['RUN_DISTUTILS']
+ if 'RUN_DISTUTILSOPTS' in os.environ:
+ env['RUN_DISTUTILSOPTS'] = os.environ['RUN_DISTUTILSOPTS']
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'RunDistUtils' : bld})
def exists():
return 1
|
004326064c87184e4373ab0b2d8d7ef9b46d94f9
|
tokens/conf.py
|
tokens/conf.py
|
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
|
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
TOKEN_TYPES = (
('MintableToken', 'Mintable Token'),
)
|
Add MintableToken as new token type
|
Add MintableToken as new token type
|
Python
|
apache-2.0
|
onyb/ethane,onyb/ethane,onyb/ethane,onyb/ethane
|
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
+
+ TOKEN_TYPES = (
+ ('MintableToken', 'Mintable Token'),
+ )
|
Add MintableToken as new token type
|
## Code Before:
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
## Instruction:
Add MintableToken as new token type
## Code After:
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
TOKEN_TYPES = (
('MintableToken', 'Mintable Token'),
)
|
PHASES = (
('PHASE_01', 'In review',),
('PHASE_02', 'Active',),
('PHASE_02', 'Inactive',),
)
+
+ TOKEN_TYPES = (
+ ('MintableToken', 'Mintable Token'),
+ )
|
f59106c4c804b0d0bc04dec9ff28b1b9c4ff08e4
|
GeneratePassword/generate_password_v3.py
|
GeneratePassword/generate_password_v3.py
|
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(w.group() for w in re.finditer(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
word_length = (password_length + 1) // number_of_words
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(re.findall(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
quotient, remainder = divmod(password_length, number_of_words)
word_length = quotient + (1 if remainder else 0)
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
Use a correct algorithm to determine the length of word to use
|
Use a correct algorithm to determine the length of word to use
|
Python
|
apache-2.0
|
OneScreenfulOfPython/screenfuls,OneScreenfulOfPython/screenfuls
|
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
- return set(w.group() for w in re.finditer(r"\w{3,}", f.read()))
+ return set(re.findall(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
- word_length = (password_length + 1) // number_of_words
+ quotient, remainder = divmod(password_length, number_of_words)
+ word_length = quotient + (1 if remainder else 0)
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
Use a correct algorithm to determine the length of word to use
|
## Code Before:
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(w.group() for w in re.finditer(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
word_length = (password_length + 1) // number_of_words
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
## Instruction:
Use a correct algorithm to determine the length of word to use
## Code After:
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
return set(re.findall(r"\w{3,}", f.read()))
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
quotient, remainder = divmod(password_length, number_of_words)
word_length = quotient + (1 if remainder else 0)
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(filepath) as f:
- return set(w.group() for w in re.finditer(r"\w{3,}", f.read()))
? ------------------- ^^^^
+ return set(re.findall(r"\w{3,}", f.read()))
? ^^^
def generate(filename, password_length, number_of_words):
"""Generate a password consisting of words from a text, at least
as long as password_length.
"""
words = get_words_from_file(filename)
- word_length = (password_length + 1) // number_of_words
+ quotient, remainder = divmod(password_length, number_of_words)
+ word_length = quotient + (1 if remainder else 0)
suitable_words = list(w for w in words if len(w) == word_length)
random.shuffle(suitable_words)
return "".join(w.title() for w in suitable_words[:number_of_words])
if __name__ == '__main__':
filename = input("Filename: ")
password_length = int(input("How many letters? "))
number_of_words = int(input("How many words? "))
password = generate(filename, password_length, number_of_words)
print("Your password is: {}".format(password))
|
67c444fb3603c234916b790d3dded3625f0512e5
|
pivot/test/test_utils.py
|
pivot/test/test_utils.py
|
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
def test_google_analytics_processor(self):
self.assertEquals(get_latest_term(), 'au12')
|
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
def test_get_latest_term(self):
self.assertEquals(get_latest_term(), 'au12')
|
Rename test to something more descriptive.
|
Rename test to something more descriptive.
|
Python
|
apache-2.0
|
uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot
|
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
- def test_google_analytics_processor(self):
+ def test_get_latest_term(self):
self.assertEquals(get_latest_term(), 'au12')
|
Rename test to something more descriptive.
|
## Code Before:
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
def test_google_analytics_processor(self):
self.assertEquals(get_latest_term(), 'au12')
## Instruction:
Rename test to something more descriptive.
## Code After:
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
def test_get_latest_term(self):
self.assertEquals(get_latest_term(), 'au12')
|
import os
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
import pivot
from pivot.utils import get_latest_term
TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__),
'test',
'test_resources',
'csvfiles/',)
class UtilsTest(TestCase):
@override_settings(CSV_ROOT=TEST_CSV_PATH)
- def test_google_analytics_processor(self):
+ def test_get_latest_term(self):
self.assertEquals(get_latest_term(), 'au12')
|
e01140053a2a906084d0ba50801b17d4ae7ce850
|
samples/unmanage_node.py
|
samples/unmanage_node.py
|
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
interfaceId = results['results'][0]['NodeID']
netObjectId = 'N:{}'.format(interfaceId)
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
|
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1')
if results['results']:
nodeId = results['results'][0]['NodeID']
caption = results['results'][0]['Caption']
netObjectId = 'N:{}'.format(nodeId)
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
print('Done...{} will be unmanaged until {}'.format(caption, tomorrow))
else:
print("Device doesn't Exist")
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
|
Correct node variable name and validate results
|
Correct node variable name and validate results
|
Python
|
apache-2.0
|
solarwinds/orionsdk-python
|
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
- results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
+ results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1')
+ if results['results']:
- interfaceId = results['results'][0]['NodeID']
+ nodeId = results['results'][0]['NodeID']
+ caption = results['results'][0]['Caption']
- netObjectId = 'N:{}'.format(interfaceId)
+ netObjectId = 'N:{}'.format(nodeId)
- now = datetime.utcnow()
+ now = datetime.utcnow()
- tomorrow = now + timedelta(days=1)
+ tomorrow = now + timedelta(days=1)
- swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
+ swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
+ print('Done...{} will be unmanaged until {}'.format(caption, tomorrow))
+ else:
+ print("Device doesn't Exist")
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
|
Correct node variable name and validate results
|
## Code Before:
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
interfaceId = results['results'][0]['NodeID']
netObjectId = 'N:{}'.format(interfaceId)
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
## Instruction:
Correct node variable name and validate results
## Code After:
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1')
if results['results']:
nodeId = results['results'][0]['NodeID']
caption = results['results'][0]['Caption']
netObjectId = 'N:{}'.format(nodeId)
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
print('Done...{} will be unmanaged until {}'.format(caption, tomorrow))
else:
print("Device doesn't Exist")
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
|
import requests
from orionsdk import SwisClient
from datetime import datetime, timedelta
def main():
hostname = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(hostname, username, password)
- results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes')
+ results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1')
+ if results['results']:
- interfaceId = results['results'][0]['NodeID']
? ^ ^^^^^^
+ nodeId = results['results'][0]['NodeID']
? ^^^^ ^^
+ caption = results['results'][0]['Caption']
- netObjectId = 'N:{}'.format(interfaceId)
? - ^^^^^^
+ netObjectId = 'N:{}'.format(nodeId)
? ++++ ^^
- now = datetime.utcnow()
+ now = datetime.utcnow()
? ++++
- tomorrow = now + timedelta(days=1)
+ tomorrow = now + timedelta(days=1)
? ++++
- swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
+ swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
? ++++
+ print('Done...{} will be unmanaged until {}'.format(caption, tomorrow))
+ else:
+ print("Device doesn't Exist")
requests.packages.urllib3.disable_warnings()
if __name__ == '__main__':
main()
|
8d40cbd1d2cf431454dcfd9a9088be73687e7c1a
|
skimage/viewer/__init__.py
|
skimage/viewer/__init__.py
|
try:
from .qt import QtGui as _QtGui
except ImportError as e:
raise ImportError('Viewer requires Qt')
from .viewers import ImageViewer, CollectionViewer
|
import warnings
try:
from .viewers import ImageViewer, CollectionViewer
except ImportError as e:
warnings.warn('Viewer requires Qt')
|
Allow viewer package to import without Qt
|
Allow viewer package to import without Qt
|
Python
|
bsd-3-clause
|
pratapvardhan/scikit-image,paalge/scikit-image,youprofit/scikit-image,michaelaye/scikit-image,blink1073/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,pratapvardhan/scikit-image,juliusbierk/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,robintw/scikit-image,GaZ3ll3/scikit-image,bennlich/scikit-image,GaZ3ll3/scikit-image,blink1073/scikit-image,paalge/scikit-image,ofgulban/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,dpshelio/scikit-image,bennlich/scikit-image,emon10005/scikit-image,rjeli/scikit-image,bsipocz/scikit-image,vighneshbirodkar/scikit-image,rjeli/scikit-image,ajaybhat/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,WarrenWeckesser/scikits-image,Britefury/scikit-image,bsipocz/scikit-image,warmspringwinds/scikit-image,paalge/scikit-image,robintw/scikit-image,ClinicalGraphics/scikit-image,keflavich/scikit-image,rjeli/scikit-image,WarrenWeckesser/scikits-image,vighneshbirodkar/scikit-image,newville/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,Britefury/scikit-image,jwiggins/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,michaelpacer/scikit-image,Hiyorimi/scikit-image,Midafi/scikit-image,michaelaye/scikit-image,ClinicalGraphics/scikit-image,oew1v07/scikit-image,michaelpacer/scikit-image
|
+ import warnings
try:
- from .qt import QtGui as _QtGui
+ from .viewers import ImageViewer, CollectionViewer
except ImportError as e:
- raise ImportError('Viewer requires Qt')
+ warnings.warn('Viewer requires Qt')
- from .viewers import ImageViewer, CollectionViewer
-
|
Allow viewer package to import without Qt
|
## Code Before:
try:
from .qt import QtGui as _QtGui
except ImportError as e:
raise ImportError('Viewer requires Qt')
from .viewers import ImageViewer, CollectionViewer
## Instruction:
Allow viewer package to import without Qt
## Code After:
import warnings
try:
from .viewers import ImageViewer, CollectionViewer
except ImportError as e:
warnings.warn('Viewer requires Qt')
|
+ import warnings
try:
- from .qt import QtGui as _QtGui
+ from .viewers import ImageViewer, CollectionViewer
except ImportError as e:
+ warnings.warn('Viewer requires Qt')
- raise ImportError('Viewer requires Qt')
-
- from .viewers import ImageViewer, CollectionViewer
|
e6d3d60265db1947b8af2d1c59c575c632ddc20b
|
linter.py
|
linter.py
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
)
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
|
Add support for handling errors and warnings
|
Add support for handling errors and warnings
|
Python
|
mit
|
lzwme/SublimeLinter-contrib-stylelint,lzwme/SublimeLinter-contrib-stylelint,kungfusheep/SublimeLinter-contrib-stylelint
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
- r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
+ r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
|
Add support for handling errors and warnings
|
## Code Before:
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
)
## Instruction:
Add support for handling errors and warnings
## Code After:
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
)
|
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provides an interface to stylelint."""
syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
error_stream = util.STREAM_BOTH
config_file = ('--config', '.stylelintrc', '~')
tempfile_suffix = 'css'
regex = (
- r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?P<message>.+)'
+ r'^\s*(?P<line>[0-9]+)\:(?P<col>[0-9]+)\s*(?:(?P<error>✖)|(?P<warning>⚠))\s*(?P<message>.+)'
? ++++++++++++++++++++++++++++++++++
)
|
0dc45239dde56ec7f1406646de4749a5cf43303e
|
proj_name/app_name/models.py
|
proj_name/app_name/models.py
|
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
|
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
class PositionedTag(Tag):
position = models.IntegerField()
|
Add a test for django model inheritance of the foreign key kind.
|
Add a test for django model inheritance of the foreign key kind.
|
Python
|
bsd-3-clause
|
g2p/tranquil
|
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
+ class PositionedTag(Tag):
+ position = models.IntegerField()
+
+
|
Add a test for django model inheritance of the foreign key kind.
|
## Code Before:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
## Instruction:
Add a test for django model inheritance of the foreign key kind.
## Code After:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
class PositionedTag(Tag):
position = models.IntegerField()
|
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
+
+ class PositionedTag(Tag):
+ position = models.IntegerField()
+
|
969344a4ed822eafcfbf7bd9d666ca45bf38168f
|
mass_mailing_partner/wizard/partner_merge.py
|
mass_mailing_partner/wizard/partner_merge.py
|
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = self.env["mailing.contact"].search(
[("partner_id", "in", partner_ids)]
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = (
self.env["mailing.contact"]
.sudo()
.search([("partner_id", "in", partner_ids)])
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
Add sudo() to prevent user without mailing access try to merge contacts
|
[FIX] mass_mailing_partner: Add sudo() to prevent user without mailing access try to merge contacts
|
Python
|
agpl-3.0
|
OCA/social,OCA/social,OCA/social
|
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
+ contacts = (
- contacts = self.env["mailing.contact"].search(
+ self.env["mailing.contact"]
+ .sudo()
- [("partner_id", "in", partner_ids)]
+ .search([("partner_id", "in", partner_ids)])
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
Add sudo() to prevent user without mailing access try to merge contacts
|
## Code Before:
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = self.env["mailing.contact"].search(
[("partner_id", "in", partner_ids)]
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
## Instruction:
Add sudo() to prevent user without mailing access try to merge contacts
## Code After:
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = (
self.env["mailing.contact"]
.sudo()
.search([("partner_id", "in", partner_ids)])
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
+ contacts = (
- contacts = self.env["mailing.contact"].search(
? -------- ^ --------
+ self.env["mailing.contact"]
? ^^
+ .sudo()
- [("partner_id", "in", partner_ids)]
+ .search([("partner_id", "in", partner_ids)])
? ++++++++ +
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
7755ab25249c39350004447daa614bc35e4517e7
|
src/malibu/__init__.py
|
src/malibu/__init__.py
|
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
__version__ = '0.1.8-7'
__release__ = '{}-{}'.format(__version__, __git_label__).strip('\n')
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
|
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
finally:
__git_label__ = __git_label__.decode('utf-8').strip()
__version__ = '0.1.8-7'
__release__ = '{}-{}'.format(__version__, __git_label__)
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
|
Remove unnecessary strip, add finally for release tagger
|
0.1.8: Remove unnecessary strip, add finally for release tagger
|
Python
|
unlicense
|
maiome-development/malibu
|
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
+ finally:
+ __git_label__ = __git_label__.decode('utf-8').strip()
__version__ = '0.1.8-7'
- __release__ = '{}-{}'.format(__version__, __git_label__).strip('\n')
+ __release__ = '{}-{}'.format(__version__, __git_label__)
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
|
Remove unnecessary strip, add finally for release tagger
|
## Code Before:
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
__version__ = '0.1.8-7'
__release__ = '{}-{}'.format(__version__, __git_label__).strip('\n')
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
## Instruction:
Remove unnecessary strip, add finally for release tagger
## Code After:
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
finally:
__git_label__ = __git_label__.decode('utf-8').strip()
__version__ = '0.1.8-7'
__release__ = '{}-{}'.format(__version__, __git_label__)
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
|
from malibu import command # noqa
from malibu import config # noqa
from malibu import database # noqa
from malibu import design # noqa
from malibu import text # noqa
from malibu import util # noqa
import subprocess
__git_label__ = ''
try:
__git_label__ = subprocess.check_output(
[
'git',
'rev-parse',
'--short',
'HEAD'
])
except (subprocess.CalledProcessError, IOError):
__git_label__ = 'RELEASE'
+ finally:
+ __git_label__ = __git_label__.decode('utf-8').strip()
__version__ = '0.1.8-7'
- __release__ = '{}-{}'.format(__version__, __git_label__).strip('\n')
? ------------
+ __release__ = '{}-{}'.format(__version__, __git_label__)
__doc__ = """
malibu is a collection of classes and utilities that make writing code
a little bit easier and a little less tedious.
The whole point of this library is to have a small codebase that could
be easily reused across projects with nice, easily loadable chunks that
can be used disjointly.
"""
|
8e58b413801a0dbbcd3e48a5ef94201a24af7e8e
|
are_there_spiders/are_there_spiders/custom_storages.py
|
are_there_spiders/are_there_spiders/custom_storages.py
|
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
|
import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
Revert "Improvement to custom storage."
|
Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.
|
Python
|
mit
|
wlonk/are_there_spiders,wlonk/are_there_spiders,wlonk/are_there_spiders
|
+ import urllib
+ import urlparse
+
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
+ # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
+ # causing erratic failures. So we subclass.
+ # (See http://stackoverflow.com/questions/11820566/inconsistent-
+ # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
+ class PatchedCachedFilesMixin(CachedFilesMixin):
+ def url(self, *a, **kw):
+ s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
+ if isinstance(s, unicode):
+ s = s.encode('utf-8', 'ignore')
+ scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
+ path = urllib.quote(path, '/%')
+ qs = urllib.quote_plus(qs, ':&=')
+ return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
+
+
- class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
+ class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
Revert "Improvement to custom storage."
|
## Code Before:
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
## Instruction:
Revert "Improvement to custom storage."
## Code After:
import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
+ import urllib
+ import urlparse
+
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
+ # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
+ # causing erratic failures. So we subclass.
+ # (See http://stackoverflow.com/questions/11820566/inconsistent-
+ # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
+ class PatchedCachedFilesMixin(CachedFilesMixin):
+ def url(self, *a, **kw):
+ s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
+ if isinstance(s, unicode):
+ s = s.encode('utf-8', 'ignore')
+ scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
+ path = urllib.quote(path, '/%')
+ qs = urllib.quote_plus(qs, ':&=')
+ return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
+
+
- class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
+ class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
? +++++++
pass
|
f0984c9855a6283de27e717fad73bb4f1b6394ab
|
flatten-array/flatten_array.py
|
flatten-array/flatten_array.py
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
Tidy and simplify generator code
|
Tidy and simplify generator code
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
- if isinstance(lst, (list, tuple)):
- for item in lst:
+ for item in lst:
+ if isinstance(item, (list, tuple)):
- if item is None:
- continue
- else:
- yield from _flatten(item)
+ yield from _flatten(item)
- else:
+ elif item is not None:
- yield lst
+ yield item
|
Tidy and simplify generator code
|
## Code Before:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
## Instruction:
Tidy and simplify generator code
## Code After:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
- if isinstance(lst, (list, tuple)):
- for item in lst:
? ----
+ for item in lst:
+ if isinstance(item, (list, tuple)):
- if item is None:
- continue
- else:
- yield from _flatten(item)
? ----
+ yield from _flatten(item)
- else:
+ elif item is not None:
- yield lst
? ^^
+ yield item
? ++++ ^ ++
|
adddfdb946ab45a186535ab4dcfc8848cf914dc0
|
allmychanges/validators.py
|
allmychanges/validators.py
|
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
Allow feed, rss, and atom prefixes in URL validator.
|
Allow feed, rss, and atom prefixes in URL validator.
|
Python
|
bsd-2-clause
|
AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com
|
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
- r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
+ r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
Allow feed, rss, and atom prefixes in URL validator.
|
## Code Before:
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
## Instruction:
Allow feed, rss, and atom prefixes in URL validator.
## Code After:
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
- r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
+ r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
? ++++++++++++++
r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri
r'$', re.IGNORECASE)
def __call__(self, value):
super(URLValidator, self).__call__(value)
|
3ee00fad1965dae23f83da870d7df1cb37727c7a
|
structlog/migrations/0001_initial.py
|
structlog/migrations/0001_initial.py
|
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
|
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
HStoreExtension(),
]
|
Add HStore extension to initial migration.
|
Add HStore extension to initial migration.
|
Python
|
bsd-2-clause
|
carlohamalainen/django-struct-log
|
from __future__ import unicode_literals
from django.db import migrations
-
+ from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
+ HStoreExtension(),
]
|
Add HStore extension to initial migration.
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
## Instruction:
Add HStore extension to initial migration.
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
HStoreExtension(),
]
|
from __future__ import unicode_literals
from django.db import migrations
-
+ from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
+ HStoreExtension(),
]
|
2403cbe2aa8f515bdd8f575112478010389ee48b
|
conan/ConanServerToArtifactory/migrate.py
|
conan/ConanServerToArtifactory/migrate.py
|
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search -r=local --raw")
packages = output.splitlines()
for package in packages:
print("Downloading %s" % package)
run("conan download %s -r=local" % package)
run("conan upload * --all --confirm -r=artifactory")
|
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search * --remote=local --raw")
packages = output.decode("utf-8").splitlines()
for package in packages[:1]:
print("Downloading %s" % package)
run("conan download {} --remote=local".format(package))
run("conan upload * --all --confirm -r=artifactory")
|
Update Conan server migration script
|
Update Conan server migration script
|
Python
|
apache-2.0
|
JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts
|
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
- output = subprocess.check_output("conan search -r=local --raw")
+ output = subprocess.check_output("conan search * --remote=local --raw")
- packages = output.splitlines()
+ packages = output.decode("utf-8").splitlines()
- for package in packages:
+ for package in packages[:1]:
print("Downloading %s" % package)
- run("conan download %s -r=local" % package)
+ run("conan download {} --remote=local".format(package))
run("conan upload * --all --confirm -r=artifactory")
|
Update Conan server migration script
|
## Code Before:
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search -r=local --raw")
packages = output.splitlines()
for package in packages:
print("Downloading %s" % package)
run("conan download %s -r=local" % package)
run("conan upload * --all --confirm -r=artifactory")
## Instruction:
Update Conan server migration script
## Code After:
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search * --remote=local --raw")
packages = output.decode("utf-8").splitlines()
for package in packages[:1]:
print("Downloading %s" % package)
run("conan download {} --remote=local".format(package))
run("conan upload * --all --confirm -r=artifactory")
|
import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
- output = subprocess.check_output("conan search -r=local --raw")
+ output = subprocess.check_output("conan search * --remote=local --raw")
? +++ +++++
- packages = output.splitlines()
+ packages = output.decode("utf-8").splitlines()
? ++++++++++++++++
- for package in packages:
+ for package in packages[:1]:
? + +++
print("Downloading %s" % package)
- run("conan download %s -r=local" % package)
? ^^ ^^^
+ run("conan download {} --remote=local".format(package))
? ^^ + +++++ ^^^^^^^^ +
run("conan upload * --all --confirm -r=artifactory")
|
3b7328dd7d9d235bf32b3cfb836b49e50b70be77
|
oz/plugins/redis_sessions/__init__.py
|
oz/plugins/redis_sessions/__init__.py
|
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
|
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
salted_password = "".join([unicode(password_salt), password])
return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
|
Allow for non-ascii characters in password_hash
|
Allow for non-ascii characters in password_hash
|
Python
|
bsd-3-clause
|
dailymuse/oz,dailymuse/oz,dailymuse/oz
|
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
- return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
+ salted_password = "".join([unicode(password_salt), password])
+ return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
|
Allow for non-ascii characters in password_hash
|
## Code Before:
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
## Instruction:
Allow for non-ascii characters in password_hash
## Code After:
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
salted_password = "".join([unicode(password_salt), password])
return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
|
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
import oz.app
from .middleware import *
from .options import *
from .tests import *
def random_hex(length):
"""Generates a random hex string"""
return binascii.hexlify(os.urandom(length))[length:]
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.app.settings["session_salt"]
- return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
+ salted_password = "".join([unicode(password_salt), password])
+ return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
|
07e825b31912a821d116b2a2b394bd041321cd6d
|
molly/utils/management/commands/deploy.py
|
molly/utils/management/commands/deploy.py
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
Deploy should remember to generate markers
|
Deploy should remember to generate markers
|
Python
|
apache-2.0
|
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
+ call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
Deploy should remember to generate markers
|
## Code Before:
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
## Instruction:
Deploy should remember to generate markers
## Code After:
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
+ call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
9c4aefb8ea88fd5505602c95f4762fdeb3aea183
|
oslo_versionedobjects/_utils.py
|
oslo_versionedobjects/_utils.py
|
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
|
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
# Need to handle either iso8601 or python UTC format
st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
|
Handle TZ change in iso8601 >=0.1.12
|
Handle TZ change in iso8601 >=0.1.12
The iso8601 lib introduced a change such that if running on python
3.2 or later it internally uses the python timezone information
instead of its own implementation. This does not change direct
date handling, but when converting this value there is a slight
difference where now python 2.x will show UTC times as "UTC", but
on python 3 they will end up with "UTC+00:00".
The to_primitive call for DateTime fields was doing an exact match
on "UTC" to determine whether to include "Z" in the resulting string.
This updates that handling to recognize either of the new values.
Change-Id: I71b58e8fd8fee8a57ee275ff3e0b77f165eca836
Closes-bug: #1744160
|
Python
|
apache-2.0
|
openstack/oslo.versionedobjects
|
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
+ # Need to handle either iso8601 or python UTC format
- st += ('Z' if tz == 'UTC' else tz)
+ st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
|
Handle TZ change in iso8601 >=0.1.12
|
## Code Before:
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
## Instruction:
Handle TZ change in iso8601 >=0.1.12
## Code After:
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
# Need to handle either iso8601 or python UTC format
st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
|
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
+ # Need to handle either iso8601 or python UTC format
- st += ('Z' if tz == 'UTC' else tz)
? ^^
+ st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
? ^^^^^^^^^^ ++++++ +
return st
|
99e0e90552c16067cfd41c9e89464311494c5a85
|
kitsune/sumo/management/commands/nunjucks_precompile.py
|
kitsune/sumo/management/commands/nunjucks_precompile.py
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
Fix nunjucks command so travis is happy
|
Fix nunjucks command so travis is happy
|
Python
|
bsd-3-clause
|
rlr/kitsune,orvi2014/kitsune,silentbob73/kitsune,H1ghT0p/kitsune,MziRintu/kitsune,feer56/Kitsune1,philipp-sumo/kitsune,safwanrahman/kitsune,turtleloveshoes/kitsune,H1ghT0p/kitsune,orvi2014/kitsune,safwanrahman/linuxdesh,safwanrahman/kitsune,Osmose/kitsune,Osmose/kitsune,NewPresident1/kitsune,H1ghT0p/kitsune,MziRintu/kitsune,safwanrahman/kitsune,iDTLabssl/kitsune,feer56/Kitsune2,dbbhattacharya/kitsune,safwanrahman/linuxdesh,MikkCZ/kitsune,YOTOV-LIMITED/kitsune,brittanystoroz/kitsune,rlr/kitsune,mozilla/kitsune,asdofindia/kitsune,orvi2014/kitsune,Osmose/kitsune,turtleloveshoes/kitsune,feer56/Kitsune2,feer56/Kitsune2,chirilo/kitsune,feer56/Kitsune1,YOTOV-LIMITED/kitsune,MziRintu/kitsune,chirilo/kitsune,MikkCZ/kitsune,rlr/kitsune,MikkCZ/kitsune,dbbhattacharya/kitsune,mozilla/kitsune,brittanystoroz/kitsune,dbbhattacharya/kitsune,feer56/Kitsune1,brittanystoroz/kitsune,anushbmx/kitsune,asdofindia/kitsune,feer56/Kitsune2,brittanystoroz/kitsune,NewPresident1/kitsune,safwanrahman/linuxdesh,YOTOV-LIMITED/kitsune,silentbob73/kitsune,turtleloveshoes/kitsune,safwanrahman/kitsune,silentbob73/kitsune,MziRintu/kitsune,iDTLabssl/kitsune,anushbmx/kitsune,anushbmx/kitsune,orvi2014/kitsune,Osmose/kitsune,YOTOV-LIMITED/kitsune,mythmon/kitsune,philipp-sumo/kitsune,dbbhattacharya/kitsune,turtleloveshoes/kitsune,silentbob73/kitsune,mythmon/kitsune,philipp-sumo/kitsune,iDTLabssl/kitsune,mozilla/kitsune,chirilo/kitsune,rlr/kitsune,mozilla/kitsune,MikkCZ/kitsune,NewPresident1/kitsune,iDTLabssl/kitsune,NewPresident1/kitsune,anushbmx/kitsune,mythmon/kitsune,asdofindia/kitsune,mythmon/kitsune,asdofindia/kitsune,chirilo/kitsune,H1ghT0p/kitsune
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
+ try:
+ os.makedirs(path('static/js/templates'))
+ except OSError:
+ pass
+
+ try:
+ os.makedirs(path('static/tpl'))
+ except OSError:
+ pass
+
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
Fix nunjucks command so travis is happy
|
## Code Before:
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
## Instruction:
Fix nunjucks command so travis is happy
## Code After:
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
+ try:
+ os.makedirs(path('static/js/templates'))
+ except OSError:
+ pass
+
+ try:
+ os.makedirs(path('static/tpl'))
+ except OSError:
+ pass
+
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
0a4057a1c220076a34182327de9b01e8412ad68e
|
neutron_fwaas/tests/functional/test_fwaas_driver.py
|
neutron_fwaas/tests/functional/test_fwaas_driver.py
|
from neutron.tests.functional.agent.linux import base
class TestFWaaSDriver(base.BaseLinuxTestCase):
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
|
from neutron.tests.functional import base
class TestFWaaSDriver(base.BaseSudoTestCase):
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
|
Use BaseSudoTestCase instead of BaseLinuxTestCase
|
Use BaseSudoTestCase instead of BaseLinuxTestCase
BaseLinuxTestCase will be removed from neutron code[1]. This change
uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods
have been transformed into fixtures.
[1] https://review.openstack.org/161913
Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628
|
Python
|
apache-2.0
|
openstack/neutron-fwaas,gaolichuang/neutron-fwaas,gaolichuang/neutron-fwaas,openstack/neutron-fwaas
|
- from neutron.tests.functional.agent.linux import base
+ from neutron.tests.functional import base
- class TestFWaaSDriver(base.BaseLinuxTestCase):
+ class TestFWaaSDriver(base.BaseSudoTestCase):
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
|
Use BaseSudoTestCase instead of BaseLinuxTestCase
|
## Code Before:
from neutron.tests.functional.agent.linux import base
class TestFWaaSDriver(base.BaseLinuxTestCase):
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
## Instruction:
Use BaseSudoTestCase instead of BaseLinuxTestCase
## Code After:
from neutron.tests.functional import base
class TestFWaaSDriver(base.BaseSudoTestCase):
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
|
- from neutron.tests.functional.agent.linux import base
? ------------
+ from neutron.tests.functional import base
- class TestFWaaSDriver(base.BaseLinuxTestCase):
? ^^^ ^
+ class TestFWaaSDriver(base.BaseSudoTestCase):
? ^ ^^
"""Test the Iptables implmentation of the FWaaS driver."""
# NOTE: Tests may be added/removed/changed, when this is fleshed out
# in future commits.
def test_status_reporting(self):
"""Test status reported correctly to agent."""
pass
|
5ebc53fccd79e479d1a39cf02160c8eb2eab247a
|
vulk/__init__.py
|
vulk/__init__.py
|
__version__ = "0.2.0"
|
from os import path as p
__version__ = "0.2.0"
PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
|
Add Path to Vulk package
|
Add Path to Vulk package
|
Python
|
apache-2.0
|
Echelon9/vulk,realitix/vulk,realitix/vulk,Echelon9/vulk
|
+ from os import path as p
+
__version__ = "0.2.0"
+ PATH_VULK = p.dirname(p.abspath(__file__))
+ PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
+ PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
+
|
Add Path to Vulk package
|
## Code Before:
__version__ = "0.2.0"
## Instruction:
Add Path to Vulk package
## Code After:
from os import path as p
__version__ = "0.2.0"
PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
|
+ from os import path as p
+
__version__ = "0.2.0"
+
+ PATH_VULK = p.dirname(p.abspath(__file__))
+ PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
+ PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
|
543509e991f88ecad7e5ed69db6d3b175fe44351
|
tests/constants.py
|
tests/constants.py
|
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_GROUP = ''
TEST_BAD_USER = '1234'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
|
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_BAD_USER = '1234'
TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
|
Add a test group key
|
Add a test group key
|
Python
|
mit
|
scolby33/pushover_complete
|
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
- TEST_GROUP = ''
TEST_BAD_USER = '1234'
+ TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
|
Add a test group key
|
## Code Before:
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_GROUP = ''
TEST_BAD_USER = '1234'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
## Instruction:
Add a test group key
## Code After:
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_BAD_USER = '1234'
TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
|
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
- TEST_GROUP = ''
TEST_BAD_USER = '1234'
+ TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
|
1cf14753174b6fdbd5999ac857ce0e55852194b6
|
dmoj/executors/ruby_executor.py
|
dmoj/executors/ruby_executor.py
|
import os
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
|
import os
import re
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_fs(self):
fs = super(RubyExecutor, self).get_fs()
home = self.runtime_dict.get('%s_home' % self.get_executor_name().lower())
if home is not None:
fs.append(re.escape(home))
components = home.split('/')
components.pop()
while components and components[-1]:
fs.append(re.escape('/'.join(components)) + '$')
components.pop()
return fs
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
|
Make Ruby work on Travis
|
Make Ruby work on Travis
|
Python
|
agpl-3.0
|
DMOJ/judge,DMOJ/judge,DMOJ/judge
|
import os
+ import re
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
+
+ def get_fs(self):
+ fs = super(RubyExecutor, self).get_fs()
+ home = self.runtime_dict.get('%s_home' % self.get_executor_name().lower())
+ if home is not None:
+ fs.append(re.escape(home))
+ components = home.split('/')
+ components.pop()
+ while components and components[-1]:
+ fs.append(re.escape('/'.join(components)) + '$')
+ components.pop()
+ return fs
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
|
Make Ruby work on Travis
|
## Code Before:
import os
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
## Instruction:
Make Ruby work on Travis
## Code After:
import os
import re
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_fs(self):
fs = super(RubyExecutor, self).get_fs()
home = self.runtime_dict.get('%s_home' % self.get_executor_name().lower())
if home is not None:
fs.append(re.escape(home))
components = home.split('/')
components.pop()
while components and components[-1]:
fs.append(re.escape('/'.join(components)) + '$')
components.pop()
return fs
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
|
import os
+ import re
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
+
+ def get_fs(self):
+ fs = super(RubyExecutor, self).get_fs()
+ home = self.runtime_dict.get('%s_home' % self.get_executor_name().lower())
+ if home is not None:
+ fs.append(re.escape(home))
+ components = home.split('/')
+ components.pop()
+ while components and components[-1]:
+ fs.append(re.escape('/'.join(components)) + '$')
+ components.pop()
+ return fs
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(cls, command):
return ['-v']
@classmethod
def get_command(cls):
name = cls.get_executor_name().lower()
if name in cls.runtime_dict:
return cls.runtime_dict[name]
if '%s_home' % name in cls.runtime_dict:
return os.path.join(cls.runtime_dict['%s_home' % name], 'bin', 'ruby')
@classmethod
def get_versionable_commands(cls):
return ('ruby', cls.get_command()),
@classmethod
def get_find_first_mapping(cls):
return {cls.name.lower(): cls.command_paths}
|
1736d7b7aed3ce3049186ce97e24941de0187caf
|
oidc_provider/lib/utils/common.py
|
oidc_provider/lib/utils/common.py
|
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
with open(file_path, 'r') as f:
key = f.read()
return key
|
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
try:
with open(file_path, 'r') as f:
key = f.read()
except IOError:
raise IOError('We could not find your key file on: ' + file_path)
return key
|
Add IOError custom message when rsa key file is missing.
|
Add IOError custom message when rsa key file is missing.
|
Python
|
mit
|
ByteInternet/django-oidc-provider,torreco/django-oidc-provider,juanifioren/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,wojtek-fliposports/django-oidc-provider,nmohoric/django-oidc-provider,nmohoric/django-oidc-provider,ByteInternet/django-oidc-provider,torreco/django-oidc-provider,wojtek-fliposports/django-oidc-provider,juanifioren/django-oidc-provider
|
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
+ try:
- with open(file_path, 'r') as f:
+ with open(file_path, 'r') as f:
- key = f.read()
+ key = f.read()
+ except IOError:
+ raise IOError('We could not find your key file on: ' + file_path)
return key
|
Add IOError custom message when rsa key file is missing.
|
## Code Before:
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
with open(file_path, 'r') as f:
key = f.read()
return key
## Instruction:
Add IOError custom message when rsa key file is missing.
## Code After:
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
try:
with open(file_path, 'r') as f:
key = f.read()
except IOError:
raise IOError('We could not find your key file on: ' + file_path)
return key
|
from django.conf import settings as django_settings
from django.core.urlresolvers import reverse
from oidc_provider import settings
def get_issuer():
"""
Construct the issuer full url. Basically is the site url with some path
appended.
"""
site_url = settings.get('SITE_URL')
path = reverse('oidc_provider:provider_info') \
.split('/.well-known/openid-configuration/')[0]
issuer = site_url + path
return issuer
def get_rsa_key():
"""
Load the rsa key previously created with `creatersakey` command.
"""
file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem'
+ try:
- with open(file_path, 'r') as f:
+ with open(file_path, 'r') as f:
? ++++
- key = f.read()
+ key = f.read()
? ++++
+ except IOError:
+ raise IOError('We could not find your key file on: ' + file_path)
return key
|
1ba14774b1ed483f512562ab83f91fab8b843db7
|
nazs/web/core/blocks.py
|
nazs/web/core/blocks.py
|
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
|
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
classes='btn btn-sm btn-primary',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
classes='btn btn-sm btn-success',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
classes='btn btn-sm btn-danger',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
|
Add proper css classes to action buttons
|
Add proper css classes to action buttons
|
Python
|
agpl-3.0
|
exekias/droplet,exekias/droplet,exekias/droplet
|
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
+ classes='btn btn-sm btn-primary',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
+ classes='btn btn-sm btn-success',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
+ classes='btn btn-sm btn-danger',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
|
Add proper css classes to action buttons
|
## Code Before:
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
## Instruction:
Add proper css classes to action buttons
## Code After:
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
classes='btn btn-sm btn-primary',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
classes='btn btn-sm btn-success',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
classes='btn btn-sm btn-danger',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
|
from django.utils.translation import ugettext as _
from achilles import blocks, tables
import nazs
register = blocks.Library('core')
@register.block(template_name='web/core/welcome.html')
def home():
return {'version': nazs.__version__}
@register.block(template_name='web/core/apply_button.html')
def apply_button():
return {'active': nazs.changed()}
@register.block('modules')
class Modules(tables.Table):
id_field = 'name'
# Module name
name = tables.Column(verbose_name=_('Module'))
# Module status
status = tables.MergeColumn(
verbose_name=_('Status'),
columns=(
('install', tables.ActionColumn(verbose_name=_('Install'),
action='core:install_module',
+ classes='btn btn-sm btn-primary',
visible=lambda m: not m.installed)),
('enable', tables.ActionColumn(verbose_name=_('Enable'),
action='core:enable_module',
+ classes='btn btn-sm btn-success',
visible=lambda m: m.installed and
not m.enabled)),
('disable', tables.ActionColumn(verbose_name=_('Disable'),
action='core:disable_module',
+ classes='btn btn-sm btn-danger',
visible=lambda m: m.installed and
m.enabled)),
)
)
def objects(self):
return nazs.modules()
def get_object(self, name):
for module in nazs.modules():
if module.name == name:
return module
raise KeyError('Module %s not found' % name)
|
6cc48b08fd0b3a0dda2a8dfdc55b8d8d3b9022b1
|
pyramda/math/mean_test.py
|
pyramda/math/mean_test.py
|
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
|
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
assert_equal(mean([5, 7, 3]), 5)
|
Add test establishing no change in behavior for unsorted input arrays
|
Add test establishing no change in behavior for unsorted input arrays
|
Python
|
mit
|
jackfirth/pyramda
|
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
+ assert_equal(mean([5, 7, 3]), 5)
|
Add test establishing no change in behavior for unsorted input arrays
|
## Code Before:
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
## Instruction:
Add test establishing no change in behavior for unsorted input arrays
## Code After:
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
assert_equal(mean([5, 7, 3]), 5)
|
from .mean import mean
from pyramda.private.asserts import assert_equal
def mean_test():
assert_equal(mean([3, 5, 7]), 5)
+ assert_equal(mean([5, 7, 3]), 5)
|
4735804f4951835e4e3c7d116628344bddf45aa3
|
atomicpress/admin.py
|
atomicpress/admin.py
|
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(ModelView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
class PostView(ModelView):
column_default_sort = ('date', True)
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(PostView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
Update post view sorting (so latest comes first)
|
Update post view sorting (so latest comes first)
|
Python
|
mit
|
marteinn/AtomicPress,marteinn/AtomicPress,marteinn/AtomicPress,marteinn/AtomicPress
|
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
+ class PostView(ModelView):
+ column_default_sort = ('date', True)
+
+
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
- admin.add_view(ModelView(models.Post, db.session, category="Post"))
+ admin.add_view(PostView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
Update post view sorting (so latest comes first)
|
## Code Before:
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(ModelView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
## Instruction:
Update post view sorting (so latest comes first)
## Code After:
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
class PostView(ModelView):
column_default_sort = ('date', True)
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
admin.add_view(PostView(models.Post, db.session, category="Post"))
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
from flask import current_app
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import AdminIndexView, expose, Admin
from flask_admin.contrib.sqla import ModelView
from atomicpress import models
from atomicpress.app import db
class HomeView(AdminIndexView):
@expose("/")
def index(self):
return self.render('admin/home.html')
+ class PostView(ModelView):
+ column_default_sort = ('date', True)
+
+
def create_admin():
app = current_app._get_current_object()
admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home'))
admin.add_view(ModelView(models.Blog, db.session, category="Blog"))
admin.add_view(ModelView(models.Author, db.session, category="Blog"))
- admin.add_view(ModelView(models.Post, db.session, category="Post"))
? ^ ^^^
+ admin.add_view(PostView(models.Post, db.session, category="Post"))
? ^ ^^
admin.add_view(ModelView(models.Tag, db.session, category="Post"))
admin.add_view(ModelView(models.Category, db.session, category="Post"))
admin.add_view(FileAdmin(app.config["UPLOADS_PATH"],
app.config["UPLOADS_URL"],
name='Upload files'))
|
08edbb1b723880ac81b63e5d1ca31c331f79b0a8
|
awx/api/pagination.py
|
awx/api/pagination.py
|
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
|
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
max_page_size = 200
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
|
Set an upper limit of 200 on the max page size
|
Set an upper limit of 200 on the max page size
|
Python
|
apache-2.0
|
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx
|
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
+ max_page_size = 200
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
|
Set an upper limit of 200 on the max page size
|
## Code Before:
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
## Instruction:
Set an upper limit of 200 on the max page size
## Code After:
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
max_page_size = 200
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
|
from rest_framework import pagination
from rest_framework.utils.urls import replace_query_param
class Pagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
+ max_page_size = 200
def get_next_link(self):
if not self.page.has_next():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)
def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request and self.request.get_full_path() or ''
page_number = self.page.previous_page_number()
return replace_query_param(url, self.page_query_param, page_number)
|
2f5417811eb8048659bd9b5408c721d481af4ece
|
tests/python-support/experiments.py
|
tests/python-support/experiments.py
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
Print JSON document upon parse error
|
Print JSON document upon parse error
|
Python
|
mit
|
Andlon/crest,Andlon/crest,Andlon/crest
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
- args = [_experiment_runner_path() ]
+ args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
+ try:
- return json.loads(result.stdout)
+ return json.loads(result.stdout)
+ except json.JSONDecodeError as err:
+ import sys
+ document = err.doc
+ print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
+ file=sys.stderr)
+ raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
Print JSON document upon parse error
|
## Code Before:
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
## Instruction:
Print JSON document upon parse error
## Code After:
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
- args = [_experiment_runner_path() ]
? -
+ args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
+ try:
- return json.loads(result.stdout)
+ return json.loads(result.stdout)
? ++++
+ except json.JSONDecodeError as err:
+ import sys
+ document = err.doc
+ print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
+ file=sys.stderr)
+ raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
a79a3f7c42c858ae42c618479654cd7589de05b9
|
zeeko/utils/tests/test_hmap.py
|
zeeko/utils/tests/test_hmap.py
|
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
@pytest.mark.skip
def test_hmap(items):
"""docstring for test"""
h = HashMap(10)
if len(items):
with pytest.raises(KeyError):
h[items[0]]
for item in items:
h.add(item)
assert len(h) == len(items)
for i, item in enumerate(items):
assert h[item] == i
assert repr(h) == "HashMap({0!r})".format(items)
if len(items):
item = items[0]
del h[item]
assert len(h) == len(items) - 1
assert item not in h
|
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
|
Remove unused tests for hash map
|
Remove unused tests for hash map
|
Python
|
bsd-3-clause
|
alexrudy/Zeeko,alexrudy/Zeeko
|
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
- @pytest.mark.skip
- def test_hmap(items):
- """docstring for test"""
- h = HashMap(10)
- if len(items):
- with pytest.raises(KeyError):
- h[items[0]]
-
- for item in items:
- h.add(item)
- assert len(h) == len(items)
- for i, item in enumerate(items):
- assert h[item] == i
-
- assert repr(h) == "HashMap({0!r})".format(items)
-
- if len(items):
- item = items[0]
-
- del h[item]
- assert len(h) == len(items) - 1
- assert item not in h
-
+
|
Remove unused tests for hash map
|
## Code Before:
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
@pytest.mark.skip
def test_hmap(items):
"""docstring for test"""
h = HashMap(10)
if len(items):
with pytest.raises(KeyError):
h[items[0]]
for item in items:
h.add(item)
assert len(h) == len(items)
for i, item in enumerate(items):
assert h[item] == i
assert repr(h) == "HashMap({0!r})".format(items)
if len(items):
item = items[0]
del h[item]
assert len(h) == len(items) - 1
assert item not in h
## Instruction:
Remove unused tests for hash map
## Code After:
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
|
import pytest
from ..hmap import HashMap
@pytest.fixture(params=[0,1,5,9])
def n(request):
"""Number of items"""
return request.param
@pytest.fixture
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)]
+
- @pytest.mark.skip
- def test_hmap(items):
- """docstring for test"""
- h = HashMap(10)
- if len(items):
- with pytest.raises(KeyError):
- h[items[0]]
-
- for item in items:
- h.add(item)
- assert len(h) == len(items)
- for i, item in enumerate(items):
- assert h[item] == i
-
- assert repr(h) == "HashMap({0!r})".format(items)
-
- if len(items):
- item = items[0]
-
- del h[item]
- assert len(h) == len(items) - 1
- assert item not in h
-
|
4b111c035f92f941cff4b6885d2fa01ddcb1657e
|
titanembeds/database/custom_redislite.py
|
titanembeds/database/custom_redislite.py
|
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
return self.redis_instance.ttl(key)
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
self.redis_instance.set(key, 1)
self.redis_instance.expireat(key, int(time.time() + expiry))
else:
oldexp = self.get_expiry(key)
self.redis_instance.set(key, int(self.redis_instance.get(key))+1)
self.redis_instance.expireat(key, int(time.time() + oldexp))
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
|
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
return self.redis_instance.ttl(key) or 0
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
self.redis_instance.set(key, 1, ex=expiry)
else:
oldexp = self.get_expiry(key)
self.redis_instance.set(key, int(self.redis_instance.get(key))+1, ex=oldexp)
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
|
Fix custom redislite to account for the none errors
|
Fix custom redislite to account for the none errors
|
Python
|
agpl-3.0
|
TitanEmbeds/Titan,TitanEmbeds/Titan,TitanEmbeds/Titan
|
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
- return self.redis_instance.ttl(key)
+ return self.redis_instance.ttl(key) or 0
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
- self.redis_instance.set(key, 1)
+ self.redis_instance.set(key, 1, ex=expiry)
- self.redis_instance.expireat(key, int(time.time() + expiry))
else:
oldexp = self.get_expiry(key)
- self.redis_instance.set(key, int(self.redis_instance.get(key))+1)
+ self.redis_instance.set(key, int(self.redis_instance.get(key))+1, ex=oldexp)
- self.redis_instance.expireat(key, int(time.time() + oldexp))
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
|
Fix custom redislite to account for the none errors
|
## Code Before:
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
return self.redis_instance.ttl(key)
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
self.redis_instance.set(key, 1)
self.redis_instance.expireat(key, int(time.time() + expiry))
else:
oldexp = self.get_expiry(key)
self.redis_instance.set(key, int(self.redis_instance.get(key))+1)
self.redis_instance.expireat(key, int(time.time() + oldexp))
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
## Instruction:
Fix custom redislite to account for the none errors
## Code After:
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
return self.redis_instance.ttl(key) or 0
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
self.redis_instance.set(key, 1, ex=expiry)
else:
oldexp = self.get_expiry(key)
self.redis_instance.set(key, int(self.redis_instance.get(key))+1, ex=oldexp)
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
|
import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return True
def get_expiry(self, key):
- return self.redis_instance.ttl(key)
+ return self.redis_instance.ttl(key) or 0
? +++++
def incr(self, key, expiry, elastic_expiry=False):
if not self.redis_instance.exists(key):
- self.redis_instance.set(key, 1)
+ self.redis_instance.set(key, 1, ex=expiry)
? +++++++++++
- self.redis_instance.expireat(key, int(time.time() + expiry))
else:
oldexp = self.get_expiry(key)
- self.redis_instance.set(key, int(self.redis_instance.get(key))+1)
+ self.redis_instance.set(key, int(self.redis_instance.get(key))+1, ex=oldexp)
? +++++++++++
- self.redis_instance.expireat(key, int(time.time() + oldexp))
return
def get(self, key):
return int(self.redis_instance.get(key))
def reset(self):
return self.redis_instance.flushdb()
|
736150f90d82a4583630b9999db94fa6afb47e10
|
test_samples/test_simple.py
|
test_samples/test_simple.py
|
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
def test_error(self):
raise RuntimeError("error raised for testing purpose")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
Add a sample of erroneous test.
|
Add a sample of erroneous test.
|
Python
|
bsd-2-clause
|
nicolasdespres/hunittest
|
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
+ def test_error(self):
+ raise RuntimeError("error raised for testing purpose")
+
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
Add a sample of erroneous test.
|
## Code Before:
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
## Instruction:
Add a sample of erroneous test.
## Code After:
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
def test_error(self):
raise RuntimeError("error raised for testing purpose")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
+ def test_error(self):
+ raise RuntimeError("error raised for testing purpose")
+
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
0a6072621570464522cbfa6d939dffccc0fa6503
|
spacy/cli/converters/iob2json.py
|
spacy/cli/converters/iob2json.py
|
from __future__ import unicode_literals
import cytoolz
from ...gold import iob_to_biluo
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in cytoolz.partition_all(n_sents, docs):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
from __future__ import unicode_literals
from ...gold import iob_to_biluo
from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
Remove cytoolz usage in CLI
|
Remove cytoolz usage in CLI
|
Python
|
mit
|
explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy
|
from __future__ import unicode_literals
- import cytoolz
-
from ...gold import iob_to_biluo
+ from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
- for group in cytoolz.partition_all(n_sents, docs):
+ for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
Remove cytoolz usage in CLI
|
## Code Before:
from __future__ import unicode_literals
import cytoolz
from ...gold import iob_to_biluo
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in cytoolz.partition_all(n_sents, docs):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
## Instruction:
Remove cytoolz usage in CLI
## Code After:
from __future__ import unicode_literals
from ...gold import iob_to_biluo
from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
from __future__ import unicode_literals
- import cytoolz
-
from ...gold import iob_to_biluo
+ from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
- for group in cytoolz.partition_all(n_sents, docs):
+ for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
2f2b64321a54c93a109c0b65866d724227db9399
|
tests/conftest.py
|
tests/conftest.py
|
from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
user = MagicMock()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
|
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
# create empty object, because Mock not included to python2
user = type('test', (object,), {})()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
|
Remove Mock and create "empty" object on the fly
|
Remove Mock and create "empty" object on the fly
|
Python
|
mit
|
jadolg/rocketchat_API
|
- from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
- user = MagicMock()
+ # create empty object, because Mock not included to python2
+ user = type('test', (object,), {})()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
|
Remove Mock and create "empty" object on the fly
|
## Code Before:
from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
user = MagicMock()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
## Instruction:
Remove Mock and create "empty" object on the fly
## Code After:
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
# create empty object, because Mock not included to python2
user = type('test', (object,), {})()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
|
- from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="[email protected]"):
- user = MagicMock()
+ # create empty object, because Mock not included to python2
+ user = type('test', (object,), {})()
user.name = name
user.password = password
user.email = email
rocket.users_register(
email=user.email,
name=user.name,
password=user.password,
username=user.name
)
return user
return _create_user
@pytest.fixture(scope="session")
def user(create_user):
_user = create_user()
return _user
@pytest.fixture(scope="session")
def logged_rocket(user):
_rocket = RocketChat(user.name, user.password)
return _rocket
|
c88969f2e4a1459e6a66da3f75f8ea41ae9cea9c
|
rplugin/python3/denite/source/denite_gtags/tags_base.py
|
rplugin/python3/denite/source/denite_gtags/tags_base.py
|
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
def __init__(self, vim):
super().__init__(vim)
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
if len(context['args']) > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
tags = self.exec_global(self.get_search_flags() + [word], context)
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
|
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
args_count = len(context['args'])
if args_count > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
tags = self.exec_global(self.get_search_flags() + ['--', word], context)
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
|
Fix error on words beginning with '-'
|
Fix error on words beginning with '-'
|
Python
|
mit
|
ozelentok/denite-gtags
|
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
- def __init__(self, vim):
- super().__init__(vim)
-
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
- if len(context['args']) > 0:
+ args_count = len(context['args'])
+ if args_count > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
- tags = self.exec_global(self.get_search_flags() + [word], context)
+ tags = self.exec_global(self.get_search_flags() + ['--', word], context)
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
|
Fix error on words beginning with '-'
|
## Code Before:
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
def __init__(self, vim):
super().__init__(vim)
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
if len(context['args']) > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
tags = self.exec_global(self.get_search_flags() + [word], context)
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
## Instruction:
Fix error on words beginning with '-'
## Code After:
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
args_count = len(context['args'])
if args_count > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
tags = self.exec_global(self.get_search_flags() + ['--', word], context)
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
|
import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
- def __init__(self, vim):
- super().__init__(vim)
-
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, context):
- if len(context['args']) > 0:
? ^^ -----
+ args_count = len(context['args'])
? ^^^^^^^^^^^^
+ if args_count > 0:
return context['args'][0]
return context['input']
def gather_candidates(self, context):
word = self.get_search_word(context)
- tags = self.exec_global(self.get_search_flags() + [word], context)
+ tags = self.exec_global(self.get_search_flags() + ['--', word], context)
? ++++++
candidates = self._convert_to_candidates(tags)
return candidates
@classmethod
def _convert_to_candidates(cls, tags):
candidates = []
for tag in tags:
path, line, text = cls._parse_tag(tag)
col = text.find(text) -1
candidates.append({
'word': tag,
'action__path': path,
'action__line': line,
'action__text': text,
'action__col': col
})
return candidates
@classmethod
def _parse_tag(cls, tag):
match = cls.TAG_PATTERN.match(tag)
return match.groups()
|
6f992bda1747d8dd23dd03f1ae3679c00f2fc977
|
marketpulse/geo/lookup.py
|
marketpulse/geo/lookup.py
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
Handle errors in case of a country mismatch.
|
Handle errors in case of a country mismatch.
|
Python
|
mpl-2.0
|
mozilla/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,mozilla/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
+ try:
- results['country'] = COUNTRY_CODES[text]
+ results['country'] = COUNTRY_CODES[text]
+ except KeyError:
+ results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
Handle errors in case of a country mismatch.
|
## Code Before:
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
## Instruction:
Handle errors in case of a country mismatch.
## Code After:
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
+ try:
- results['country'] = COUNTRY_CODES[text]
+ results['country'] = COUNTRY_CODES[text]
? ++++
+ except KeyError:
+ results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
2f084990d919855a4b1e4bb909c607ef91810fba
|
knights/dj.py
|
knights/dj.py
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
for path in params.get('DIRS', []):
loader.add_path(path)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
tmpl = loader.load_template(template_name)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
Use built in template dirs list Add user to context
|
Use built in template dirs list
Add user to context
|
Python
|
mit
|
funkybob/knights-templater,funkybob/knights-templater
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
- for path in params.get('DIRS', []):
- loader.add_path(path)
-
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
+ try:
- tmpl = loader.load_template(template_name)
+ tmpl = loader.load_template(template_name, self.template_dirs)
+ except Exception as e:
+ raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
+ context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
Use built in template dirs list Add user to context
|
## Code Before:
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
for path in params.get('DIRS', []):
loader.add_path(path)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
tmpl = loader.load_template(template_name)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
## Instruction:
Use built in template dirs list Add user to context
## Code After:
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
- for path in params.get('DIRS', []):
- loader.add_path(path)
-
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
+ try:
- tmpl = loader.load_template(template_name)
+ tmpl = loader.load_template(template_name, self.template_dirs)
? ++++ ++++++++++++++++++++
+ except Exception as e:
+ raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
+ context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
50c44a5708d1c054207eba264e1cdf9d1f6718da
|
deployer/logger.py
|
deployer/logger.py
|
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
|
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
handler.setLevel(LOG_ROOT_LEVEL)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
|
Set log level for handler
|
Set log level for handler
|
Python
|
mit
|
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
|
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
- handler.setLevel(logging.INFO)
+ handler.setLevel(LOG_ROOT_LEVEL)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
|
Set log level for handler
|
## Code Before:
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
## Instruction:
Set log level for handler
## Code After:
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
handler.setLevel(LOG_ROOT_LEVEL)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
|
from __future__ import absolute_import
import logging
from logging.handlers import SysLogHandler
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \
LOG_IDENTIFIER
def init_logging(name=None):
app_logger = logging.getLogger(name)
app_logger.setLevel(LOG_ROOT_LEVEL)
app_logger.propagate = False
if TOTEM_ENV == 'local':
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app_logger.addHandler(handler)
else:
formatter = logging.Formatter(
'{0}[%(process)d]: %(name)s: %(message)s'
.format(LOG_IDENTIFIER))
handler = logging.handlers.SysLogHandler(
address='/dev/log',
facility=SysLogHandler.LOG_DAEMON)
handler.setFormatter(formatter)
- handler.setLevel(logging.INFO)
+ handler.setLevel(LOG_ROOT_LEVEL)
app_logger.addHandler(handler)
app_logger.info('Logger initialized')
return app_logger
def init_celery_logging(*args, **kwargs):
init_logging('celery')
|
7f83888c957b892e6cc9d2e92f49a2737a9eabfe
|
logstash_handler/__init__.py
|
logstash_handler/__init__.py
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ca_certs=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ca_certs = ca_certs
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
Add support for CA certificates
|
Add support for CA certificates
better SSL support
|
Python
|
mit
|
klynch/python-logstash-handler
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
- def __init__(self, host, port, keyfile=None, certfile=None, ssl=True):
+ def __init__(self, host, port, keyfile=None, certfile=None, ca_certs=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
+ self.ca_certs = ca_certs
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
- return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile)
+ return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
Add support for CA certificates
|
## Code Before:
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
## Instruction:
Add support for CA certificates
## Code After:
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ca_certs=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ca_certs = ca_certs
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
- def __init__(self, host, port, keyfile=None, certfile=None, ssl=True):
+ def __init__(self, host, port, keyfile=None, certfile=None, ca_certs=None, ssl=True):
? +++++++++++++++
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
+ self.ca_certs = ca_certs
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
- return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile)
+ return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs)
? ++++++++++++++++++++++++
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.