commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d46df1680e3d799971e73ec73043c2a6c0590ce | scripts/build_tar.py | scripts/build_tar.py | import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith(".pyc"):
continue
if _is_file_newer(os.path.join(dirname, filename), file_mtime):
return True
return False
def _is_file_newer(filename, file_mtime):
return os.stat(filename).st_mtime > file_mtime
def _tar():
if 0 != subprocess.call("tar cvf {0} flask_app manage.py static".format(tarfile), shell=True, cwd=root_dir):
raise Exception("Tar failed")
if __name__ == '__main__':
if not os.path.exists(tarfile) or \
_is_dir_newer(os.path.join(root_dir, "flask_app"), tarfile) or \
_is_dir_newer(os.path.join(root_dir, "static"), tarfile) or \
_is_file_newer(os.path.join(root_dir, "manage.py"), os.stat(tarfile).st_mtime):
_tar()
| import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
if _is_file_newer(dirname, file_mtime):
return True
for filename in filenames:
if filename.endswith(".pyc"):
continue
if _is_file_newer(os.path.join(dirname, filename), file_mtime):
return True
return False
def _is_file_newer(filename, file_mtime):
returned = os.stat(filename).st_mtime > file_mtime
return returned
def _tar():
if 0 != subprocess.call("tar cvf {0} flask_app manage.py static".format(tarfile), shell=True, cwd=root_dir):
raise Exception("Tar failed")
if __name__ == '__main__':
if not os.path.exists(tarfile) or \
_is_dir_newer(os.path.join(root_dir, "flask_app"), tarfile) or \
_is_dir_newer(os.path.join(root_dir, "static"), tarfile) or \
_is_file_newer(os.path.join(root_dir, "manage.py"), os.stat(tarfile).st_mtime):
_tar()
| Fix building tar in deployment | Fix building tar in deployment
| Python | bsd-3-clause | vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,Infinidat/lanister,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,getslash/mailboxer | import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
+ if _is_file_newer(dirname, file_mtime):
+ return True
for filename in filenames:
if filename.endswith(".pyc"):
continue
if _is_file_newer(os.path.join(dirname, filename), file_mtime):
return True
return False
def _is_file_newer(filename, file_mtime):
- return os.stat(filename).st_mtime > file_mtime
+ returned = os.stat(filename).st_mtime > file_mtime
+ return returned
def _tar():
if 0 != subprocess.call("tar cvf {0} flask_app manage.py static".format(tarfile), shell=True, cwd=root_dir):
raise Exception("Tar failed")
if __name__ == '__main__':
if not os.path.exists(tarfile) or \
_is_dir_newer(os.path.join(root_dir, "flask_app"), tarfile) or \
_is_dir_newer(os.path.join(root_dir, "static"), tarfile) or \
_is_file_newer(os.path.join(root_dir, "manage.py"), os.stat(tarfile).st_mtime):
_tar()
| Fix building tar in deployment | ## Code Before:
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith(".pyc"):
continue
if _is_file_newer(os.path.join(dirname, filename), file_mtime):
return True
return False
def _is_file_newer(filename, file_mtime):
return os.stat(filename).st_mtime > file_mtime
def _tar():
if 0 != subprocess.call("tar cvf {0} flask_app manage.py static".format(tarfile), shell=True, cwd=root_dir):
raise Exception("Tar failed")
if __name__ == '__main__':
if not os.path.exists(tarfile) or \
_is_dir_newer(os.path.join(root_dir, "flask_app"), tarfile) or \
_is_dir_newer(os.path.join(root_dir, "static"), tarfile) or \
_is_file_newer(os.path.join(root_dir, "manage.py"), os.stat(tarfile).st_mtime):
_tar()
## Instruction:
Fix building tar in deployment
## Code After:
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
if _is_file_newer(dirname, file_mtime):
return True
for filename in filenames:
if filename.endswith(".pyc"):
continue
if _is_file_newer(os.path.join(dirname, filename), file_mtime):
return True
return False
def _is_file_newer(filename, file_mtime):
returned = os.stat(filename).st_mtime > file_mtime
return returned
def _tar():
if 0 != subprocess.call("tar cvf {0} flask_app manage.py static".format(tarfile), shell=True, cwd=root_dir):
raise Exception("Tar failed")
if __name__ == '__main__':
if not os.path.exists(tarfile) or \
_is_dir_newer(os.path.join(root_dir, "flask_app"), tarfile) or \
_is_dir_newer(os.path.join(root_dir, "static"), tarfile) or \
_is_file_newer(os.path.join(root_dir, "manage.py"), os.stat(tarfile).st_mtime):
_tar()
| ...
for dirname, _, filenames in os.walk(directory):
if _is_file_newer(dirname, file_mtime):
return True
for filename in filenames:
...
def _is_file_newer(filename, file_mtime):
returned = os.stat(filename).st_mtime > file_mtime
return returned
... |
373a172535db60e0b428500b1036decd97cf9504 | bookstore_app/urls.py | bookstore_app/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/', views.register, name='register'),
url(r'^login/', views.login, name='login')
] | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^books/([a-zA-Z0-9]+)/$', views.book, name='book')
] | Add book url route matcher | Add book url route matcher
| Python | mit | siawyoung/bookstore,siawyoung/bookstore,siawyoung/bookstore | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
- url(r'^register/', views.register, name='register'),
+ url(r'^register/$', views.register, name='register'),
- url(r'^login/', views.login, name='login')
+ url(r'^login/$', views.login, name='login'),
+ url(r'^books/([a-zA-Z0-9]+)/$', views.book, name='book')
] | Add book url route matcher | ## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/', views.register, name='register'),
url(r'^login/', views.login, name='login')
]
## Instruction:
Add book url route matcher
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^books/([a-zA-Z0-9]+)/$', views.book, name='book')
] | ...
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^books/([a-zA-Z0-9]+)/$', views.book, name='book')
]
... |
a5a92b81244076e8cf04c06398ce63a87d1357dd | adhocracy/tests/test_doctest_files.py | adhocracy/tests/test_doctest_files.py | from glob import glob
import doctest
from doctest import DocFileSuite
from os.path import dirname
import unittest
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
from adhocracy.tests.testbrowser import app_url, instance_url
from adhocracy.tests.testbrowser import Browser
def find_use_cases():
here = dirname(__file__)
paths = glob('{here}/use_cases/*.rst'.format(here=here))
# we need relative paths for DocFileSuite
pathes = [path.replace(here, '.') for path in paths]
return pathes
def make_browser():
return Browser(wsgi_app=ADHOCRACY_LAYER_APP)
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
globs = {"browser": make_browser(),
'make_browser': make_browser,
"app": ADHOCRACY_LAYER_APP,
"app_url": app_url,
"instance_url": instance_url
}
use_cases = find_use_cases()
class DoctestTestCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_suite(self):
return DocFileSuite(
*use_cases,
#add here aditional testfiles
setUp=ADHOCRACY_LAYER.setUp,
tearDown=ADHOCRACY_LAYER.tearDown,
globs=globs,
optionflags=flags
)
| from glob import glob
import doctest
from doctest import DocFileSuite
from os.path import dirname
import unittest
from adhocracy import model
from adhocracy.tests import testtools
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
from adhocracy.tests.testbrowser import app_url, instance_url
from adhocracy.tests.testbrowser import Browser
def find_use_cases():
here = dirname(__file__)
paths = glob('{here}/use_cases/*.rst'.format(here=here))
# we need relative paths for DocFileSuite
pathes = [path.replace(here, '.') for path in paths]
return pathes
def make_browser():
return Browser(wsgi_app=ADHOCRACY_LAYER_APP)
use_cases = find_use_cases()
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
globs = {"browser": make_browser(),
'make_browser': make_browser,
"app": ADHOCRACY_LAYER_APP,
"app_url": app_url,
"instance_url": instance_url,
'testtools': testtools,
'model': model
}
class DoctestTestCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_suite(self):
return DocFileSuite(
*use_cases,
#add here aditional testfiles
setUp=ADHOCRACY_LAYER.setUp,
tearDown=ADHOCRACY_LAYER.tearDown,
globs=globs,
optionflags=flags
)
| Add the modules models and testtools to the doctest globals | Add the modules models and testtools to the doctest globals
| Python | agpl-3.0 | SysTheron/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,alkadis/vcv,SysTheron/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,SysTheron/adhocracy,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,liqd/adhocracy,DanielNeugebauer/adhocracy | from glob import glob
import doctest
from doctest import DocFileSuite
from os.path import dirname
import unittest
+ from adhocracy import model
+ from adhocracy.tests import testtools
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
from adhocracy.tests.testbrowser import app_url, instance_url
from adhocracy.tests.testbrowser import Browser
def find_use_cases():
here = dirname(__file__)
paths = glob('{here}/use_cases/*.rst'.format(here=here))
# we need relative paths for DocFileSuite
pathes = [path.replace(here, '.') for path in paths]
return pathes
def make_browser():
return Browser(wsgi_app=ADHOCRACY_LAYER_APP)
+ use_cases = find_use_cases()
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
globs = {"browser": make_browser(),
'make_browser': make_browser,
"app": ADHOCRACY_LAYER_APP,
"app_url": app_url,
- "instance_url": instance_url
+ "instance_url": instance_url,
+ 'testtools': testtools,
+ 'model': model
}
- use_cases = find_use_cases()
class DoctestTestCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_suite(self):
return DocFileSuite(
*use_cases,
#add here aditional testfiles
setUp=ADHOCRACY_LAYER.setUp,
tearDown=ADHOCRACY_LAYER.tearDown,
globs=globs,
optionflags=flags
)
| Add the modules models and testtools to the doctest globals | ## Code Before:
from glob import glob
import doctest
from doctest import DocFileSuite
from os.path import dirname
import unittest
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
from adhocracy.tests.testbrowser import app_url, instance_url
from adhocracy.tests.testbrowser import Browser
def find_use_cases():
here = dirname(__file__)
paths = glob('{here}/use_cases/*.rst'.format(here=here))
# we need relative paths for DocFileSuite
pathes = [path.replace(here, '.') for path in paths]
return pathes
def make_browser():
return Browser(wsgi_app=ADHOCRACY_LAYER_APP)
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
globs = {"browser": make_browser(),
'make_browser': make_browser,
"app": ADHOCRACY_LAYER_APP,
"app_url": app_url,
"instance_url": instance_url
}
use_cases = find_use_cases()
class DoctestTestCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_suite(self):
return DocFileSuite(
*use_cases,
#add here aditional testfiles
setUp=ADHOCRACY_LAYER.setUp,
tearDown=ADHOCRACY_LAYER.tearDown,
globs=globs,
optionflags=flags
)
## Instruction:
Add the modules models and testtools to the doctest globals
## Code After:
from glob import glob
import doctest
from doctest import DocFileSuite
from os.path import dirname
import unittest
from adhocracy import model
from adhocracy.tests import testtools
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
from adhocracy.tests.testbrowser import app_url, instance_url
from adhocracy.tests.testbrowser import Browser
def find_use_cases():
here = dirname(__file__)
paths = glob('{here}/use_cases/*.rst'.format(here=here))
# we need relative paths for DocFileSuite
pathes = [path.replace(here, '.') for path in paths]
return pathes
def make_browser():
return Browser(wsgi_app=ADHOCRACY_LAYER_APP)
use_cases = find_use_cases()
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
globs = {"browser": make_browser(),
'make_browser': make_browser,
"app": ADHOCRACY_LAYER_APP,
"app_url": app_url,
"instance_url": instance_url,
'testtools': testtools,
'model': model
}
class DoctestTestCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_suite(self):
return DocFileSuite(
*use_cases,
#add here aditional testfiles
setUp=ADHOCRACY_LAYER.setUp,
tearDown=ADHOCRACY_LAYER.tearDown,
globs=globs,
optionflags=flags
)
| # ... existing code ...
from adhocracy import model
from adhocracy.tests import testtools
from adhocracy.tests.testbrowser import ADHOCRACY_LAYER, ADHOCRACY_LAYER_APP
# ... modified code ...
use_cases = find_use_cases()
flags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
...
"app_url": app_url,
"instance_url": instance_url,
'testtools': testtools,
'model': model
}
# ... rest of the code ... |
039f6fa4b26b747432138a8bf9e2754c6daafec3 | byceps/blueprints/api/decorators.py | byceps/blueprints/api/decorators.py |
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
def api_token_required(func):
"""Ensure the request is authenticated via API token."""
@wraps(func)
def wrapper(*args, **kwargs):
if not _has_valid_api_token():
www_authenticate = WWWAuthenticate('Bearer')
abort(401, www_authenticate=www_authenticate)
return func(*args, **kwargs)
return wrapper
def _has_valid_api_token() -> bool:
request_token = _extract_token_from_request()
if request_token is None:
return False
api_token = api_service.find_api_token_by_token(request_token)
return api_token is not None and not api_token.suspended
def _extract_token_from_request() -> Optional[str]:
header_value = request.headers.get('Authorization')
if header_value is None:
return None
return header_value.replace('Bearer ', '', 1)
|
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
from ...services.authentication.api.transfer.models import ApiToken
def api_token_required(func):
"""Ensure the request is authenticated via API token."""
@wraps(func)
def wrapper(*args, **kwargs):
api_token = _find_valid_api_token()
if api_token is None:
www_authenticate = WWWAuthenticate('Bearer')
abort(401, www_authenticate=www_authenticate)
if api_token.suspended:
www_authenticate = WWWAuthenticate('Bearer')
www_authenticate['error'] = 'invalid_token'
abort(401, www_authenticate=www_authenticate)
return func(*args, **kwargs)
return wrapper
def _find_valid_api_token() -> Optional[ApiToken]:
request_token = _extract_token_from_request()
if request_token is None:
return None
return api_service.find_api_token_by_token(request_token)
def _extract_token_from_request() -> Optional[str]:
header_value = request.headers.get('Authorization')
if header_value is None:
return None
return header_value.replace('Bearer ', '', 1)
| Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended | Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
+ from ...services.authentication.api.transfer.models import ApiToken
def api_token_required(func):
"""Ensure the request is authenticated via API token."""
@wraps(func)
def wrapper(*args, **kwargs):
- if not _has_valid_api_token():
+ api_token = _find_valid_api_token()
+
+ if api_token is None:
www_authenticate = WWWAuthenticate('Bearer')
abort(401, www_authenticate=www_authenticate)
+
+ if api_token.suspended:
+ www_authenticate = WWWAuthenticate('Bearer')
+ www_authenticate['error'] = 'invalid_token'
+ abort(401, www_authenticate=www_authenticate)
+
return func(*args, **kwargs)
return wrapper
- def _has_valid_api_token() -> bool:
+ def _find_valid_api_token() -> Optional[ApiToken]:
request_token = _extract_token_from_request()
if request_token is None:
- return False
+ return None
- api_token = api_service.find_api_token_by_token(request_token)
+ return api_service.find_api_token_by_token(request_token)
- return api_token is not None and not api_token.suspended
def _extract_token_from_request() -> Optional[str]:
header_value = request.headers.get('Authorization')
if header_value is None:
return None
return header_value.replace('Bearer ', '', 1)
| Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended | ## Code Before:
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
def api_token_required(func):
"""Ensure the request is authenticated via API token."""
@wraps(func)
def wrapper(*args, **kwargs):
if not _has_valid_api_token():
www_authenticate = WWWAuthenticate('Bearer')
abort(401, www_authenticate=www_authenticate)
return func(*args, **kwargs)
return wrapper
def _has_valid_api_token() -> bool:
request_token = _extract_token_from_request()
if request_token is None:
return False
api_token = api_service.find_api_token_by_token(request_token)
return api_token is not None and not api_token.suspended
def _extract_token_from_request() -> Optional[str]:
header_value = request.headers.get('Authorization')
if header_value is None:
return None
return header_value.replace('Bearer ', '', 1)
## Instruction:
Add `invalid_token` error to `WWW-Authenticate` header if API token is suspended
## Code After:
from functools import wraps
from typing import Optional
from flask import abort, request
from werkzeug.datastructures import WWWAuthenticate
from ...services.authentication.api import service as api_service
from ...services.authentication.api.transfer.models import ApiToken
def api_token_required(func):
"""Ensure the request is authenticated via API token."""
@wraps(func)
def wrapper(*args, **kwargs):
api_token = _find_valid_api_token()
if api_token is None:
www_authenticate = WWWAuthenticate('Bearer')
abort(401, www_authenticate=www_authenticate)
if api_token.suspended:
www_authenticate = WWWAuthenticate('Bearer')
www_authenticate['error'] = 'invalid_token'
abort(401, www_authenticate=www_authenticate)
return func(*args, **kwargs)
return wrapper
def _find_valid_api_token() -> Optional[ApiToken]:
request_token = _extract_token_from_request()
if request_token is None:
return None
return api_service.find_api_token_by_token(request_token)
def _extract_token_from_request() -> Optional[str]:
header_value = request.headers.get('Authorization')
if header_value is None:
return None
return header_value.replace('Bearer ', '', 1)
| // ... existing code ...
from ...services.authentication.api import service as api_service
from ...services.authentication.api.transfer.models import ApiToken
// ... modified code ...
def wrapper(*args, **kwargs):
api_token = _find_valid_api_token()
if api_token is None:
www_authenticate = WWWAuthenticate('Bearer')
...
abort(401, www_authenticate=www_authenticate)
if api_token.suspended:
www_authenticate = WWWAuthenticate('Bearer')
www_authenticate['error'] = 'invalid_token'
abort(401, www_authenticate=www_authenticate)
return func(*args, **kwargs)
...
def _find_valid_api_token() -> Optional[ApiToken]:
request_token = _extract_token_from_request()
...
if request_token is None:
return None
return api_service.find_api_token_by_token(request_token)
// ... rest of the code ... |
b11ef81b180cc18acb44988f3e269af6b54f4c89 | timewreport/interval.py | timewreport/interval.py | import dateutil.parser
from datetime import datetime
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return datetime(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
| import dateutil.parser
from datetime import datetime, date
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return date(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
| Make get_date() return date object instead of datetime | Make get_date() return date object instead of datetime
| Python | mit | lauft/timew-report | import dateutil.parser
- from datetime import datetime
+ from datetime import datetime, date
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
- return datetime(self.__start.year, self.__start.month, self.__start.day)
+ return date(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
| Make get_date() return date object instead of datetime | ## Code Before:
import dateutil.parser
from datetime import datetime
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return datetime(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
## Instruction:
Make get_date() return date object instead of datetime
## Code After:
import dateutil.parser
from datetime import datetime, date
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return date(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
| ...
from datetime import datetime, date
from dateutil.tz import tz
...
def get_date(self):
return date(self.__start.year, self.__start.month, self.__start.day)
... |
fbf42c288a6faa13ac918047eac09985cbd6f6e0 | cal/v1/network/drivers/openstack_network.py | cal/v1/network/drivers/openstack_network.py |
from neutronclient.v2_0 import client
from network_driver import NetworkDriver
class OpenstackNetWorkDriver(NetworkDriver):
"""docstring for OpenstackNetWorkDriver"""
def __init__(self, auth_url, project_name,
username, password, user_domain_name=None,
project_domain_name=None, driver_name=None):
super(OpenstackNetWorkDriver, self).__init__()
self.provider = "OPENSTACK"
self.auth_url = auth_url
self.project_domain_name = project_domain_name
self.user_domain_name = user_domain_name
self.project_name = project_name
self.username = username
self.password = password
if driver_name:
self.driver_name = driver_name
else:
self.driver_name = "default"
self._setup()
def _setup(self):
self.client = client.Client(
username=self.username,
password=self.password,
tenant_name=self.project_name,
auth_url=self.auth_url
)
def create(self):
raise NotImplementedError
def show(self):
raise NotImplementedError
def list(self):
raise NotImplementedError
def update(self):
raise NotImplementedError
def delete(self):
raise NotImplementedError
|
from neutronclient.v2_0 import client
from network_driver import NetworkDriver
class OpenstackNetWorkDriver(NetworkDriver):
"""docstring for OpenstackNetWorkDriver"""
def __init__(self, auth_url, project_name,
username, password, **kargs):
super(OpenstackNetWorkDriver, self).__init__()
self.provider = "OPENSTACK"
self.auth_url = auth_url
self.project_name = project_name
self.username = username
self.password = password
self.driver_name = kargs.pop('driver_name', 'default')
self._setup()
def _setup(self):
self.client = client.Client(
username=self.username,
password=self.password,
project_name=self.project_name,
auth_url=self.auth_url
)
def create(self, network):
return self.client.create_network({'network': network})
def show(self, network_id):
return self.client.show_network(network_id)
def list(self, retrieve_all=True, **kargs):
return self.client.list_networks(retrieve_all, **kargs)
def update(self, network_id, network):
return self.client.update_network(network_id, {'network': network})
def delete(self, network_id):
return self.client.delete_network(network_id)
| Add neutron client without test | Add neutron client without test
| Python | apache-2.0 | cloudcomputinghust/CAL |
from neutronclient.v2_0 import client
from network_driver import NetworkDriver
class OpenstackNetWorkDriver(NetworkDriver):
+
"""docstring for OpenstackNetWorkDriver"""
def __init__(self, auth_url, project_name,
+ username, password, **kargs):
- username, password, user_domain_name=None,
- project_domain_name=None, driver_name=None):
super(OpenstackNetWorkDriver, self).__init__()
self.provider = "OPENSTACK"
self.auth_url = auth_url
- self.project_domain_name = project_domain_name
- self.user_domain_name = user_domain_name
self.project_name = project_name
self.username = username
self.password = password
+ self.driver_name = kargs.pop('driver_name', 'default')
- if driver_name:
- self.driver_name = driver_name
- else:
- self.driver_name = "default"
-
self._setup()
def _setup(self):
self.client = client.Client(
username=self.username,
password=self.password,
- tenant_name=self.project_name,
+ project_name=self.project_name,
auth_url=self.auth_url
)
- def create(self):
+ def create(self, network):
- raise NotImplementedError
+ return self.client.create_network({'network': network})
- def show(self):
+ def show(self, network_id):
- raise NotImplementedError
+ return self.client.show_network(network_id)
- def list(self):
- raise NotImplementedError
+ def list(self, retrieve_all=True, **kargs):
+ return self.client.list_networks(retrieve_all, **kargs)
- def update(self):
- raise NotImplementedError
+ def update(self, network_id, network):
+ return self.client.update_network(network_id, {'network': network})
- def delete(self):
+ def delete(self, network_id):
- raise NotImplementedError
+ return self.client.delete_network(network_id)
| Add neutron client without test | ## Code Before:
from neutronclient.v2_0 import client
from network_driver import NetworkDriver
class OpenstackNetWorkDriver(NetworkDriver):
"""docstring for OpenstackNetWorkDriver"""
def __init__(self, auth_url, project_name,
username, password, user_domain_name=None,
project_domain_name=None, driver_name=None):
super(OpenstackNetWorkDriver, self).__init__()
self.provider = "OPENSTACK"
self.auth_url = auth_url
self.project_domain_name = project_domain_name
self.user_domain_name = user_domain_name
self.project_name = project_name
self.username = username
self.password = password
if driver_name:
self.driver_name = driver_name
else:
self.driver_name = "default"
self._setup()
def _setup(self):
self.client = client.Client(
username=self.username,
password=self.password,
tenant_name=self.project_name,
auth_url=self.auth_url
)
def create(self):
raise NotImplementedError
def show(self):
raise NotImplementedError
def list(self):
raise NotImplementedError
def update(self):
raise NotImplementedError
def delete(self):
raise NotImplementedError
## Instruction:
Add neutron client without test
## Code After:
from neutronclient.v2_0 import client
from network_driver import NetworkDriver
class OpenstackNetWorkDriver(NetworkDriver):
"""docstring for OpenstackNetWorkDriver"""
def __init__(self, auth_url, project_name,
username, password, **kargs):
super(OpenstackNetWorkDriver, self).__init__()
self.provider = "OPENSTACK"
self.auth_url = auth_url
self.project_name = project_name
self.username = username
self.password = password
self.driver_name = kargs.pop('driver_name', 'default')
self._setup()
def _setup(self):
self.client = client.Client(
username=self.username,
password=self.password,
project_name=self.project_name,
auth_url=self.auth_url
)
def create(self, network):
return self.client.create_network({'network': network})
def show(self, network_id):
return self.client.show_network(network_id)
def list(self, retrieve_all=True, **kargs):
return self.client.list_networks(retrieve_all, **kargs)
def update(self, network_id, network):
return self.client.update_network(network_id, {'network': network})
def delete(self, network_id):
return self.client.delete_network(network_id)
| # ... existing code ...
class OpenstackNetWorkDriver(NetworkDriver):
"""docstring for OpenstackNetWorkDriver"""
# ... modified code ...
def __init__(self, auth_url, project_name,
username, password, **kargs):
super(OpenstackNetWorkDriver, self).__init__()
...
self.auth_url = auth_url
self.project_name = project_name
...
self.password = password
self.driver_name = kargs.pop('driver_name', 'default')
self._setup()
...
password=self.password,
project_name=self.project_name,
auth_url=self.auth_url
...
def create(self, network):
return self.client.create_network({'network': network})
def show(self, network_id):
return self.client.show_network(network_id)
def list(self, retrieve_all=True, **kargs):
return self.client.list_networks(retrieve_all, **kargs)
def update(self, network_id, network):
return self.client.update_network(network_id, {'network': network})
def delete(self, network_id):
return self.client.delete_network(network_id)
# ... rest of the code ... |
79f7d8052333fcace914fa27ea2deb5f0d7cdbfc | readers/models.py | readers/models.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| Make what reader can handle what clearer | Make what reader can handle what clearer
| Python | mit | phildini/bockus,phildini/bockus,phildini/bockus | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
- (IBOOKS, IBOOKS),
- (KINDLE, KINDLE),
+ (IBOOKS, 'iBooks (.epub, .pdf)'),
+ (KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| Make what reader can handle what clearer | ## Code Before:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
## Instruction:
Make what reader can handle what clearer
## Code After:
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| # ... existing code ...
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
# ... rest of the code ... |
694651b5c143e4ce1fd3de25500909c1a16faf95 | api/podcasts/controller.py | api/podcasts/controller.py | from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> list[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| from typing import List
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| Fix typehint that is invalid in python 3.8 | Fix typehint that is invalid in python 3.8
| Python | mit | urfonline/api,urfonline/api,urfonline/api | + from typing import List
+
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
- def fetch_cached_podcasts() -> list[PodcastDetails]:
+ def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| Fix typehint that is invalid in python 3.8 | ## Code Before:
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> list[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
## Instruction:
Fix typehint that is invalid in python 3.8
## Code After:
from typing import List
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| ...
from typing import List
from django.core.cache import cache
...
def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
... |
f10d443eda1e8727c48439cc7c9491178a1ac4c8 | performance_testing/result.py | performance_testing/result.py | import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
name = '%d-%d-%d_%d-%d-%d' % (
date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second)
self.file = File(directory, name)
class File:
def __init__(self, directory, name):
if not os.path.exists(directory):
os.makedirs(directory)
self.path = os.path.join(directory, name)
if not os.path.exists(self.path):
open(self.path, 'w').close()
def write_line(self, text):
stream = open(self.path, 'a')
stream.write('%s\n' % text)
stream.close()
| import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S'))
class File:
def __init__(self, directory, name):
if not os.path.exists(directory):
os.makedirs(directory)
self.path = os.path.join(directory, name)
if not os.path.exists(self.path):
open(self.path, 'w').close()
def write_line(self, text):
stream = open(self.path, 'a')
stream.write('%s\n' % text)
stream.close()
| Use date-format function for file-name | Use date-format function for file-name
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
+ self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S'))
- name = '%d-%d-%d_%d-%d-%d' % (
- date.year,
- date.month,
- date.day,
- date.hour,
- date.minute,
- date.second)
- self.file = File(directory, name)
class File:
def __init__(self, directory, name):
if not os.path.exists(directory):
os.makedirs(directory)
self.path = os.path.join(directory, name)
if not os.path.exists(self.path):
open(self.path, 'w').close()
def write_line(self, text):
stream = open(self.path, 'a')
stream.write('%s\n' % text)
stream.close()
| Use date-format function for file-name | ## Code Before:
import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
name = '%d-%d-%d_%d-%d-%d' % (
date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second)
self.file = File(directory, name)
class File:
def __init__(self, directory, name):
if not os.path.exists(directory):
os.makedirs(directory)
self.path = os.path.join(directory, name)
if not os.path.exists(self.path):
open(self.path, 'w').close()
def write_line(self, text):
stream = open(self.path, 'a')
stream.write('%s\n' % text)
stream.close()
## Instruction:
Use date-format function for file-name
## Code After:
import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S'))
class File:
def __init__(self, directory, name):
if not os.path.exists(directory):
os.makedirs(directory)
self.path = os.path.join(directory, name)
if not os.path.exists(self.path):
open(self.path, 'w').close()
def write_line(self, text):
stream = open(self.path, 'a')
stream.write('%s\n' % text)
stream.close()
| ...
date = datetime.fromtimestamp(time())
self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S'))
... |
dc60ed6efdd4eb9a78e29623acee7505f2d864e6 | Lib/test/test_fork1.py | Lib/test/test_fork1.py |
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(4):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(4)
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
pid = os.getpid()
for key in alive.keys():
if alive[key] == pid:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
|
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| Use a constant to specify the number of child threads to create. | Use a constant to specify the number of child threads to create.
Instead of assuming that the number process ids of the threads is the
same as the process id of the controlling process, use a copy of the
dictionary and check for changes in the process ids of the threads
from the thread's process ids in the parent process. This makes the
test make more sense on systems which assign a new pid to each thread
(i.e., Linux).
This doesn't fix the other problems evident with this test on Linux.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
+
+ NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
- for i in range(4):
+ for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
- assert a == range(4)
+ assert a == range(NUM_THREADS)
+
+ prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
- pid = os.getpid()
for key in alive.keys():
- if alive[key] == pid:
+ if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| Use a constant to specify the number of child threads to create. | ## Code Before:
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(4):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(4)
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
pid = os.getpid()
for key in alive.keys():
if alive[key] == pid:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
## Instruction:
Use a constant to specify the number of child threads to create.
## Code After:
import os, sys, time, thread
LONGSLEEP = 2
SHORTSLEEP = 0.5
NUM_THREADS = 4
alive = {}
def f(id):
while 1:
alive[id] = os.getpid()
try:
time.sleep(SHORTSLEEP)
except IOError:
pass
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
time.sleep(LONGSLEEP)
a = alive.keys()
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
cpid = os.fork()
if cpid == 0:
# Child
time.sleep(LONGSLEEP)
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
os._exit(n)
else:
# Parent
spid, status = os.waitpid(cpid, 0)
assert spid == cpid
assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
main()
| # ... existing code ...
SHORTSLEEP = 0.5
NUM_THREADS = 4
# ... modified code ...
def main():
for i in range(NUM_THREADS):
thread.start_new(f, (i,))
...
a.sort()
assert a == range(NUM_THREADS)
prefork_lives = alive.copy()
...
n = 0
for key in alive.keys():
if alive[key] != prefork_lives[key]:
n = n+1
# ... rest of the code ... |
4304409d6f6028cb5f22edd97b8ecffa197dd9ed | server.py | server.py | import asyncio
import logging
# https://pypi.python.org/pypi/websockets
import websockets
clients = set()
logging.basicConfig(level=logging.INFO)
@asyncio.coroutine
def chat(websocket, uri):
clients.add(websocket)
while True:
msg = yield from websocket.recv()
if msg is None:
return
print(msg)
for client in clients.copy():
if client is not websocket:
try:
yield from client.send(msg)
except websockets.exceptions.InvalidState:
clients.remove(client)
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
| import asyncio
import logging
# https://pypi.python.org/pypi/websockets
import websockets
clients = set()
logging.basicConfig(level=logging.INFO)
@asyncio.coroutine
def chat(websocket, uri):
clients.add(websocket)
while True:
msg = yield from websocket.recv()
if msg is None:
return
print(msg)
for client in clients.copy():
if client is not websocket:
try:
yield from client.send(msg)
except websockets.exceptions.InvalidState:
clients.remove(client)
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.Task(start_server)
asyncio.get_event_loop().run_forever()
| Use Task instead of run_until_complete | Use Task instead of run_until_complete
| Python | unlicense | ajdavis/asyncio-chat-example,ajdavis/asyncio-chat-example | import asyncio
import logging
# https://pypi.python.org/pypi/websockets
import websockets
clients = set()
logging.basicConfig(level=logging.INFO)
@asyncio.coroutine
def chat(websocket, uri):
clients.add(websocket)
while True:
msg = yield from websocket.recv()
if msg is None:
return
print(msg)
for client in clients.copy():
if client is not websocket:
try:
yield from client.send(msg)
except websockets.exceptions.InvalidState:
clients.remove(client)
start_server = websockets.serve(chat, 'localhost', 8765)
- asyncio.get_event_loop().run_until_complete(start_server)
+ asyncio.Task(start_server)
asyncio.get_event_loop().run_forever()
| Use Task instead of run_until_complete | ## Code Before:
import asyncio
import logging
# https://pypi.python.org/pypi/websockets
import websockets
clients = set()
logging.basicConfig(level=logging.INFO)
@asyncio.coroutine
def chat(websocket, uri):
clients.add(websocket)
while True:
msg = yield from websocket.recv()
if msg is None:
return
print(msg)
for client in clients.copy():
if client is not websocket:
try:
yield from client.send(msg)
except websockets.exceptions.InvalidState:
clients.remove(client)
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
## Instruction:
Use Task instead of run_until_complete
## Code After:
import asyncio
import logging
# https://pypi.python.org/pypi/websockets
import websockets
clients = set()
logging.basicConfig(level=logging.INFO)
@asyncio.coroutine
def chat(websocket, uri):
clients.add(websocket)
while True:
msg = yield from websocket.recv()
if msg is None:
return
print(msg)
for client in clients.copy():
if client is not websocket:
try:
yield from client.send(msg)
except websockets.exceptions.InvalidState:
clients.remove(client)
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.Task(start_server)
asyncio.get_event_loop().run_forever()
| # ... existing code ...
start_server = websockets.serve(chat, 'localhost', 8765)
asyncio.Task(start_server)
asyncio.get_event_loop().run_forever()
# ... rest of the code ... |
da01999b6adcb79955a416ce3b3de50769adfe34 | opps/core/utils.py | opps/core/utils.py |
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
|
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| Add new module, get template path return absolut file path | Add new module, get template path
return absolut file path
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps |
from django.db.models import get_models, get_app
+ from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
+
+ def get_template_path(path):
+ try:
+ template = loader.find_template(path)
+ if template[1]:
+ return template[1].name
+ for template_loader in loader.template_source_loaders:
+ try:
+ source, origin = template_loader.load_template_source(path)
+ return origin
+ except TemplateDoesNotExist:
+ pass
+ raise TemplateDoesNotExist(path)
+ except TemplateDoesNotExist:
+ return None
+ | Add new module, get template path return absolut file path | ## Code Before:
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
## Instruction:
Add new module, get template path return absolut file path
## Code After:
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| // ... existing code ...
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
// ... modified code ...
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
// ... rest of the code ... |
c1f8d5817b8c94b422c0d454dcc0fa3c00e751b6 | activelink/tests/urls.py | activelink/tests/urls.py | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
)
| from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
]
if DJANGO_VERSION < (1, 10):
urlpatterns = patterns('', *urlpatterns)
| Add support for Django 1.11 | Add support for Django 1.11
| Python | unlicense | j4mie/django-activelink | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
+
+ if DJANGO_VERSION >= (1, 10):
+ from django.conf.urls import url
- if DJANGO_VERSION >= (1, 6):
+ elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
- )
+ ]
+ if DJANGO_VERSION < (1, 10):
+ urlpatterns = patterns('', *urlpatterns)
+ | Add support for Django 1.11 | ## Code Before:
from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
)
## Instruction:
Add support for Django 1.11
## Code After:
from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
]
if DJANGO_VERSION < (1, 10):
urlpatterns = patterns('', *urlpatterns)
| ...
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
...
urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
...
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
]
if DJANGO_VERSION < (1, 10):
urlpatterns = patterns('', *urlpatterns)
... |
1daf5825580d31e3f2825b5b5edfaa2aed8146fe | mopidy/internal/gi.py | mopidy/internal/gi.py | from __future__ import absolute_import, unicode_literals
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
| from __future__ import absolute_import, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
REQUIRED_GST_VERSION = (1, 2)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
| Check GStreamer version on start | gst1: Check GStreamer version on start
If GStreamer is too old, it fails like this:
$ mopidy
ERROR: Mopidy requires GStreamer >= 1.2, but found GStreamer 1.0.0.
| Python | apache-2.0 | kingosticks/mopidy,jodal/mopidy,mokieyue/mopidy,tkem/mopidy,kingosticks/mopidy,tkem/mopidy,mokieyue/mopidy,adamcik/mopidy,adamcik/mopidy,jodal/mopidy,mopidy/mopidy,vrs01/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,tkem/mopidy,jodal/mopidy,jcass77/mopidy,mopidy/mopidy,adamcik/mopidy,tkem/mopidy,mokieyue/mopidy,jcass77/mopidy,ZenithDK/mopidy,vrs01/mopidy,kingosticks/mopidy,mopidy/mopidy,ZenithDK/mopidy,vrs01/mopidy,jcass77/mopidy,vrs01/mopidy,mokieyue/mopidy | from __future__ import absolute_import, unicode_literals
+ import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
+ REQUIRED_GST_VERSION = (1, 2)
+
+ if Gst.version() < REQUIRED_GST_VERSION:
+ sys.exit(
+ 'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
+ '.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
+
+
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
| Check GStreamer version on start | ## Code Before:
from __future__ import absolute_import, unicode_literals
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
## Instruction:
Check GStreamer version on start
## Code After:
from __future__ import absolute_import, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
REQUIRED_GST_VERSION = (1, 2)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
| ...
import sys
import textwrap
...
REQUIRED_GST_VERSION = (1, 2)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
... |
23675e41656cac48f390d97f065b36de39e27d58 | duckbot.py | duckbot.py | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
await bot.say('pretending to roll')
bot.run(duckbot_settings.TOKEN)
| import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
lower_bound = 1
upper_boundb = 6
await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
| Add a real roll command | Add a real roll command
| Python | mit | andrewlin16/duckbot,andrewlin16/duckbot | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
+ rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
- await bot.say('pretending to roll')
+ lower_bound = 1
+ upper_boundb = 6
+ await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
| Add a real roll command | ## Code Before:
import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
await bot.say('pretending to roll')
bot.run(duckbot_settings.TOKEN)
## Instruction:
Add a real roll command
## Code After:
import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
lower_bound = 1
upper_boundb = 6
await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
| // ... existing code ...
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
// ... modified code ...
async def roll():
lower_bound = 1
upper_boundb = 6
await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
// ... rest of the code ... |
b345c00b41ade2e12449566f7cb013a7bb8d078f | democracy/migrations/0032_add_language_code_to_comment.py | democracy/migrations/0032_add_language_code_to_comment.py | from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| Add literal dependency so migration 0031 won't fail if run in the wrong order | Add literal dependency so migration 0031 won't fail if run in the wrong order
| Python | mit | City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi | from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
+ # comment.save() database operations will require a recent user model with all the fields included
+ ('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| Add literal dependency so migration 0031 won't fail if run in the wrong order | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
## Instruction:
Add literal dependency so migration 0031 won't fail if run in the wrong order
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| // ... existing code ...
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
// ... rest of the code ... |
a07c3db369fec32507a7f51b96927bfe383597bc | tests/PexpectTestCase.py | tests/PexpectTestCase.py |
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <[email protected]>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print '\n', self.id(),
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
|
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <[email protected]>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
| Make test case base compatible with Python 3 | Make test case base compatible with Python 3
| Python | isc | Wakeupbuddy/pexpect,dongguangming/pexpect,nodish/pexpect,Depado/pexpect,bangi123/pexpect,bangi123/pexpect,Depado/pexpect,quatanium/pexpect,dongguangming/pexpect,bangi123/pexpect,nodish/pexpect,blink1073/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,dongguangming/pexpect,Wakeupbuddy/pexpect,crdoconnor/pexpect,blink1073/pexpect,quatanium/pexpect,crdoconnor/pexpect,Wakeupbuddy/pexpect,Depado/pexpect,nodish/pexpect,quatanium/pexpect,blink1073/pexpect,dongguangming/pexpect,bangi123/pexpect,crdoconnor/pexpect |
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <[email protected]>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
+ from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
- print '\n', self.id(),
+ print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
| Make test case base compatible with Python 3 | ## Code Before:
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <[email protected]>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print '\n', self.id(),
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
## Instruction:
Make test case base compatible with Python 3
## Code After:
'''
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier <[email protected]>
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
import unittest
import sys
import os
class PexpectTestCase(unittest.TestCase):
def setUp(self):
self.PYTHONBIN = sys.executable
self.original_path = os.getcwd()
newpath = os.path.join (os.environ['PROJECT_PEXPECT_HOME'], 'tests')
os.chdir (newpath)
print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
def tearDown(self):
os.chdir (self.original_path)
| // ... existing code ...
'''
from __future__ import print_function
// ... modified code ...
os.chdir (newpath)
print('\n', self.id(), end='')
unittest.TestCase.setUp(self)
// ... rest of the code ... |
6498d61ba18699a93689a52a43963e034b14ed84 | diecutter/utils/files.py | diecutter/utils/files.py | """Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(directory)
False
Deletion of temporary directory is recursive.
>>> with temporary_directory() as directory:
... filename = os.path.join(directory, 'sample.txt')
... __ = open(filename, 'w').close()
... os.path.isfile(filename)
True
>>> os.path.isfile(filename)
False
"""
def __enter__(self):
"""Create temporary directory and return its path."""
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
shutil.rmtree(self.path)
class chdir(object):
"""Context manager that change current working directory."""
def __init__(self, new_dir):
#: Remember previous value of os.getcwd().
self.previous_dir = os.getcwd()
#: New directory.
self.new_dir = new_dir
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
os.chdir(self.previous_dir)
| """Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(directory)
False
Deletion of temporary directory is recursive.
>>> with temporary_directory() as directory:
... filename = os.path.join(directory, 'sample.txt')
... __ = open(filename, 'w').close()
... os.path.isfile(filename)
True
>>> os.path.isfile(filename)
False
"""
def __enter__(self):
"""Create temporary directory and return its path."""
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
try:
shutil.rmtree(self.path)
except OSError:
pass
class chdir(object):
"""Context manager that change current working directory."""
def __init__(self, new_dir):
#: Remember previous value of os.getcwd().
self.previous_dir = os.getcwd()
#: New directory.
self.new_dir = new_dir
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
os.chdir(self.previous_dir)
| Fix tests on travis ci. | Fix tests on travis ci.
| Python | bsd-3-clause | diecutter/diecutter,diecutter/diecutter | """Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(directory)
False
Deletion of temporary directory is recursive.
>>> with temporary_directory() as directory:
... filename = os.path.join(directory, 'sample.txt')
... __ = open(filename, 'w').close()
... os.path.isfile(filename)
True
>>> os.path.isfile(filename)
False
"""
def __enter__(self):
"""Create temporary directory and return its path."""
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
+ try:
- shutil.rmtree(self.path)
+ shutil.rmtree(self.path)
+ except OSError:
+ pass
class chdir(object):
"""Context manager that change current working directory."""
def __init__(self, new_dir):
#: Remember previous value of os.getcwd().
self.previous_dir = os.getcwd()
#: New directory.
self.new_dir = new_dir
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
os.chdir(self.previous_dir)
| Fix tests on travis ci. | ## Code Before:
"""Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(directory)
False
Deletion of temporary directory is recursive.
>>> with temporary_directory() as directory:
... filename = os.path.join(directory, 'sample.txt')
... __ = open(filename, 'w').close()
... os.path.isfile(filename)
True
>>> os.path.isfile(filename)
False
"""
def __enter__(self):
"""Create temporary directory and return its path."""
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
shutil.rmtree(self.path)
class chdir(object):
"""Context manager that change current working directory."""
def __init__(self, new_dir):
#: Remember previous value of os.getcwd().
self.previous_dir = os.getcwd()
#: New directory.
self.new_dir = new_dir
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
os.chdir(self.previous_dir)
## Instruction:
Fix tests on travis ci.
## Code After:
"""Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(directory)
False
Deletion of temporary directory is recursive.
>>> with temporary_directory() as directory:
... filename = os.path.join(directory, 'sample.txt')
... __ = open(filename, 'w').close()
... os.path.isfile(filename)
True
>>> os.path.isfile(filename)
False
"""
def __enter__(self):
"""Create temporary directory and return its path."""
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
try:
shutil.rmtree(self.path)
except OSError:
pass
class chdir(object):
"""Context manager that change current working directory."""
def __init__(self, new_dir):
#: Remember previous value of os.getcwd().
self.previous_dir = os.getcwd()
#: New directory.
self.new_dir = new_dir
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
os.chdir(self.previous_dir)
| # ... existing code ...
"""Remove temporary directory recursively."""
try:
shutil.rmtree(self.path)
except OSError:
pass
# ... rest of the code ... |
05cf5f3729ffbceeb2436322b2aac5285d7228de | wsgi.py | wsgi.py |
import webapp
application = webapp.create_app()
|
import config
import webapp
application = webapp.create_app()
if config.REGISTRATION_IS_OPEN:
print(" * Registration is OPEN")
else:
print(" * Registration is NOT OPEN: pregistration code is '%s'" %
application.config['PREREGISTRATION_CODE'])
| Print registration code in WSGI app. | Print registration code in WSGI app.
Otherwise, how will we know what it is?
| Python | bsd-2-clause | trombonehero/nerf-herder,trombonehero/nerf-herder,trombonehero/nerf-herder |
+ import config
import webapp
+
application = webapp.create_app()
+ if config.REGISTRATION_IS_OPEN:
+ print(" * Registration is OPEN")
+ else:
+ print(" * Registration is NOT OPEN: pregistration code is '%s'" %
+ application.config['PREREGISTRATION_CODE'])
+ | Print registration code in WSGI app. | ## Code Before:
import webapp
application = webapp.create_app()
## Instruction:
Print registration code in WSGI app.
## Code After:
import config
import webapp
application = webapp.create_app()
if config.REGISTRATION_IS_OPEN:
print(" * Registration is OPEN")
else:
print(" * Registration is NOT OPEN: pregistration code is '%s'" %
application.config['PREREGISTRATION_CODE'])
| ...
import config
import webapp
application = webapp.create_app()
if config.REGISTRATION_IS_OPEN:
print(" * Registration is OPEN")
else:
print(" * Registration is NOT OPEN: pregistration code is '%s'" %
application.config['PREREGISTRATION_CODE'])
... |
f98b78fcf37e9d3e200c468b5a0bba25abdd13fd | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| from django.conf.urls import url
from django.contrib.auth.views import LoginView
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', LoginView.as_view()),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| Replace contrib.auth's "login" view with LoginView. | Replace contrib.auth's "login" view with LoginView.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.11/#id2
contrib.auth's login() and logout() function-based views are deprecated in favor of new class-based views LoginView and LogoutView.
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | from django.conf.urls import url
- from django.contrib.auth.views import login
+ from django.contrib.auth.views import LoginView
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
- url('^accounts/login/$', login),
+ url('^accounts/login/$', LoginView.as_view()),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| Replace contrib.auth's "login" view with LoginView. | ## Code Before:
from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
## Instruction:
Replace contrib.auth's "login" view with LoginView.
## Code After:
from django.conf.urls import url
from django.contrib.auth.views import LoginView
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', LoginView.as_view()),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| # ... existing code ...
from django.conf.urls import url
from django.contrib.auth.views import LoginView
# ... modified code ...
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', LoginView.as_view()),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
# ... rest of the code ... |
d731b4172592ef905101868b43817f25f5b04063 | virtstrap/exceptions.py | virtstrap/exceptions.py | class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
| class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
class RequirementsConfigError(Exception):
"""Exception for command configuration errors"""
pass
| Add a requirements configuration exception | Add a requirements configuration exception
| Python | mit | ravenac95/virtstrap-core,ravenac95/testvirtstrapdocs,ravenac95/virtstrap-core | class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
+ class RequirementsConfigError(Exception):
+ """Exception for command configuration errors"""
+ pass
+ | Add a requirements configuration exception | ## Code Before:
class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
## Instruction:
Add a requirements configuration exception
## Code After:
class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
class RequirementsConfigError(Exception):
"""Exception for command configuration errors"""
pass
| # ... existing code ...
pass
class RequirementsConfigError(Exception):
"""Exception for command configuration errors"""
pass
# ... rest of the code ... |
44be93c5efb334297fc1bb10eaafec197018b241 | python/render/render_tracks.py | python/render/render_tracks.py | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
| __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
| Update formatting on track labels | Update formatting on track labels
| Python | mit | Duke-GCB/TrackHubGenerator,Duke-GCB/TrackHubGenerator | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
- d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number'])
+ d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number'])
- d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier'])
+ d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
| Update formatting on track labels | ## Code Before:
__author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
## Instruction:
Update formatting on track labels
## Code After:
__author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width'])
return d
def render_tracks(assembly, metadata_file):
obj = yaml.load(metadata_file)
# Just pull out the assembly ones
tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly]
trackdb = {'tracks': tracks}
render_template(trackdb, 'trackDb')
def main():
parser = argparse.ArgumentParser(description='Render trackDb.txt')
parser.add_argument('--assembly')
parser.add_argument('metadata_file', type=argparse.FileType('r'))
args = parser.parse_args()
render_tracks(args.assembly, args.metadata_file)
if __name__ == '__main__':
main()
| ...
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number'])
d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width'])
return d
... |
89b7b7f7fe1ec50f1d0bdfba7581f76326efe717 | dacapo_analyzer.py | dacapo_analyzer.py | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| Use only msecs of dacapo output. | [client] Use only msecs of dacapo output.
Signed-off-by: Michael Markert <[email protected]>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
- WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
+ WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| Use only msecs of dacapo output. | ## Code Before:
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
## Instruction:
Use only msecs of dacapo output.
## Code After:
import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| ...
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
... |
185906c1afc2bc38f0a7282e2b22e49262a73f9b | south/models.py | south/models.py | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
| Python | apache-2.0 | smartfile/django-south,smartfile/django-south | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
-
- class Meta:
- unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | ## Code Before:
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
## Instruction:
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
## Code After:
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| // ... existing code ...
applied = models.DateTimeField(blank=True)
// ... rest of the code ... |
af6c260bb27f6b1c5f56ffbd0616b30b9afdbd7b | tests/user_utils_test.py | tests/user_utils_test.py | """Tests for user utility functions."""
from drudge import Vec, sum_, prod_
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
| """Tests for user utility functions."""
import time
import types
from unittest.mock import MagicMock
from drudge import Vec, sum_, prod_, TimeStamper
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
def test_time_stamper():
"""Test the time stamper utility."""
tensor = types.SimpleNamespace(n_terms=2, cache=MagicMock())
stamper = TimeStamper()
time.sleep(0.5)
res = stamper.stamp('Nothing')
assert res.startswith('Nothing done')
assert float(res.split()[-2]) - 0.5 < 0.1
time.sleep(0.5)
res = stamper.stamp('Tensor', tensor)
assert res.startswith('Tensor done, 2 terms')
assert float(res.split()[-2]) - 0.5 < 0.1
tensor.cache.assert_called_once_with()
| Add tests for the time stamping facility | Add tests for the time stamping facility
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge | """Tests for user utility functions."""
+ import time
+ import types
+ from unittest.mock import MagicMock
+
- from drudge import Vec, sum_, prod_
+ from drudge import Vec, sum_, prod_, TimeStamper
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
+
+ def test_time_stamper():
+ """Test the time stamper utility."""
+
+ tensor = types.SimpleNamespace(n_terms=2, cache=MagicMock())
+
+ stamper = TimeStamper()
+ time.sleep(0.5)
+ res = stamper.stamp('Nothing')
+ assert res.startswith('Nothing done')
+ assert float(res.split()[-2]) - 0.5 < 0.1
+
+ time.sleep(0.5)
+ res = stamper.stamp('Tensor', tensor)
+ assert res.startswith('Tensor done, 2 terms')
+ assert float(res.split()[-2]) - 0.5 < 0.1
+ tensor.cache.assert_called_once_with()
+ | Add tests for the time stamping facility | ## Code Before:
"""Tests for user utility functions."""
from drudge import Vec, sum_, prod_
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
## Instruction:
Add tests for the time stamping facility
## Code After:
"""Tests for user utility functions."""
import time
import types
from unittest.mock import MagicMock
from drudge import Vec, sum_, prod_, TimeStamper
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
def test_time_stamper():
"""Test the time stamper utility."""
tensor = types.SimpleNamespace(n_terms=2, cache=MagicMock())
stamper = TimeStamper()
time.sleep(0.5)
res = stamper.stamp('Nothing')
assert res.startswith('Nothing done')
assert float(res.split()[-2]) - 0.5 < 0.1
time.sleep(0.5)
res = stamper.stamp('Tensor', tensor)
assert res.startswith('Tensor done, 2 terms')
assert float(res.split()[-2]) - 0.5 < 0.1
tensor.cache.assert_called_once_with()
| // ... existing code ...
import time
import types
from unittest.mock import MagicMock
from drudge import Vec, sum_, prod_, TimeStamper
from drudge.term import parse_terms
// ... modified code ...
assert prod_([]) == 1
def test_time_stamper():
"""Test the time stamper utility."""
tensor = types.SimpleNamespace(n_terms=2, cache=MagicMock())
stamper = TimeStamper()
time.sleep(0.5)
res = stamper.stamp('Nothing')
assert res.startswith('Nothing done')
assert float(res.split()[-2]) - 0.5 < 0.1
time.sleep(0.5)
res = stamper.stamp('Tensor', tensor)
assert res.startswith('Tensor done, 2 terms')
assert float(res.split()[-2]) - 0.5 < 0.1
tensor.cache.assert_called_once_with()
// ... rest of the code ... |
9a1272082f8750565f727f2c97a71768a9ceb7ca | books/search_indexes.py | books/search_indexes.py | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all() | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified' | Add fields to index so 'update_index' works | Add fields to index so 'update_index' works
| Python | mit | phildini/bockus,phildini/bockus,phildini/bockus | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
+ def get_updated_field(self):
+ return 'modified'
+
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
+
+ def get_updated_field(self):
+ return 'modified' | Add fields to index so 'update_index' works | ## Code Before:
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
## Instruction:
Add fields to index so 'update_index' works
## Code After:
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified' | // ... existing code ...
def get_updated_field(self):
return 'modified'
// ... modified code ...
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
// ... rest of the code ... |
d5b5421c95b1e2feb4646a42b5aca71a2280e30c | tests/dojo_test.py | tests/dojo_test.py | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3) | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
def test_person_added_to_system(self):
initial_person_count = len(self.dojo.all_people)
person = self.dojo.add_person("Neil", "Armstrong", "Staff")
self.assertTrue(person)
new_person_count = len(self.dojo.all_people)
self.assertEqual(new_person_count - initial_person_count, 1) | Create test to check that a person has been added | Create test to check that a person has been added
| Python | mit | EdwinKato/Space-Allocator,EdwinKato/Space-Allocator | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
+
+ def test_person_added_to_system(self):
+ initial_person_count = len(self.dojo.all_people)
+ person = self.dojo.add_person("Neil", "Armstrong", "Staff")
+ self.assertTrue(person)
+ new_person_count = len(self.dojo.all_people)
+ self.assertEqual(new_person_count - initial_person_count, 1) | Create test to check that a person has been added | ## Code Before:
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
## Instruction:
Create test to check that a person has been added
## Code After:
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
def test_person_added_to_system(self):
initial_person_count = len(self.dojo.all_people)
person = self.dojo.add_person("Neil", "Armstrong", "Staff")
self.assertTrue(person)
new_person_count = len(self.dojo.all_people)
self.assertEqual(new_person_count - initial_person_count, 1) | // ... existing code ...
self.assertEqual(new_room_count - initial_room_count, 3)
def test_person_added_to_system(self):
initial_person_count = len(self.dojo.all_people)
person = self.dojo.add_person("Neil", "Armstrong", "Staff")
self.assertTrue(person)
new_person_count = len(self.dojo.all_people)
self.assertEqual(new_person_count - initial_person_count, 1)
// ... rest of the code ... |
707ded0f673f44b31d0762d8210a6b94074200e8 | troposphere/certificatemanager.py | troposphere/certificatemanager.py | from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
| Update AWS::CertificateManager::Certificate per 2020-06-11 changes | Update AWS::CertificateManager::Certificate per 2020-06-11 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | - from . import AWSObject, AWSProperty, Tags
+
+
+ from . import AWSObject
+ from . import AWSProperty
+ from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
+ 'HostedZoneId': (basestring, False),
- 'ValidationDomain': (basestring, True),
+ 'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
+ 'CertificateAuthorityArn': (basestring, False),
+ 'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
| Update AWS::CertificateManager::Certificate per 2020-06-11 changes | ## Code Before:
from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
## Instruction:
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
## Code After:
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
| // ... existing code ...
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
// ... modified code ...
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
...
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
// ... rest of the code ... |
c53824a3427235c814cfe35c5c85fd5e1e312b40 | i3/.config/i3/scripts/lock_screen/lock_screen.py | i3/.config/i3/scripts/lock_screen/lock_screen.py |
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
current_timeouts = dpms.GetTimeouts()
with mss() as sct:
# Get the "All-in-one" monitor
monitor = sct.monitors[0]
# Get raw pixels of the screen
sct_img = sct.grab(monitor)
# Create Image object using Pillow
img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
with NamedTemporaryFile(suffix=".png") as tempfile:
# Apply filters to Image
img = img.filter(ImageFilter.GaussianBlur(radius=GAUSSIAN_BLUR_RADIUS))
# Save temporary file
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
dpms.GetTimeouts()
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
except CalledProcessError:
# Something went wrong, lock it anyway
check_call(["i3lock", "-ne"])
finally:
# Restore DPMS settings
dpms.SetTimeouts(*current_timeouts)
dpms.GetTimeouts()
|
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
current_timeouts = dpms.GetTimeouts()
with mss() as sct:
# Get the "All-in-one" monitor
monitor = sct.monitors[0]
# Get raw pixels of the screen
sct_img = sct.grab(monitor)
# Create Image object using Pillow
img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
with NamedTemporaryFile(suffix=".png") as tempfile:
# Apply filters to Image
img = img.filter(ImageFilter.GaussianBlur(radius=GAUSSIAN_BLUR_RADIUS))
# Save temporary file
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
except CalledProcessError:
# Something went wrong, lock it anyway
check_call(["i3lock", "-ne"])
finally:
# Restore DPMS settings
dpms.SetTimeouts(*current_timeouts)
| Remove call to GetTimeouts() after SetTimeouts() | i3: Remove call to GetTimeouts() after SetTimeouts()
Fixed in commit 72e984a54049c77208546b8565cece100e87be48 from
m45t3r/python-dpms.
| Python | mit | m45t3r/dotfiles,m45t3r/dotfiles,m45t3r/dotfiles |
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
current_timeouts = dpms.GetTimeouts()
with mss() as sct:
# Get the "All-in-one" monitor
monitor = sct.monitors[0]
# Get raw pixels of the screen
sct_img = sct.grab(monitor)
# Create Image object using Pillow
img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
with NamedTemporaryFile(suffix=".png") as tempfile:
# Apply filters to Image
img = img.filter(ImageFilter.GaussianBlur(radius=GAUSSIAN_BLUR_RADIUS))
# Save temporary file
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
- dpms.GetTimeouts()
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
except CalledProcessError:
# Something went wrong, lock it anyway
check_call(["i3lock", "-ne"])
finally:
# Restore DPMS settings
dpms.SetTimeouts(*current_timeouts)
- dpms.GetTimeouts()
| Remove call to GetTimeouts() after SetTimeouts() | ## Code Before:
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
current_timeouts = dpms.GetTimeouts()
with mss() as sct:
# Get the "All-in-one" monitor
monitor = sct.monitors[0]
# Get raw pixels of the screen
sct_img = sct.grab(monitor)
# Create Image object using Pillow
img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
with NamedTemporaryFile(suffix=".png") as tempfile:
# Apply filters to Image
img = img.filter(ImageFilter.GaussianBlur(radius=GAUSSIAN_BLUR_RADIUS))
# Save temporary file
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
dpms.GetTimeouts()
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
except CalledProcessError:
# Something went wrong, lock it anyway
check_call(["i3lock", "-ne"])
finally:
# Restore DPMS settings
dpms.SetTimeouts(*current_timeouts)
dpms.GetTimeouts()
## Instruction:
Remove call to GetTimeouts() after SetTimeouts()
## Code After:
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
current_timeouts = dpms.GetTimeouts()
with mss() as sct:
# Get the "All-in-one" monitor
monitor = sct.monitors[0]
# Get raw pixels of the screen
sct_img = sct.grab(monitor)
# Create Image object using Pillow
img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
with NamedTemporaryFile(suffix=".png") as tempfile:
# Apply filters to Image
img = img.filter(ImageFilter.GaussianBlur(radius=GAUSSIAN_BLUR_RADIUS))
# Save temporary file
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
except CalledProcessError:
# Something went wrong, lock it anyway
check_call(["i3lock", "-ne"])
finally:
# Restore DPMS settings
dpms.SetTimeouts(*current_timeouts)
| # ... existing code ...
dpms.SetTimeouts(*SCREEN_TIMEOUT)
try:
# ... modified code ...
dpms.SetTimeouts(*current_timeouts)
# ... rest of the code ... |
19faa280c924254b960a8b9fcb716017e51db09f | pymks/tests/test_mksRegressionModel.py | pymks/tests/test_mksRegressionModel.py | from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
model.coeff = np.fft.ifft(model.Fcoeff, axis=0)
assert np.allclose(coeff, model.coeff)
if __name__ == '__main__':
test()
| from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
if __name__ == '__main__':
test()
| Fix test due to addition of coeff property | Fix test due to addition of coeff property
Address #49
Add fftshift to test coefficients as model.coeff now returns the
shifted real versions.
| Python | mit | davidbrough1/pymks,XinyiGong/pymks,awhite40/pymks,davidbrough1/pymks,fredhohman/pymks | from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
- model.coeff = np.fft.ifft(model.Fcoeff, axis=0)
- assert np.allclose(coeff, model.coeff)
+ assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
if __name__ == '__main__':
test()
| Fix test due to addition of coeff property | ## Code Before:
from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
model.coeff = np.fft.ifft(model.Fcoeff, axis=0)
assert np.allclose(coeff, model.coeff)
if __name__ == '__main__':
test()
## Instruction:
Fix test due to addition of coeff property
## Code After:
from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
if __name__ == '__main__':
test()
| ...
model.fit(X, y)
assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
... |
14ea472acfce8b5317a8c8c970db901501ea34c0 | _tests/macro_testing/runner.py | _tests/macro_testing/runner.py |
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(tests_path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
|
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
| Make the paths not relative, so tests can be run from anywhere. | Make the paths not relative, so tests can be run from anywhere.
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh |
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
+ path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
- json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
+ json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
- json_file_path = os.path.join(tests_path, json_file)
+ json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
| Make the paths not relative, so tests can be run from anywhere. | ## Code Before:
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
json_files = [f for f in os.listdir(tests_path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(tests_path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
## Instruction:
Make the paths not relative, so tests can be run from anywhere.
## Code After:
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This function will create a MacroTestCase subclass (using
JSONSpecMacrosTestCaseFactory) for each JSON file in the given path.
If `recursive` is True, it will also look in subdirectories. This is
not yet supported.
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# Create a camelcased name for the test. This is a minor thing, but I
# think it's nice.
name, extension = os.path.splitext(json_file)
class_name = ''.join(x for x in name.title() if x not in ' _-') + 'TestCase'
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# Add the test class to globals() so that unittest.main() picks it up
globals()[class_name] = test_class
if __name__ == '__main__':
JSONTestCaseLoader('./tests/')
unittest.main()
| # ... existing code ...
"""
path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), tests_path))
json_files = [f for f in os.listdir(path) if f.endswith('.json')]
for json_file in json_files:
# ... modified code ...
# Get the full path to the file and create a test class
json_file_path = os.path.join(path, json_file)
test_class = JSONSpecMacroTestCaseFactory(class_name, json_file_path)
# ... rest of the code ... |
c25d55643953d5bce511b1d3d32e6fce162b4ccd | hoptoad/tests.py | hoptoad/tests.py | from django.test import TestCase
from django.conf import settings
class BasicTests(TestCase):
"""Basic tests like setup and connectivity."""
def test_api_key_present(self):
self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(),
msg='The HOPTOAD_API_KEY setting is not present.')
self.assertTrue(settings.HOPTOAD_API_KEY,
msg='The HOPTOAD_API_KEY setting is blank.')
| import urllib2
from django.test import TestCase
from django.conf import settings
class BasicTests(TestCase):
"""Basic tests like setup and connectivity."""
def test_api_key_present(self):
self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(),
msg='The HOPTOAD_API_KEY setting is not present.')
self.assertTrue(settings.HOPTOAD_API_KEY,
msg='The HOPTOAD_API_KEY setting is blank.')
def test_hoptoad_connectivity(self):
try:
ht = urllib2.urlopen('http://hoptoadapp.com/')
except urllib2.HTTPError:
self.fail(msg='Could not reach hoptoadapp.com -- are you online?')
self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.')
| Add a unit test for hoptoadapp.com connectivity. | Add a unit test for hoptoadapp.com connectivity.
| Python | mit | sjl/django-hoptoad,sjl/django-hoptoad | + import urllib2
from django.test import TestCase
from django.conf import settings
class BasicTests(TestCase):
"""Basic tests like setup and connectivity."""
def test_api_key_present(self):
self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(),
msg='The HOPTOAD_API_KEY setting is not present.')
self.assertTrue(settings.HOPTOAD_API_KEY,
msg='The HOPTOAD_API_KEY setting is blank.')
+ def test_hoptoad_connectivity(self):
-
+ try:
+ ht = urllib2.urlopen('http://hoptoadapp.com/')
+ except urllib2.HTTPError:
+ self.fail(msg='Could not reach hoptoadapp.com -- are you online?')
+ self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.')
+
+ | Add a unit test for hoptoadapp.com connectivity. | ## Code Before:
from django.test import TestCase
from django.conf import settings
class BasicTests(TestCase):
"""Basic tests like setup and connectivity."""
def test_api_key_present(self):
self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(),
msg='The HOPTOAD_API_KEY setting is not present.')
self.assertTrue(settings.HOPTOAD_API_KEY,
msg='The HOPTOAD_API_KEY setting is blank.')
## Instruction:
Add a unit test for hoptoadapp.com connectivity.
## Code After:
import urllib2
from django.test import TestCase
from django.conf import settings
class BasicTests(TestCase):
"""Basic tests like setup and connectivity."""
def test_api_key_present(self):
self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(),
msg='The HOPTOAD_API_KEY setting is not present.')
self.assertTrue(settings.HOPTOAD_API_KEY,
msg='The HOPTOAD_API_KEY setting is blank.')
def test_hoptoad_connectivity(self):
try:
ht = urllib2.urlopen('http://hoptoadapp.com/')
except urllib2.HTTPError:
self.fail(msg='Could not reach hoptoadapp.com -- are you online?')
self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.')
| // ... existing code ...
import urllib2
from django.test import TestCase
// ... modified code ...
def test_hoptoad_connectivity(self):
try:
ht = urllib2.urlopen('http://hoptoadapp.com/')
except urllib2.HTTPError:
self.fail(msg='Could not reach hoptoadapp.com -- are you online?')
self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.')
// ... rest of the code ... |
56b4532bd330ad4075f882511c87cb97eaeff10e | jujupy/__init__.py | jujupy/__init__.py | from jujupy.client import *
from jujupy.client import _temp_env
__all__ = ['_temp_env']
| from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
| Switch to explicit imports for jujupy. | Switch to explicit imports for jujupy. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | - from jujupy.client import *
+ from jujupy.client import (
- from jujupy.client import _temp_env
+ AgentsNotStarted,
+ AuthNotAccepted,
+ AGENTS_READY,
+ client_from_config,
+ ConditionList,
+ coalesce_agent_status,
+ describe_substrate,
+ EnvJujuClient,
+ EnvJujuClient1X,
+ EnvJujuClient25,
+ ensure_dir,
+ get_cache_path,
+ get_client_class,
+ get_local_root,
+ get_machine_dns_name,
+ get_timeout_path,
+ get_timeout_prefix,
+ GroupReporter,
+ IncompatibleConfigClass,
+ InvalidEndpoint,
+ jes_home_path,
+ JESNotSupported,
+ JujuData,
+ JUJU_DEV_FEATURE_FLAGS,
+ Juju2Backend,
+ KILL_CONTROLLER,
+ KVM_MACHINE,
+ LXC_MACHINE,
+ LXD_MACHINE,
+ Machine,
+ NameNotAccepted,
+ NoProvider,
+ parse_new_state_server_from_error,
+ SimpleEnvironment,
+ SoftDeadlineExceeded,
+ Status,
+ temp_bootstrap_env,
+ _temp_env,
+ temp_yaml_file,
+ TypeNotAccepted,
+ uniquify_local,
+ until_timeout,
+ )
- __all__ = ['_temp_env']
+ __all__ = [
+ 'AgentsNotStarted',
+ 'AuthNotAccepted',
+ 'AGENTS_READY',
+ 'client_from_config',
+ 'ConditionList',
+ 'coalesce_agent_status',
+ 'describe_substrate',
+ 'EnvJujuClient',
+ 'EnvJujuClient1X',
+ 'EnvJujuClient25',
+ 'ensure_dir',
+ 'get_cache_path',
+ 'get_client_class',
+ 'get_local_root',
+ 'get_machine_dns_name',
+ 'get_timeout_path',
+ 'get_timeout_prefix',
+ 'GroupReporter',
+ 'IncompatibleConfigClass',
+ 'InvalidEndpoint',
+ 'jes_home_path',
+ 'JESNotSupported',
+ 'JujuData',
+ 'JUJU_DEV_FEATURE_FLAGS',
+ 'Juju2Backend',
+ 'KILL_CONTROLLER',
+ 'KVM_MACHINE',
+ 'LXC_MACHINE',
+ 'LXD_MACHINE',
+ 'Machine',
+ 'NameNotAccepted',
+ 'NoProvider',
+ 'parse_new_state_server_from_error',
+ 'SimpleEnvironment',
+ 'SoftDeadlineExceeded',
+ 'Status',
+ 'temp_bootstrap_env',
+ '_temp_env',
+ 'temp_yaml_file',
+ 'TypeNotAccepted',
+ 'uniquify_local',
+ 'until_timeout',
+ ]
| Switch to explicit imports for jujupy. | ## Code Before:
from jujupy.client import *
from jujupy.client import _temp_env
__all__ = ['_temp_env']
## Instruction:
Switch to explicit imports for jujupy.
## Code After:
from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
| ...
from jujupy.client import (
AgentsNotStarted,
AuthNotAccepted,
AGENTS_READY,
client_from_config,
ConditionList,
coalesce_agent_status,
describe_substrate,
EnvJujuClient,
EnvJujuClient1X,
EnvJujuClient25,
ensure_dir,
get_cache_path,
get_client_class,
get_local_root,
get_machine_dns_name,
get_timeout_path,
get_timeout_prefix,
GroupReporter,
IncompatibleConfigClass,
InvalidEndpoint,
jes_home_path,
JESNotSupported,
JujuData,
JUJU_DEV_FEATURE_FLAGS,
Juju2Backend,
KILL_CONTROLLER,
KVM_MACHINE,
LXC_MACHINE,
LXD_MACHINE,
Machine,
NameNotAccepted,
NoProvider,
parse_new_state_server_from_error,
SimpleEnvironment,
SoftDeadlineExceeded,
Status,
temp_bootstrap_env,
_temp_env,
temp_yaml_file,
TypeNotAccepted,
uniquify_local,
until_timeout,
)
__all__ = [
'AgentsNotStarted',
'AuthNotAccepted',
'AGENTS_READY',
'client_from_config',
'ConditionList',
'coalesce_agent_status',
'describe_substrate',
'EnvJujuClient',
'EnvJujuClient1X',
'EnvJujuClient25',
'ensure_dir',
'get_cache_path',
'get_client_class',
'get_local_root',
'get_machine_dns_name',
'get_timeout_path',
'get_timeout_prefix',
'GroupReporter',
'IncompatibleConfigClass',
'InvalidEndpoint',
'jes_home_path',
'JESNotSupported',
'JujuData',
'JUJU_DEV_FEATURE_FLAGS',
'Juju2Backend',
'KILL_CONTROLLER',
'KVM_MACHINE',
'LXC_MACHINE',
'LXD_MACHINE',
'Machine',
'NameNotAccepted',
'NoProvider',
'parse_new_state_server_from_error',
'SimpleEnvironment',
'SoftDeadlineExceeded',
'Status',
'temp_bootstrap_env',
'_temp_env',
'temp_yaml_file',
'TypeNotAccepted',
'uniquify_local',
'until_timeout',
]
... |
3b2dab6b7c7a2e0f155825d2819c14de20135fd1 | scripts/add_global_subscriptions.py | scripts/add_global_subscriptions.py |
import logging
import sys
from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
app = init_app()
def add_global_subscriptions():
notification_type = 'email_transactional'
user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE
for user in models.User.find():
for user_event in user_events:
user_event_id = to_subscription_key(user._id, user_event)
subscription = NotificationSubscription.load(user_event_id)
if not subscription:
subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
logger.info('No subscription found. {} created.'.format(subscription))
else:
logger.info('Subscription {} found.'.format(subscription))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
scripts_utils.add_file_logger(logger, __file__)
add_global_subscriptions()
|
import logging
import sys
from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
app = init_app()
def add_global_subscriptions():
notification_type = 'email_transactional'
user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE
for user in models.User.find():
if user.is_active and user.is_registered:
for user_event in user_events:
user_event_id = to_subscription_key(user._id, user_event)
subscription = NotificationSubscription.load(user_event_id)
if not subscription:
subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
logger.info('No subscription found. {} created.'.format(subscription))
else:
logger.info('Subscription {} found.'.format(subscription))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
scripts_utils.add_file_logger(logger, __file__)
add_global_subscriptions()
| Add check for active and registered users | Add check for active and registered users
| Python | apache-2.0 | caneruguz/osf.io,alexschiller/osf.io,rdhyee/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,mfraezz/osf.io,aaxelb/osf.io,mattclark/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,cslzchen/osf.io,laurenrevere/osf.io,chennan47/osf.io,caseyrollins/osf.io,mfraezz/osf.io,chrisseto/osf.io,Nesiehr/osf.io,felliott/osf.io,Johnetordoff/osf.io,wearpants/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,hmoco/osf.io,erinspace/osf.io,baylee-d/osf.io,adlius/osf.io,Nesiehr/osf.io,binoculars/osf.io,wearpants/osf.io,amyshi188/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,emetsger/osf.io,alexschiller/osf.io,amyshi188/osf.io,acshi/osf.io,laurenrevere/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,chrisseto/osf.io,hmoco/osf.io,TomBaxter/osf.io,binoculars/osf.io,acshi/osf.io,mluo613/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,mluo613/osf.io,leb2dg/osf.io,adlius/osf.io,Nesiehr/osf.io,mluo613/osf.io,crcresearch/osf.io,mattclark/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,caseyrollins/osf.io,alexschiller/osf.io,sloria/osf.io,rdhyee/osf.io,alexschiller/osf.io,chennan47/osf.io,TomBaxter/osf.io,crcresearch/osf.io,erinspace/osf.io,SSJohns/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,pattisdr/osf.io,cslzchen/osf.io,felliott/osf.io,chennan47/osf.io,wearpants/osf.io,mattclark/osf.io,pattisdr/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,binoculars/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,acshi/osf.io,Johnetordoff/osf.io,sloria/osf.io,felliott/osf.io,monikagrabowska/osf.io,sloria/osf.io,icereval/osf.io,emetsger/osf.io,rdhyee/osf.io,Nesiehr/osf.io,caneruguz/osf.io,amyshi188/osf.io,felliott/osf.io,emetsger/osf.io,acshi/osf.io,acshi/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,wearpants/osf.io,erinspace/osf.io,rdhyee/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,adlius/osf.io,samchrisinger/osf.io,aaxelb/osf.io,cwisecarver/osf.io,saradbowman/osf.io,leb2dg/osf.io,mfraezz/osf.io,SSJohns/osf.io,emetsger/osf.io,saradbowman/osf.io,hmoco/osf.io,TomBaxter/osf.io,hmoco/osf.io,icereval/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,adlius/osf.io,SSJohns/osf.io,CenterForOpenScience/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,icereval/osf.io,caneruguz/osf.io |
import logging
import sys
from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
app = init_app()
def add_global_subscriptions():
notification_type = 'email_transactional'
user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE
for user in models.User.find():
+ if user.is_active and user.is_registered:
- for user_event in user_events:
+ for user_event in user_events:
- user_event_id = to_subscription_key(user._id, user_event)
+ user_event_id = to_subscription_key(user._id, user_event)
- subscription = NotificationSubscription.load(user_event_id)
+ subscription = NotificationSubscription.load(user_event_id)
- if not subscription:
+ if not subscription:
- subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
+ subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
- subscription.add_user_to_subscription(user, notification_type)
+ subscription.add_user_to_subscription(user, notification_type)
- subscription.save()
+ subscription.save()
- logger.info('No subscription found. {} created.'.format(subscription))
+ logger.info('No subscription found. {} created.'.format(subscription))
- else:
+ else:
- logger.info('Subscription {} found.'.format(subscription))
+ logger.info('Subscription {} found.'.format(subscription))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
scripts_utils.add_file_logger(logger, __file__)
add_global_subscriptions()
| Add check for active and registered users | ## Code Before:
import logging
import sys
from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
app = init_app()
def add_global_subscriptions():
notification_type = 'email_transactional'
user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE
for user in models.User.find():
for user_event in user_events:
user_event_id = to_subscription_key(user._id, user_event)
subscription = NotificationSubscription.load(user_event_id)
if not subscription:
subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
logger.info('No subscription found. {} created.'.format(subscription))
else:
logger.info('Subscription {} found.'.format(subscription))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
scripts_utils.add_file_logger(logger, __file__)
add_global_subscriptions()
## Instruction:
Add check for active and registered users
## Code After:
import logging
import sys
from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
app = init_app()
def add_global_subscriptions():
notification_type = 'email_transactional'
user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE
for user in models.User.find():
if user.is_active and user.is_registered:
for user_event in user_events:
user_event_id = to_subscription_key(user._id, user_event)
subscription = NotificationSubscription.load(user_event_id)
if not subscription:
subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
logger.info('No subscription found. {} created.'.format(subscription))
else:
logger.info('Subscription {} found.'.format(subscription))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
scripts_utils.add_file_logger(logger, __file__)
add_global_subscriptions()
| // ... existing code ...
for user in models.User.find():
if user.is_active and user.is_registered:
for user_event in user_events:
user_event_id = to_subscription_key(user._id, user_event)
subscription = NotificationSubscription.load(user_event_id)
if not subscription:
subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
logger.info('No subscription found. {} created.'.format(subscription))
else:
logger.info('Subscription {} found.'.format(subscription))
// ... rest of the code ... |
78747b26f642af4d1404df5a3a6d08160f07d2f0 | setup.py | setup.py |
from distutils.core import setup
setup(name='hawkular-client',
version='0.4.0',
description='Python client to communicate with Hawkular over HTTP(S)',
author='Michael Burman',
author_email='[email protected]',
url='http://github.com/hawkular/hawkular-client-python',
packages=['hawkular']
)
|
from distutils.core import setup
from os import path
from setuptools.command.install import install
import pypandoc
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
long_description = f.read()
# Create rst here from Markdown
z = pypandoc.convert('README.md','rst',format='markdown')
with open('README.rst','w') as outfile:
outfile.write(z)
setup(name='hawkular-client',
version='0.4.0',
description='Python client to communicate with Hawkular server over HTTP(S)',
author='Michael Burman',
author_email='[email protected]',
license='Apache License 2.0',
url='http://github.com/hawkular/hawkular-client-python',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: System :: Monitoring',
],
packages=['hawkular']
)
| Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt | Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt
| Python | apache-2.0 | hawkular/hawkular-client-python,burmanm/hawkular-client-python,burmanm/hawkular-client-python,hawkular/hawkular-client-python |
from distutils.core import setup
+ from os import path
+ from setuptools.command.install import install
+ import pypandoc
+ here = path.abspath(path.dirname(__file__))
+
+ with open(path.join(here, 'README.md')) as f:
+ long_description = f.read()
+
+ # Create rst here from Markdown
+ z = pypandoc.convert('README.md','rst',format='markdown')
+
+ with open('README.rst','w') as outfile:
+ outfile.write(z)
+
setup(name='hawkular-client',
version='0.4.0',
- description='Python client to communicate with Hawkular over HTTP(S)',
+ description='Python client to communicate with Hawkular server over HTTP(S)',
author='Michael Burman',
author_email='[email protected]',
+ license='Apache License 2.0',
url='http://github.com/hawkular/hawkular-client-python',
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'Intended Audience :: Developers',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 3',
+ 'Topic :: System :: Monitoring',
+ ],
packages=['hawkular']
)
| Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt | ## Code Before:
from distutils.core import setup
setup(name='hawkular-client',
version='0.4.0',
description='Python client to communicate with Hawkular over HTTP(S)',
author='Michael Burman',
author_email='[email protected]',
url='http://github.com/hawkular/hawkular-client-python',
packages=['hawkular']
)
## Instruction:
Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt
## Code After:
from distutils.core import setup
from os import path
from setuptools.command.install import install
import pypandoc
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
long_description = f.read()
# Create rst here from Markdown
z = pypandoc.convert('README.md','rst',format='markdown')
with open('README.rst','w') as outfile:
outfile.write(z)
setup(name='hawkular-client',
version='0.4.0',
description='Python client to communicate with Hawkular server over HTTP(S)',
author='Michael Burman',
author_email='[email protected]',
license='Apache License 2.0',
url='http://github.com/hawkular/hawkular-client-python',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: System :: Monitoring',
],
packages=['hawkular']
)
| // ... existing code ...
from distutils.core import setup
from os import path
from setuptools.command.install import install
import pypandoc
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
long_description = f.read()
# Create rst here from Markdown
z = pypandoc.convert('README.md','rst',format='markdown')
with open('README.rst','w') as outfile:
outfile.write(z)
setup(name='hawkular-client',
// ... modified code ...
version='0.4.0',
description='Python client to communicate with Hawkular server over HTTP(S)',
author='Michael Burman',
...
author_email='[email protected]',
license='Apache License 2.0',
url='http://github.com/hawkular/hawkular-client-python',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: System :: Monitoring',
],
packages=['hawkular']
// ... rest of the code ... |
048f2d9469b3f9eb266a343602ddf608e3bd6d86 | highton/models/email_address.py | highton/models/email_address.py | from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION)
self.address = fields.StringField(name=HightonConstants.ADDRESS)
super().__init__(**kwargs)
| from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
| Set EmailAddress Things to required | Set EmailAddress Things to required
| Python | apache-2.0 | seibert-media/Highton,seibert-media/Highton | from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
- self.location = fields.StringField(name=HightonConstants.LOCATION)
+ self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
- self.address = fields.StringField(name=HightonConstants.ADDRESS)
+ self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
| Set EmailAddress Things to required | ## Code Before:
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION)
self.address = fields.StringField(name=HightonConstants.ADDRESS)
super().__init__(**kwargs)
## Instruction:
Set EmailAddress Things to required
## Code After:
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
| # ... existing code ...
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
# ... rest of the code ... |
24ff6aa99c7ee78d58200aad03c50722563cb1a0 | purchase_product_usage/models/account_move.py | purchase_product_usage/models/account_move.py |
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
| Change only account if usage is defined in POL | [13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL
| Python | agpl-3.0 | OCA/purchase-workflow,OCA/purchase-workflow |
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
- account = line.purchase_line_id.usage_id.account_id
+ line.account_id = line.purchase_line_id.usage_id.account_id
- else:
- account = line._get_computed_account()
- line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
| Change only account if usage is defined in POL | ## Code Before:
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
## Instruction:
Change only account if usage is defined in POL
## Code After:
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
| // ... existing code ...
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
// ... rest of the code ... |
70e7b932c1c6013306a53f47c14d969d4ada8ab4 | api/home/models.py | api/home/models.py | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, default='')
override_title = models.CharField(max_length=265, default='')
override_description = models.TextField(default='')
override_background_color = models.CharField(max_length=64, default='')
| from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, blank=True, default='')
override_title = models.CharField(max_length=265, blank=True, default='')
override_description = models.TextField(default='', blank=True)
override_background_color = models.CharField(max_length=64, blank=True, default='')
| Allow overrides to be blank | Allow overrides to be blank
| Python | mit | urfonline/api,urfonline/api,urfonline/api | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
- override_kicker = models.CharField(max_length=64, default='')
+ override_kicker = models.CharField(max_length=64, blank=True, default='')
- override_title = models.CharField(max_length=265, default='')
+ override_title = models.CharField(max_length=265, blank=True, default='')
- override_description = models.TextField(default='')
+ override_description = models.TextField(default='', blank=True)
- override_background_color = models.CharField(max_length=64, default='')
+ override_background_color = models.CharField(max_length=64, blank=True, default='')
| Allow overrides to be blank | ## Code Before:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, default='')
override_title = models.CharField(max_length=265, default='')
override_description = models.TextField(default='')
override_background_color = models.CharField(max_length=64, default='')
## Instruction:
Allow overrides to be blank
## Code After:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3', 'Third 3'),
)
class HomepageBlock(models.Model):
limit = models.Q(app_label='shows', model='show') | models.Q(app_label='articles',
model='article') | models.Q(
app_label='events', model='event')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
published_at = models.DateTimeField()
position = models.CharField(max_length=12, choices=POSITIONS)
override_kicker = models.CharField(max_length=64, blank=True, default='')
override_title = models.CharField(max_length=265, blank=True, default='')
override_description = models.TextField(default='', blank=True)
override_background_color = models.CharField(max_length=64, blank=True, default='')
| # ... existing code ...
override_kicker = models.CharField(max_length=64, blank=True, default='')
override_title = models.CharField(max_length=265, blank=True, default='')
override_description = models.TextField(default='', blank=True)
override_background_color = models.CharField(max_length=64, blank=True, default='')
# ... rest of the code ... |
ab57bcc9f4219af63e99d82a844986213ade4c01 | script/commit_message.py | script/commit_message.py | import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
| import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
| Fix script up to search branches | Fix script up to search branches
| Python | mit | pact-foundation/pact-python,pact-foundation/pact-python | import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
+ cmd_tag = "git describe --abbrev=0"
+ tag = subprocess.check_output(cmd_tag,
+ shell=True).decode("utf-8").split('\n')[0]
+
- cmd = "git log --pretty=format:'%s' master..HEAD"
+ cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
| Fix script up to search branches | ## Code Before:
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
## Instruction:
Fix script up to search branches
## Code After:
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
| // ... existing code ...
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
// ... rest of the code ... |
157c08a6ccd738d5bccfe8145c2a1f1e9d21ba82 | madlib_web_client.py | madlib_web_client.py | import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Drop table if it already exists
cur.execute("DROP TABLE test;")
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| Add a drop table for testing. | Add a drop table for testing.
| Python | isc | appletonmakerspace/madlib,mikeputnam/madlib | import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
+ # Drop table if it already exists
+ cur.execute("DROP TABLE test;")
+
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
- cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
+ cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
+
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| Add a drop table for testing. | ## Code Before:
import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
## Instruction:
Add a drop table for testing.
## Code After:
import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Drop table if it already exists
cur.execute("DROP TABLE test;")
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| ...
# Drop table if it already exists
cur.execute("DROP TABLE test;")
# Create a table
...
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
...
@app.route("/")
... |
74d668cb8291822a167d1ddd0fecf7e580375377 | serv/rcompserv/serv.py | serv/rcompserv/serv.py | from aiohttp import web
from . import __version__
class Server:
def __init__(self, host='127.0.0.1', port=8080):
self._host = host
self._port = port
self.app = web.Application()
self.app.router.add_get('/', self.index)
self.known_commands = ['version']
self.app.router.add_get('/version', self.version)
async def index(self, request):
return web.json_response({'commands': self.known_commands})
async def version(self, request):
return web.json_response({'version': __version__})
def run(self):
web.run_app(self.app, host=self._host, port=self._port)
| import uuid
from datetime import datetime
from aiohttp import web
import redis
from . import __version__
class Server:
def __init__(self, host='127.0.0.1', port=8080):
self._host = host
self._port = port
self.app = web.Application()
self.app.on_startup.append(self.start_redis)
self.app.router.add_get('/', self.index)
self.known_commands = ['version', 'trivial']
self.app.router.add_get('/version', self.version)
self.app.router.add_get('/trivial', self.trivial)
async def start_redis(self, app):
app['redis'] = redis.StrictRedis()
async def index(self, request):
return web.json_response({'commands': self.known_commands})
async def version(self, request):
return web.json_response({'version': __version__})
async def trivial(self, request):
job_id = str(uuid.uuid4())
start_time = str(datetime.utcnow())
request.app['redis'].hset(job_id, 'cmd', 'trivial')
request.app['redis'].hset(job_id, 'stime', start_time)
request.app['redis'].hset(job_id, 'done', 1)
request.app['redis'].hset(job_id, 'output', '')
return web.json_response({
'cmd': str(request.app['redis'].hget(job_id, 'cmd'), encoding='utf-8'),
'id': job_id,
'stime': str(request.app['redis'].hget(job_id, 'stime'), encoding='utf-8'),
'done': False if request.app['redis'].hget(job_id, 'done') == 0 else True,
'output': str(request.app['redis'].hget(job_id, 'output'), encoding='utf-8')
})
def run(self):
web.run_app(self.app, host=self._host, port=self._port)
| Add route for `trivial` (vacuous) command | Add route for `trivial` (vacuous) command
| Python | bsd-3-clause | slivingston/rcomp,slivingston/rcomp,slivingston/rcomp | + import uuid
+ from datetime import datetime
+
from aiohttp import web
+ import redis
from . import __version__
class Server:
def __init__(self, host='127.0.0.1', port=8080):
self._host = host
self._port = port
self.app = web.Application()
+ self.app.on_startup.append(self.start_redis)
self.app.router.add_get('/', self.index)
- self.known_commands = ['version']
+ self.known_commands = ['version', 'trivial']
self.app.router.add_get('/version', self.version)
+ self.app.router.add_get('/trivial', self.trivial)
+
+ async def start_redis(self, app):
+ app['redis'] = redis.StrictRedis()
async def index(self, request):
return web.json_response({'commands': self.known_commands})
async def version(self, request):
return web.json_response({'version': __version__})
+ async def trivial(self, request):
+ job_id = str(uuid.uuid4())
+ start_time = str(datetime.utcnow())
+ request.app['redis'].hset(job_id, 'cmd', 'trivial')
+ request.app['redis'].hset(job_id, 'stime', start_time)
+ request.app['redis'].hset(job_id, 'done', 1)
+ request.app['redis'].hset(job_id, 'output', '')
+ return web.json_response({
+ 'cmd': str(request.app['redis'].hget(job_id, 'cmd'), encoding='utf-8'),
+ 'id': job_id,
+ 'stime': str(request.app['redis'].hget(job_id, 'stime'), encoding='utf-8'),
+ 'done': False if request.app['redis'].hget(job_id, 'done') == 0 else True,
+ 'output': str(request.app['redis'].hget(job_id, 'output'), encoding='utf-8')
+ })
+
def run(self):
web.run_app(self.app, host=self._host, port=self._port)
| Add route for `trivial` (vacuous) command | ## Code Before:
from aiohttp import web
from . import __version__
class Server:
def __init__(self, host='127.0.0.1', port=8080):
self._host = host
self._port = port
self.app = web.Application()
self.app.router.add_get('/', self.index)
self.known_commands = ['version']
self.app.router.add_get('/version', self.version)
async def index(self, request):
return web.json_response({'commands': self.known_commands})
async def version(self, request):
return web.json_response({'version': __version__})
def run(self):
web.run_app(self.app, host=self._host, port=self._port)
## Instruction:
Add route for `trivial` (vacuous) command
## Code After:
import uuid
from datetime import datetime
from aiohttp import web
import redis
from . import __version__
class Server:
def __init__(self, host='127.0.0.1', port=8080):
self._host = host
self._port = port
self.app = web.Application()
self.app.on_startup.append(self.start_redis)
self.app.router.add_get('/', self.index)
self.known_commands = ['version', 'trivial']
self.app.router.add_get('/version', self.version)
self.app.router.add_get('/trivial', self.trivial)
async def start_redis(self, app):
app['redis'] = redis.StrictRedis()
async def index(self, request):
return web.json_response({'commands': self.known_commands})
async def version(self, request):
return web.json_response({'version': __version__})
async def trivial(self, request):
job_id = str(uuid.uuid4())
start_time = str(datetime.utcnow())
request.app['redis'].hset(job_id, 'cmd', 'trivial')
request.app['redis'].hset(job_id, 'stime', start_time)
request.app['redis'].hset(job_id, 'done', 1)
request.app['redis'].hset(job_id, 'output', '')
return web.json_response({
'cmd': str(request.app['redis'].hget(job_id, 'cmd'), encoding='utf-8'),
'id': job_id,
'stime': str(request.app['redis'].hget(job_id, 'stime'), encoding='utf-8'),
'done': False if request.app['redis'].hget(job_id, 'done') == 0 else True,
'output': str(request.app['redis'].hget(job_id, 'output'), encoding='utf-8')
})
def run(self):
web.run_app(self.app, host=self._host, port=self._port)
| # ... existing code ...
import uuid
from datetime import datetime
from aiohttp import web
import redis
# ... modified code ...
self.app = web.Application()
self.app.on_startup.append(self.start_redis)
self.app.router.add_get('/', self.index)
self.known_commands = ['version', 'trivial']
self.app.router.add_get('/version', self.version)
self.app.router.add_get('/trivial', self.trivial)
async def start_redis(self, app):
app['redis'] = redis.StrictRedis()
...
async def trivial(self, request):
job_id = str(uuid.uuid4())
start_time = str(datetime.utcnow())
request.app['redis'].hset(job_id, 'cmd', 'trivial')
request.app['redis'].hset(job_id, 'stime', start_time)
request.app['redis'].hset(job_id, 'done', 1)
request.app['redis'].hset(job_id, 'output', '')
return web.json_response({
'cmd': str(request.app['redis'].hget(job_id, 'cmd'), encoding='utf-8'),
'id': job_id,
'stime': str(request.app['redis'].hget(job_id, 'stime'), encoding='utf-8'),
'done': False if request.app['redis'].hget(job_id, 'done') == 0 else True,
'output': str(request.app['redis'].hget(job_id, 'output'), encoding='utf-8')
})
def run(self):
# ... rest of the code ... |
3bf8790a0a8bd5464cedcb4f2acb92f758bc01b4 | apgl/data/ExamplesGenerator.py | apgl/data/ExamplesGenerator.py | '''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels. Must have more than 1 example and feature.
"""
if numExamples == 0 or numFeatures == 0:
raise ValueError("Cannot generate empty dataset")
X = numpy.random.rand(numExamples, numFeatures)
c = numpy.random.rand(numFeatures)
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
return X, y
def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels
"""
X = numpy.random.rand(numExamples, numFeatures)
y = (numpy.random.rand(numExamples)>0.5)*2 - 1
return X, y
| '''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels. Must have more than 1 example and feature.
"""
if numExamples == 0 or numFeatures == 0:
raise ValueError("Cannot generate empty dataset")
X = numpy.random.rand(numExamples, numFeatures)
c = numpy.random.rand(numFeatures)
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
y = numpy.array(y, numpy.int)
return X, y
def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels
"""
X = numpy.random.rand(numExamples, numFeatures)
y = (numpy.random.rand(numExamples)>0.5)*2 - 1
return X, y
| Make sure labels are ints. | Make sure labels are ints. | Python | bsd-3-clause | charanpald/APGL | '''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels. Must have more than 1 example and feature.
"""
if numExamples == 0 or numFeatures == 0:
raise ValueError("Cannot generate empty dataset")
X = numpy.random.rand(numExamples, numFeatures)
c = numpy.random.rand(numFeatures)
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
+ y = numpy.array(y, numpy.int)
return X, y
def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels
"""
X = numpy.random.rand(numExamples, numFeatures)
y = (numpy.random.rand(numExamples)>0.5)*2 - 1
return X, y
| Make sure labels are ints. | ## Code Before:
'''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels. Must have more than 1 example and feature.
"""
if numExamples == 0 or numFeatures == 0:
raise ValueError("Cannot generate empty dataset")
X = numpy.random.rand(numExamples, numFeatures)
c = numpy.random.rand(numFeatures)
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
return X, y
def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels
"""
X = numpy.random.rand(numExamples, numFeatures)
y = (numpy.random.rand(numExamples)>0.5)*2 - 1
return X, y
## Instruction:
Make sure labels are ints.
## Code After:
'''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels. Must have more than 1 example and feature.
"""
if numExamples == 0 or numFeatures == 0:
raise ValueError("Cannot generate empty dataset")
X = numpy.random.rand(numExamples, numFeatures)
c = numpy.random.rand(numFeatures)
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
y = numpy.array(y, numpy.int)
return X, y
def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10):
"""
Generate a certain number of examples with a uniform distribution between 0 and 1. Create
binary -/+ 1 labels
"""
X = numpy.random.rand(numExamples, numFeatures)
y = (numpy.random.rand(numExamples)>0.5)*2 - 1
return X, y
| ...
y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise)
y = numpy.array(y, numpy.int)
... |
74ecf023ef13fdba6378d6b50b3eaeb06b9e0c97 | rebuild_dependant_repos.py | rebuild_dependant_repos.py | import os, sys, re, logging
import requests
from github import Github
logging.basicConfig(level=logging.DEBUG)
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["TAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["TAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image name is required as the first argument.")
image_name = sys.argv[1]
image_name = re.sub(r"[^a-zA-Z0-9-]", " ", image_name)
query = "org:avatao-content language:Dockerfile FROM " + image_name
logging.debug("Searching GitHub with query: '%s'", query)
code_search = g.search_code(query)
circleci_project_slugs = set()
for result in code_search:
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
logging.debug("Found %d candidate repositories.", len(circleci_project_slugs))
current_item = 1
for slug in circleci_project_slugs:
logging.debug("[%d/%d] Triggering CI pipeline for: %s", current_item, len(circleci_project_slugs), slug)
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
current_item += 1
| import os, sys, re
import requests
from github import Github
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["AVATAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["AVATAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image name is required as the first argument.")
image_name = sys.argv[1]
image_name = re.sub(r"[^a-zA-Z0-9-]", " ", image_name)
query = "org:avatao-content language:Dockerfile " + image_name
print("Searching GitHub with query: '%s'" % query)
code_search = g.search_code(query)
circleci_project_slugs = set()
for result in code_search:
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
print("Found %d candidate repositories." % len(circleci_project_slugs))
current_item = 1
for slug in circleci_project_slugs:
print("[%d/%d] Triggering CI pipeline for: %s" % (current_item, len(circleci_project_slugs), slug))
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
current_item += 1
| Rename env vars & modify query | Rename env vars & modify query
| Python | apache-2.0 | avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox | - import os, sys, re, logging
+ import os, sys, re
import requests
from github import Github
- logging.basicConfig(level=logging.DEBUG)
-
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
- CIRCLECI_ACCESS_TOKEN = os.environ["TAO_CIRCLECI_TOKEN"]
+ CIRCLECI_ACCESS_TOKEN = os.environ["AVATAO_CIRCLECI_TOKEN"]
- GITHUB_ACCESS_TOKEN = os.environ["TAO_GITHUB_TOKEN"]
+ GITHUB_ACCESS_TOKEN = os.environ["AVATAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image name is required as the first argument.")
image_name = sys.argv[1]
image_name = re.sub(r"[^a-zA-Z0-9-]", " ", image_name)
- query = "org:avatao-content language:Dockerfile FROM " + image_name
+ query = "org:avatao-content language:Dockerfile " + image_name
- logging.debug("Searching GitHub with query: '%s'", query)
+ print("Searching GitHub with query: '%s'" % query)
code_search = g.search_code(query)
circleci_project_slugs = set()
for result in code_search:
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
- logging.debug("Found %d candidate repositories.", len(circleci_project_slugs))
+ print("Found %d candidate repositories." % len(circleci_project_slugs))
current_item = 1
for slug in circleci_project_slugs:
- logging.debug("[%d/%d] Triggering CI pipeline for: %s", current_item, len(circleci_project_slugs), slug)
+ print("[%d/%d] Triggering CI pipeline for: %s" % (current_item, len(circleci_project_slugs), slug))
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
current_item += 1
| Rename env vars & modify query | ## Code Before:
import os, sys, re, logging
import requests
from github import Github
logging.basicConfig(level=logging.DEBUG)
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["TAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["TAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image name is required as the first argument.")
image_name = sys.argv[1]
image_name = re.sub(r"[^a-zA-Z0-9-]", " ", image_name)
query = "org:avatao-content language:Dockerfile FROM " + image_name
logging.debug("Searching GitHub with query: '%s'", query)
code_search = g.search_code(query)
circleci_project_slugs = set()
for result in code_search:
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
logging.debug("Found %d candidate repositories.", len(circleci_project_slugs))
current_item = 1
for slug in circleci_project_slugs:
logging.debug("[%d/%d] Triggering CI pipeline for: %s", current_item, len(circleci_project_slugs), slug)
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
current_item += 1
## Instruction:
Rename env vars & modify query
## Code After:
import os, sys, re
import requests
from github import Github
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["AVATAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["AVATAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image name is required as the first argument.")
image_name = sys.argv[1]
image_name = re.sub(r"[^a-zA-Z0-9-]", " ", image_name)
query = "org:avatao-content language:Dockerfile " + image_name
print("Searching GitHub with query: '%s'" % query)
code_search = g.search_code(query)
circleci_project_slugs = set()
for result in code_search:
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
print("Found %d candidate repositories." % len(circleci_project_slugs))
current_item = 1
for slug in circleci_project_slugs:
print("[%d/%d] Triggering CI pipeline for: %s" % (current_item, len(circleci_project_slugs), slug))
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
current_item += 1
| ...
import os, sys, re
import requests
...
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["AVATAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["AVATAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
...
query = "org:avatao-content language:Dockerfile " + image_name
print("Searching GitHub with query: '%s'" % query)
code_search = g.search_code(query)
...
circleci_project_slugs.add(f"gh/{result.repository.organization.login}/{result.repository.name}")
print("Found %d candidate repositories." % len(circleci_project_slugs))
...
for slug in circleci_project_slugs:
print("[%d/%d] Triggering CI pipeline for: %s" % (current_item, len(circleci_project_slugs), slug))
requests.post(f"{CIRCLECI_BASEURL}/project/{slug}/pipeline", headers={"Circle-Token": CIRCLECI_ACCESS_TOKEN})
... |
49069663a3fe3d44be9ab59e59a90d0dfcf49f0c | mayatools/qt.py | mayatools/qt.py |
try:
import sip
from uitools.qt import QtCore
import maya.OpenMayaUI as apiUI
# These modules will not exist while building the docs.
except ImportError:
import os
if os.environ.get('SPHINX') != 'True':
raise
def get_maya_window():
"""Get the main Maya window as a QtGui.QMainWindow."""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return sip.wrapinstance(long(ptr), QtCore.QObject)
def maya_to_qt(maya_object):
"""Convert a Maya UI path to a Qt object.
:param str maya_object: The path of the Maya UI object to convert.
:returns: QtCore.QObject or None
"""
ptr = (
apiUI.MQtUtil.findControl(maya_object) or
apiUI.MQtUtil.findLayout(maya_object) or
apiUI.MQtUtil.findMenuItem(maya_object)
)
if ptr is not None:
return sip.wrapinstance(long(ptr), QtCore.QObject) |
try:
from uitools.sip import wrapinstance
from uitools.qt import QtCore
import maya.OpenMayaUI as apiUI
# These modules will not exist while building the docs.
except ImportError:
import os
if os.environ.get('SPHINX') != 'True':
raise
def get_maya_window():
"""Get the main Maya window as a QtGui.QMainWindow."""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject)
def maya_to_qt(maya_object):
"""Convert a Maya UI path to a Qt object.
:param str maya_object: The path of the Maya UI object to convert.
:returns: QtCore.QObject or None
"""
ptr = (
apiUI.MQtUtil.findControl(maya_object) or
apiUI.MQtUtil.findLayout(maya_object) or
apiUI.MQtUtil.findMenuItem(maya_object)
)
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject) | Use uitools.sip instead of straight sip | Use uitools.sip instead of straight sip | Python | bsd-3-clause | westernx/mayatools,westernx/mayatools |
try:
- import sip
+ from uitools.sip import wrapinstance
from uitools.qt import QtCore
import maya.OpenMayaUI as apiUI
# These modules will not exist while building the docs.
except ImportError:
import os
if os.environ.get('SPHINX') != 'True':
raise
def get_maya_window():
"""Get the main Maya window as a QtGui.QMainWindow."""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
- return sip.wrapinstance(long(ptr), QtCore.QObject)
+ return wrapinstance(long(ptr), QtCore.QObject)
def maya_to_qt(maya_object):
"""Convert a Maya UI path to a Qt object.
:param str maya_object: The path of the Maya UI object to convert.
:returns: QtCore.QObject or None
"""
ptr = (
apiUI.MQtUtil.findControl(maya_object) or
apiUI.MQtUtil.findLayout(maya_object) or
apiUI.MQtUtil.findMenuItem(maya_object)
)
if ptr is not None:
- return sip.wrapinstance(long(ptr), QtCore.QObject)
+ return wrapinstance(long(ptr), QtCore.QObject) | Use uitools.sip instead of straight sip | ## Code Before:
try:
import sip
from uitools.qt import QtCore
import maya.OpenMayaUI as apiUI
# These modules will not exist while building the docs.
except ImportError:
import os
if os.environ.get('SPHINX') != 'True':
raise
def get_maya_window():
"""Get the main Maya window as a QtGui.QMainWindow."""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return sip.wrapinstance(long(ptr), QtCore.QObject)
def maya_to_qt(maya_object):
"""Convert a Maya UI path to a Qt object.
:param str maya_object: The path of the Maya UI object to convert.
:returns: QtCore.QObject or None
"""
ptr = (
apiUI.MQtUtil.findControl(maya_object) or
apiUI.MQtUtil.findLayout(maya_object) or
apiUI.MQtUtil.findMenuItem(maya_object)
)
if ptr is not None:
return sip.wrapinstance(long(ptr), QtCore.QObject)
## Instruction:
Use uitools.sip instead of straight sip
## Code After:
try:
from uitools.sip import wrapinstance
from uitools.qt import QtCore
import maya.OpenMayaUI as apiUI
# These modules will not exist while building the docs.
except ImportError:
import os
if os.environ.get('SPHINX') != 'True':
raise
def get_maya_window():
"""Get the main Maya window as a QtGui.QMainWindow."""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject)
def maya_to_qt(maya_object):
"""Convert a Maya UI path to a Qt object.
:param str maya_object: The path of the Maya UI object to convert.
:returns: QtCore.QObject or None
"""
ptr = (
apiUI.MQtUtil.findControl(maya_object) or
apiUI.MQtUtil.findLayout(maya_object) or
apiUI.MQtUtil.findMenuItem(maya_object)
)
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject) | ...
try:
from uitools.sip import wrapinstance
from uitools.qt import QtCore
...
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject)
...
if ptr is not None:
return wrapinstance(long(ptr), QtCore.QObject)
... |
973641c7d68f4b1505541a06ec46901b412ab56b | tests/test_constraints.py | tests/test_constraints.py | import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
| import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
def test_licq(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
rank = np.linalg.matrix_rank(constraint_gradients)
self.assertEqual(rank, 2 * 5)
| Test LICQ condition of constraint gradient | Test LICQ condition of constraint gradient
| Python | mit | JakobGM/robotarm-optimization | import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
+ def test_licq(self):
+ constraint_gradients = self.constraint_gradients_func(self.thetas)
+ rank = np.linalg.matrix_rank(constraint_gradients)
+ self.assertEqual(rank, 2 * 5)
+ | Test LICQ condition of constraint gradient | ## Code Before:
import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
## Instruction:
Test LICQ condition of constraint gradient
## Code After:
import unittest
import numpy as np
from constraints import (generate_constraints_function,
generate_constraint_gradients_function, )
from robot_arm import RobotArm
class TestConstraintFunctions(unittest.TestCase):
def setUp(self):
self.lengths = (3, 2, 2,)
self.destinations = (
(5, 4, 6, 4, 5),
(0, 2, 0.5, -2, -1),
)
self.theta = (np.pi, np.pi / 2, 0,)
self.thetas = np.ones((3 * 5,))
self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
self.constraints_func = generate_constraints_function(self.robot_arm)
self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)
def test_constraints_func_return_type(self):
constraints = self.constraints_func(self.thetas)
self.assertEqual(constraints.shape, (2 * 5,))
def test_constraint_gradients_func_return_type(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
def test_licq(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
rank = np.linalg.matrix_rank(constraint_gradients)
self.assertEqual(rank, 2 * 5)
| # ... existing code ...
# print(np.array2string(constraint_gradients, max_line_width=np.inf))
def test_licq(self):
constraint_gradients = self.constraint_gradients_func(self.thetas)
rank = np.linalg.matrix_rank(constraint_gradients)
self.assertEqual(rank, 2 * 5)
# ... rest of the code ... |
a9bc4d98e8b61b63c14a2a5f1e11c85d91747f30 | analysis/data_process/uk_2017/config.py | analysis/data_process/uk_2017/config.py |
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_file = '../../../survey_creation/uk_17/uk_17.csv'
answer_folder = '../../../survey_creation/uk_17/listAnswers'
# Location for the json file of all questions
json_to_plot_location = './to_plot.json'
cleaned_df_location = './dataset/cleaned_data.csv'
class PlottingConfig(CleaningConfig):
pass
class NotebookConfig(PlottingConfig):
notebook_folder = './'
notebook_filename = 'uk_17.ipynb'
to_import = ['import pandas as pd',
'import numpy as np',
'get_ipython().magic("matplotlib inline")',
'import matplotlib',
'import matplotlib.pyplot as plt',
'from config import CleaningConfig, PlottingConfig, NotebookConfig',
'from counting import get_count',
'from plotting import get_plot',
'from likertScalePlot import likert_scale']
|
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_file = '../../../survey_creation/uk_17/uk_17.csv'
answer_folder = '../../../survey_creation/uk_17/listAnswers'
# Location for the json file of all questions
json_to_plot_location = './to_plot.json'
cleaned_df_location = './dataset/cleaned_data.csv'
class PlottingConfig(CleaningConfig):
count_na = True
plot_na = False
normalise = False
class NotebookConfig(PlottingConfig):
notebook_folder = './'
notebook_filename = 'uk_17.ipynb'
to_import = ['import pandas as pd',
'import numpy as np',
'import matplotlib',
'import matplotlib.pyplot as plt',
'from config import CleaningConfig, PlottingConfig, NotebookConfig',
'from counting import get_count',
'from plotting import get_plot',
'from IPython.display import display',
'from likertScalePlot import likert_scale']
processing_options = {'metadata': {'path': './',
'hide_input': True}}
| Add options in the plot | Add options in the plot
| Python | bsd-3-clause | softwaresaved/international-survey |
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_file = '../../../survey_creation/uk_17/uk_17.csv'
answer_folder = '../../../survey_creation/uk_17/listAnswers'
# Location for the json file of all questions
json_to_plot_location = './to_plot.json'
cleaned_df_location = './dataset/cleaned_data.csv'
class PlottingConfig(CleaningConfig):
-
- pass
+ count_na = True
+ plot_na = False
+ normalise = False
class NotebookConfig(PlottingConfig):
notebook_folder = './'
notebook_filename = 'uk_17.ipynb'
to_import = ['import pandas as pd',
'import numpy as np',
- 'get_ipython().magic("matplotlib inline")',
'import matplotlib',
'import matplotlib.pyplot as plt',
'from config import CleaningConfig, PlottingConfig, NotebookConfig',
'from counting import get_count',
'from plotting import get_plot',
+ 'from IPython.display import display',
'from likertScalePlot import likert_scale']
+ processing_options = {'metadata': {'path': './',
+ 'hide_input': True}}
| Add options in the plot | ## Code Before:
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_file = '../../../survey_creation/uk_17/uk_17.csv'
answer_folder = '../../../survey_creation/uk_17/listAnswers'
# Location for the json file of all questions
json_to_plot_location = './to_plot.json'
cleaned_df_location = './dataset/cleaned_data.csv'
class PlottingConfig(CleaningConfig):
pass
class NotebookConfig(PlottingConfig):
notebook_folder = './'
notebook_filename = 'uk_17.ipynb'
to_import = ['import pandas as pd',
'import numpy as np',
'get_ipython().magic("matplotlib inline")',
'import matplotlib',
'import matplotlib.pyplot as plt',
'from config import CleaningConfig, PlottingConfig, NotebookConfig',
'from counting import get_count',
'from plotting import get_plot',
'from likertScalePlot import likert_scale']
## Instruction:
Add options in the plot
## Code After:
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_file = '../../../survey_creation/uk_17/uk_17.csv'
answer_folder = '../../../survey_creation/uk_17/listAnswers'
# Location for the json file of all questions
json_to_plot_location = './to_plot.json'
cleaned_df_location = './dataset/cleaned_data.csv'
class PlottingConfig(CleaningConfig):
count_na = True
plot_na = False
normalise = False
class NotebookConfig(PlottingConfig):
notebook_folder = './'
notebook_filename = 'uk_17.ipynb'
to_import = ['import pandas as pd',
'import numpy as np',
'import matplotlib',
'import matplotlib.pyplot as plt',
'from config import CleaningConfig, PlottingConfig, NotebookConfig',
'from counting import get_count',
'from plotting import get_plot',
'from IPython.display import display',
'from likertScalePlot import likert_scale']
processing_options = {'metadata': {'path': './',
'hide_input': True}}
| ...
class PlottingConfig(CleaningConfig):
count_na = True
plot_na = False
normalise = False
...
'import numpy as np',
'import matplotlib',
...
'from plotting import get_plot',
'from IPython.display import display',
'from likertScalePlot import likert_scale']
processing_options = {'metadata': {'path': './',
'hide_input': True}}
... |
2b5e33bf178cd1fdd8e320051d0c99a45d7613a1 | models/product_bundle.py | models/product_bundle.py | from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Use of product.template instead of product.product in bundle line | Use of product.template instead of product.product in bundle line
| Python | agpl-3.0 | akretion/sale-workflow,richard-willowit/sale-workflow,ddico/sale-workflow,Eficent/sale-workflow,anas-taji/sale-workflow,BT-cserra/sale-workflow,BT-fgarbely/sale-workflow,fevxie/sale-workflow,diagramsoftware/sale-workflow,adhoc-dev/sale-workflow,thomaspaulb/sale-workflow,kittiu/sale-workflow,factorlibre/sale-workflow,numerigraphe/sale-workflow,xpansa/sale-workflow,brain-tec/sale-workflow,acsone/sale-workflow,brain-tec/sale-workflow,Endika/sale-workflow,open-synergy/sale-workflow,anybox/sale-workflow,BT-ojossen/sale-workflow,BT-jmichaud/sale-workflow,acsone/sale-workflow,luistorresm/sale-workflow,jjscarafia/sale-workflow,alexsandrohaag/sale-workflow,Antiun/sale-workflow,Rona111/sale-workflow,jabibi/sale-workflow,akretion/sale-workflow,numerigraphe/sale-workflow,kittiu/sale-workflow | from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
- product_id = fields.Many2one('product.template', string=_('Product'), required=True)
+ product_id = fields.Many2one(
+ 'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Use of product.template instead of product.product in bundle line | ## Code Before:
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
Use of product.template instead of product.product in bundle line
## Code After:
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| // ... existing code ...
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
// ... rest of the code ... |
46ab82bf387b6f7d13abc94bacb16b76bc292080 | util/cron/verify_config_names.py | util/cron/verify_config_names.py |
from __future__ import print_function
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
config_name = content.split('"')[1]
expected_script_name = 'test-{0}.bash'.format(config_name)
if not filename.endswith(expected_script_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
filename, config_name))
|
from __future__ import print_function
import os.path
import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
filename_parts = os.path.splitext(filename)
filename_base = filename_parts[0]
pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"',
re.IGNORECASE)
match = pattern.search(content)
config_name = None
if match is not None:
config_name = match.group('config_name')
else:
print('[ERROR] Could not find nightly test config name '
'in: {0}'.format(filename))
sys.exit(0)
if not filename_base.endswith(config_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
filename, config_name))
| Update config name verify script to work with the .bat files. | Update config name verify script to work with the .bat files.
| Python | apache-2.0 | chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel |
from __future__ import print_function
+ import os.path
+ import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
- config_name = content.split('"')[1]
- expected_script_name = 'test-{0}.bash'.format(config_name)
+ filename_parts = os.path.splitext(filename)
+ filename_base = filename_parts[0]
+ pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"',
+ re.IGNORECASE)
+ match = pattern.search(content)
+ config_name = None
+ if match is not None:
+ config_name = match.group('config_name')
+ else:
+ print('[ERROR] Could not find nightly test config name '
+ 'in: {0}'.format(filename))
+ sys.exit(0)
+
- if not filename.endswith(expected_script_name):
+ if not filename_base.endswith(config_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
filename, config_name))
| Update config name verify script to work with the .bat files. | ## Code Before:
from __future__ import print_function
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
config_name = content.split('"')[1]
expected_script_name = 'test-{0}.bash'.format(config_name)
if not filename.endswith(expected_script_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
filename, config_name))
## Instruction:
Update config name verify script to work with the .bat files.
## Code After:
from __future__ import print_function
import os.path
import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
filename_parts = os.path.splitext(filename)
filename_base = filename_parts[0]
pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"',
re.IGNORECASE)
match = pattern.search(content)
config_name = None
if match is not None:
config_name = match.group('config_name')
else:
print('[ERROR] Could not find nightly test config name '
'in: {0}'.format(filename))
sys.exit(0)
if not filename_base.endswith(config_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
filename, config_name))
| ...
import os.path
import re
import sys
...
filename_parts = os.path.splitext(filename)
filename_base = filename_parts[0]
pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"',
re.IGNORECASE)
match = pattern.search(content)
config_name = None
if match is not None:
config_name = match.group('config_name')
else:
print('[ERROR] Could not find nightly test config name '
'in: {0}'.format(filename))
sys.exit(0)
if not filename_base.endswith(config_name):
print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format(
... |
df2bf7cc95f38d9e6605dcc91e56b28502063b6a | apps/faqs/admin.py | apps/faqs/admin.py | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Category, Faq
@admin.register(Faq)
class FaqAdmin(SearchMetaBaseAdmin):
""" Admin settings for the Faq model """
prepopulated_fields = {"url_title": ("question",)}
filter_horizontal = ("categories",)
fieldsets = (
(None, {
"fields": (
"page",
"question",
"url_title",
"answer",
"categories",
"order",
)
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
""" Admin settings for the FAQ Category model. """
prepopulated_fields = {"url_title": ("title",)}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
| from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Category, Faq
@admin.register(Faq)
class FaqAdmin(SearchMetaBaseAdmin):
""" Admin settings for the Faq model """
prepopulated_fields = {"url_title": ("question",)}
filter_horizontal = ("categories",)
fieldsets = (
(None, {
"fields": ["page", "question", "url_title", "answer", "categories", "order"]
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
""" Admin settings for the FAQ Category model. """
prepopulated_fields = {
"slug": ("title",)
}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
| Fix usage of `url_title` in CategoryAdmin. | Fix usage of `url_title` in CategoryAdmin.
| Python | mit | onespacemedia/cms-faqs,onespacemedia/cms-faqs | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Category, Faq
@admin.register(Faq)
class FaqAdmin(SearchMetaBaseAdmin):
""" Admin settings for the Faq model """
prepopulated_fields = {"url_title": ("question",)}
filter_horizontal = ("categories",)
fieldsets = (
(None, {
+ "fields": ["page", "question", "url_title", "answer", "categories", "order"]
- "fields": (
- "page",
- "question",
- "url_title",
- "answer",
- "categories",
- "order",
- )
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
""" Admin settings for the FAQ Category model. """
- prepopulated_fields = {"url_title": ("title",)}
+ prepopulated_fields = {
+ "slug": ("title",)
+ }
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
| Fix usage of `url_title` in CategoryAdmin. | ## Code Before:
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Category, Faq
@admin.register(Faq)
class FaqAdmin(SearchMetaBaseAdmin):
""" Admin settings for the Faq model """
prepopulated_fields = {"url_title": ("question",)}
filter_horizontal = ("categories",)
fieldsets = (
(None, {
"fields": (
"page",
"question",
"url_title",
"answer",
"categories",
"order",
)
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
""" Admin settings for the FAQ Category model. """
prepopulated_fields = {"url_title": ("title",)}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
## Instruction:
Fix usage of `url_title` in CategoryAdmin.
## Code After:
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Category, Faq
@admin.register(Faq)
class FaqAdmin(SearchMetaBaseAdmin):
""" Admin settings for the Faq model """
prepopulated_fields = {"url_title": ("question",)}
filter_horizontal = ("categories",)
fieldsets = (
(None, {
"fields": ["page", "question", "url_title", "answer", "categories", "order"]
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
""" Admin settings for the FAQ Category model. """
prepopulated_fields = {
"slug": ("title",)
}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
| # ... existing code ...
(None, {
"fields": ["page", "question", "url_title", "answer", "categories", "order"]
}),
# ... modified code ...
prepopulated_fields = {
"slug": ("title",)
}
# ... rest of the code ... |
4785a5e8d639dea1a9cf767d2c77f6bd9dbe2433 | leapp/cli/upgrade/__init__.py | leapp/cli/upgrade/__init__.py | from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
| from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
manager = load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
| Add back missing manager creation | leapp: Add back missing manager creation
| Python | lgpl-2.1 | leapp-to/prototype,vinzenz/prototype,leapp-to/prototype,vinzenz/prototype,vinzenz/prototype,leapp-to/prototype,vinzenz/prototype,leapp-to/prototype | from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
- load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
+ manager = load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
| Add back missing manager creation | ## Code Before:
from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
## Instruction:
Add back missing manager creation
## Code After:
from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
manager = load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
| // ... existing code ...
def load_repositories():
manager = load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
// ... rest of the code ... |
c15875062be2b59c78fca9a224b0231986a37868 | feincms3/templatetags/feincms3_renderer.py | feincms3/templatetags/feincms3_renderer.py | from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
| from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
| Add note to render_plugin[s] that render_region should be preferred | Add note to render_plugin[s] that render_region should be preferred
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 | from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
+
+ In general you should prefer
+ :func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
+ tag.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
+
+ In general you should prefer
+ :func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
+ tag.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
| Add note to render_plugin[s] that render_region should be preferred | ## Code Before:
from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
## Instruction:
Add note to render_plugin[s] that render_region should be preferred
## Code After:
from django import template
from django.utils.html import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def render_plugin(context, plugin):
"""
Render a single plugin. See :mod:`feincms3.renderer` for additional
details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
return context['renderer'].render_plugin_in_context(plugin, context)
@register.simple_tag(takes_context=True)
def render_plugins(context, plugins):
"""
Render and concatenate a list of plugins. See
:mod:`feincms3.renderer` for additional details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
renderer = context['renderer']
return mark_safe(''.join(
renderer.render_plugin_in_context(plugin, context)
for plugin in plugins
))
@register.simple_tag(takes_context=True)
def render_region(context, regions, region, **kwargs):
"""
Render a single region. See :class:`~feincms3.renderer.Regions` for
additional details. Any and all keyword arguments are forwarded to the
``render`` method of the ``Regions`` instance.
"""
return regions.render(region, context, **kwargs)
| # ... existing code ...
details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
# ... modified code ...
:mod:`feincms3.renderer` for additional details.
In general you should prefer
:func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
tag.
"""
# ... rest of the code ... |
106833059bc2dad8a284de50e153bf673d2e3b4b | premis_event_service/urls.py | premis_event_service/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
| try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import * # In case of Django<=1.3
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
| Support new and old Django urlconf imports | Support new and old Django urlconf imports
| Python | bsd-3-clause | unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service | - from django.conf.urls.defaults import *
+ try:
+ from django.conf.urls import patterns, url
+ except ImportError:
+ from django.conf.urls.defaults import * # In case of Django<=1.3
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
| Support new and old Django urlconf imports | ## Code Before:
from django.conf.urls.defaults import *
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
## Instruction:
Support new and old Django urlconf imports
## Code After:
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import * # In case of Django<=1.3
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
| # ... existing code ...
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import * # In case of Django<=1.3
# ... rest of the code ... |
d74908f5acb5c1a88965ed086d41435e0041d85b | pyluos/modules/l0_dc_motor.py | pyluos/modules/l0_dc_motor.py | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| Fix l0 dc field name. | Fix l0 dc field name.
| Python | mit | pollen/pyrobus | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
+ field = self.name.replace('m', 's')
- self._delegate._push_value(self.name, self._speed)
+ self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| Fix l0 dc field name. | ## Code Before:
from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
## Instruction:
Fix l0 dc field name.
## Code After:
from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| ...
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
... |
dd35907f9164cd8f75babb1b5b9b6ff9711628fb | djangopeople/djangopeople/management/commands/fix_counts.py | djangopeople/djangopeople/management/commands/fix_counts.py | from django.core.management.base import NoArgsCommand
from ...models import Country, Region
class Command(NoArgsCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle_noargs(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
| from django.core.management.base import BaseCommand
from ...models import Country, Region
class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
| Remove usage of deprecated NoArgsCommand | Remove usage of deprecated NoArgsCommand
| Python | mit | brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,brutasse/djangopeople,brutasse/djangopeople | - from django.core.management.base import NoArgsCommand
+ from django.core.management.base import BaseCommand
from ...models import Country, Region
- class Command(NoArgsCommand):
+ class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
- def handle_noargs(self, **options):
+ def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
| Remove usage of deprecated NoArgsCommand | ## Code Before:
from django.core.management.base import NoArgsCommand
from ...models import Country, Region
class Command(NoArgsCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle_noargs(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
## Instruction:
Remove usage of deprecated NoArgsCommand
## Code After:
from django.core.management.base import BaseCommand
from ...models import Country, Region
class Command(BaseCommand):
"""
Countries and regions keep a denormalized count of people that gets out of
sync during migrate. This updates it.
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
for geo in qs:
qs.model.objects.filter(pk=geo.pk).update(
num_people=geo.djangoperson_set.count(),
)
| // ... existing code ...
from django.core.management.base import BaseCommand
// ... modified code ...
class Command(BaseCommand):
"""
...
"""
def handle(self, **options):
for qs in (Country.objects.all(), Region.objects.all()):
// ... rest of the code ... |
fb8cfa8eb7d088ebe11075bff42bea54c97e9c18 | hermes/views.py | hermes/views.py | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| Add slug variable to pass in the URL | Add slug variable to pass in the URL | Python | mit | emilian/django-hermes | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
+ slug = None
+
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| Add slug variable to pass in the URL | ## Code Before:
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
## Instruction:
Add slug variable to pass in the URL
## Code After:
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| // ... existing code ...
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
// ... rest of the code ... |
445bd6d2b5f68da6d51d9acb84b1e15e6b4af2d8 | k8s/models/common.py | k8s/models/common.py | from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = RequiredField(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(six.text_type)
labels = Field(dict)
annotations = Field(dict)
| from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = Field(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(six.text_type)
labels = Field(dict)
annotations = Field(dict)
generateName = Field(six.text_type)
| Add support for auto-generated names in metadata | Add support for auto-generated names in metadata
| Python | apache-2.0 | fiaas/k8s | from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
- name = RequiredField(six.text_type)
+ name = Field(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(six.text_type)
labels = Field(dict)
annotations = Field(dict)
+ generateName = Field(six.text_type)
| Add support for auto-generated names in metadata | ## Code Before:
from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = RequiredField(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(six.text_type)
labels = Field(dict)
annotations = Field(dict)
## Instruction:
Add support for auto-generated names in metadata
## Code After:
from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = Field(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(six.text_type)
labels = Field(dict)
annotations = Field(dict)
generateName = Field(six.text_type)
| // ... existing code ...
class ObjectMeta(Model):
name = Field(six.text_type)
namespace = Field(six.text_type, "default")
// ... modified code ...
annotations = Field(dict)
generateName = Field(six.text_type)
// ... rest of the code ... |
318cbaabb289034584cdfb82639c84ed91fc6e2e | tests/test_io.py | tests/test_io.py | import pytest
from pikepdf import Pdf
from io import BytesIO
@pytest.fixture
def sandwich(resources):
# Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP
return Pdf.open(resources / 'sandwich.pdf')
class LimitedBytesIO(BytesIO):
"""Version of BytesIO that only accepts small reads/writes"""
def write(self, b):
amt = min(len(b), 100)
return super().write(b[:amt])
def test_weird_output_stream(sandwich):
bio = BytesIO()
lbio = LimitedBytesIO()
sandwich.save(bio, static_id=True)
sandwich.save(lbio, static_id=True)
assert bio.getvalue() == lbio.getvalue()
def test_overwrite_with_memory_file(outdir):
(outdir / 'example.pdf').touch()
pdf = Pdf.new()
pdf.save(outdir / 'example.pdf')
| import pytest
from pikepdf import Pdf
from pikepdf._cpphelpers import fspath
from io import BytesIO
from shutil import copy
import sys
@pytest.fixture
def sandwich(resources):
# Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP
return Pdf.open(resources / 'sandwich.pdf')
class LimitedBytesIO(BytesIO):
"""Version of BytesIO that only accepts small reads/writes"""
def write(self, b):
amt = min(len(b), 100)
return super().write(b[:amt])
def test_weird_output_stream(sandwich):
bio = BytesIO()
lbio = LimitedBytesIO()
sandwich.save(bio, static_id=True)
sandwich.save(lbio, static_id=True)
assert bio.getvalue() == lbio.getvalue()
def test_overwrite_with_memory_file(outdir):
(outdir / 'example.pdf').touch()
pdf = Pdf.new()
pdf.save(outdir / 'example.pdf')
@pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil')
def test_overwrite_input(resources, outdir):
copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf')
p = Pdf.open(outdir / 'sandwich.pdf')
with pytest.raises(ValueError, match=r'overwrite input file'):
p.save(outdir / 'sandwich.pdf')
| Add test to check that we do not overwrite input file | Add test to check that we do not overwrite input file
| Python | mpl-2.0 | pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf | import pytest
from pikepdf import Pdf
+ from pikepdf._cpphelpers import fspath
from io import BytesIO
+ from shutil import copy
+ import sys
@pytest.fixture
def sandwich(resources):
# Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP
return Pdf.open(resources / 'sandwich.pdf')
class LimitedBytesIO(BytesIO):
"""Version of BytesIO that only accepts small reads/writes"""
def write(self, b):
amt = min(len(b), 100)
return super().write(b[:amt])
def test_weird_output_stream(sandwich):
bio = BytesIO()
lbio = LimitedBytesIO()
sandwich.save(bio, static_id=True)
sandwich.save(lbio, static_id=True)
assert bio.getvalue() == lbio.getvalue()
def test_overwrite_with_memory_file(outdir):
(outdir / 'example.pdf').touch()
pdf = Pdf.new()
pdf.save(outdir / 'example.pdf')
+
+ @pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil')
+ def test_overwrite_input(resources, outdir):
+ copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf')
+ p = Pdf.open(outdir / 'sandwich.pdf')
+ with pytest.raises(ValueError, match=r'overwrite input file'):
+ p.save(outdir / 'sandwich.pdf')
+ | Add test to check that we do not overwrite input file | ## Code Before:
import pytest
from pikepdf import Pdf
from io import BytesIO
@pytest.fixture
def sandwich(resources):
# Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP
return Pdf.open(resources / 'sandwich.pdf')
class LimitedBytesIO(BytesIO):
"""Version of BytesIO that only accepts small reads/writes"""
def write(self, b):
amt = min(len(b), 100)
return super().write(b[:amt])
def test_weird_output_stream(sandwich):
bio = BytesIO()
lbio = LimitedBytesIO()
sandwich.save(bio, static_id=True)
sandwich.save(lbio, static_id=True)
assert bio.getvalue() == lbio.getvalue()
def test_overwrite_with_memory_file(outdir):
(outdir / 'example.pdf').touch()
pdf = Pdf.new()
pdf.save(outdir / 'example.pdf')
## Instruction:
Add test to check that we do not overwrite input file
## Code After:
import pytest
from pikepdf import Pdf
from pikepdf._cpphelpers import fspath
from io import BytesIO
from shutil import copy
import sys
@pytest.fixture
def sandwich(resources):
# Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP
return Pdf.open(resources / 'sandwich.pdf')
class LimitedBytesIO(BytesIO):
"""Version of BytesIO that only accepts small reads/writes"""
def write(self, b):
amt = min(len(b), 100)
return super().write(b[:amt])
def test_weird_output_stream(sandwich):
bio = BytesIO()
lbio = LimitedBytesIO()
sandwich.save(bio, static_id=True)
sandwich.save(lbio, static_id=True)
assert bio.getvalue() == lbio.getvalue()
def test_overwrite_with_memory_file(outdir):
(outdir / 'example.pdf').touch()
pdf = Pdf.new()
pdf.save(outdir / 'example.pdf')
@pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil')
def test_overwrite_input(resources, outdir):
copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf')
p = Pdf.open(outdir / 'sandwich.pdf')
with pytest.raises(ValueError, match=r'overwrite input file'):
p.save(outdir / 'sandwich.pdf')
| ...
from pikepdf import Pdf
from pikepdf._cpphelpers import fspath
from io import BytesIO
from shutil import copy
import sys
...
pdf.save(outdir / 'example.pdf')
@pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil')
def test_overwrite_input(resources, outdir):
copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf')
p = Pdf.open(outdir / 'sandwich.pdf')
with pytest.raises(ValueError, match=r'overwrite input file'):
p.save(outdir / 'sandwich.pdf')
... |
e4ad2863236cd36e5860f1d17a06ca05e30216d5 | make_database.py | make_database.py | import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close()
| import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0,
name TEXT,
artist_name TEXT,
artist_uri TEXT,
artist_image TEXT,
album_name TEXT,
album_uri TEXT,
album_image TEXT
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close()
| Store more stuff about songs in the queue | Store more stuff about songs in the queue
| Python | mit | projectweekend/Pi-Jukebox,projectweekend/Pi-Jukebox,projectweekend/Pi-Jukebox | import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
- has_played INTEGER DEFAULT 0
+ has_played INTEGER DEFAULT 0,
+ name TEXT,
+ artist_name TEXT,
+ artist_uri TEXT,
+ artist_image TEXT,
+ album_name TEXT,
+ album_uri TEXT,
+ album_image TEXT
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close()
| Store more stuff about songs in the queue | ## Code Before:
import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close()
## Instruction:
Store more stuff about songs in the queue
## Code After:
import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0,
name TEXT,
artist_name TEXT,
artist_uri TEXT,
artist_image TEXT,
album_name TEXT,
album_uri TEXT,
album_image TEXT
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close()
| ...
spotify_uri TEXT,
has_played INTEGER DEFAULT 0,
name TEXT,
artist_name TEXT,
artist_uri TEXT,
artist_image TEXT,
album_name TEXT,
album_uri TEXT,
album_image TEXT
);
... |
b8ad378a796ee867acfa3198e04d47a500dd90d3 | mla/neuralnet/activations.py | mla/neuralnet/activations.py | import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
def linear(z):
return z
def softplus(z):
"""Smooth relu."""
# Avoid numerical overflow, see:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html
return np.logaddexp(0.0, z)
def softsign(z):
return z / (1 + np.abs(z))
def tanh(z):
return np.tanh(z)
def relu(z):
return np.maximum(0, z)
def get_activation(name):
"""Return activation function by name"""
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
| import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
def linear(z):
return z
def softplus(z):
"""Smooth relu."""
# Avoid numerical overflow, see:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html
return np.logaddexp(0.0, z)
def softsign(z):
return z / (1 + np.abs(z))
def tanh(z):
return np.tanh(z)
def relu(z):
return np.maximum(0, z)
def leakyrelu(z, a=0.01):
return np.maximum(z * a, z)
def get_activation(name):
"""Return activation function by name"""
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
| Add Leaky ReLU activation. Differentiation with autograd package confirmed to work correctly. | Add Leaky ReLU activation.
Differentiation with autograd package confirmed to work correctly.
| Python | mit | rushter/MLAlgorithms | import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
def linear(z):
return z
def softplus(z):
"""Smooth relu."""
# Avoid numerical overflow, see:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html
return np.logaddexp(0.0, z)
def softsign(z):
return z / (1 + np.abs(z))
def tanh(z):
return np.tanh(z)
def relu(z):
return np.maximum(0, z)
+ def leakyrelu(z, a=0.01):
+ return np.maximum(z * a, z)
+
+
def get_activation(name):
"""Return activation function by name"""
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
| Add Leaky ReLU activation. Differentiation with autograd package confirmed to work correctly. | ## Code Before:
import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
def linear(z):
return z
def softplus(z):
"""Smooth relu."""
# Avoid numerical overflow, see:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html
return np.logaddexp(0.0, z)
def softsign(z):
return z / (1 + np.abs(z))
def tanh(z):
return np.tanh(z)
def relu(z):
return np.maximum(0, z)
def get_activation(name):
"""Return activation function by name"""
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
## Instruction:
Add Leaky ReLU activation. Differentiation with autograd package confirmed to work correctly.
## Code After:
import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
def linear(z):
return z
def softplus(z):
"""Smooth relu."""
# Avoid numerical overflow, see:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.logaddexp.html
return np.logaddexp(0.0, z)
def softsign(z):
return z / (1 + np.abs(z))
def tanh(z):
return np.tanh(z)
def relu(z):
return np.maximum(0, z)
def leakyrelu(z, a=0.01):
return np.maximum(z * a, z)
def get_activation(name):
"""Return activation function by name"""
try:
return globals()[name]
except:
raise ValueError('Invalid activation function.')
| // ... existing code ...
def leakyrelu(z, a=0.01):
return np.maximum(z * a, z)
def get_activation(name):
// ... rest of the code ... |
3c264c4ddf3e21c3b0e495d663e78dc3c80ce949 | python/saliweb/test/MySQLdb/cursors.py | python/saliweb/test/MySQLdb/cursors.py | import datetime
class DictCursor(object):
def __init__(self, conn):
self.conn = conn
def execute(self, sql, args=()):
self.sql, self.args = sql, args
def fetchone(self):
if self.sql == 'SELECT * FROM jobs WHERE name=%s AND passwd=%s':
# Check completed jobs
for j in self.conn._jobs:
if self.args == (j.name, j.passwd):
return {'state': 'COMPLETED', 'name': j.name,
'passwd': j.passwd,
'archive_time': datetime.datetime(year=2099,
month=1, day=1),
'directory': j.directory}
# Check incoming jobs
for j in self.conn._incoming_jobs:
if self.args == (j['name'], j['passwd']):
return {'state': 'INCOMING', 'name': j['name'],
'contact_email': j['email'],
'submit_time': datetime.datetime(year=2000,
month=1, day=1)}
def __iter__(self):
return iter([])
| import datetime
class DictCursor(object):
def __init__(self, conn):
self.conn = conn
def execute(self, sql, args=()):
self.sql, self.args = sql, args
def fetchone(self):
if self.sql == 'SELECT * FROM jobs WHERE name=%s AND passwd=%s':
# Check completed jobs
for j in self.conn._jobs:
if self.args == (j.name, j.passwd):
return {'state': 'COMPLETED', 'name': j.name,
'passwd': j.passwd,
'archive_time': datetime.datetime(year=2099,
month=1, day=1),
'directory': j.directory,
'contact_email': '[email protected]'}
# Check incoming jobs
for j in self.conn._incoming_jobs:
if self.args == (j['name'], j['passwd']):
return {'state': 'INCOMING', 'name': j['name'],
'contact_email': j['email'],
'submit_time': datetime.datetime(year=2000,
month=1, day=1)}
def __iter__(self):
return iter([])
| Add support for completed-job email to mocks | Add support for completed-job email to mocks
| Python | lgpl-2.1 | salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb | import datetime
class DictCursor(object):
def __init__(self, conn):
self.conn = conn
def execute(self, sql, args=()):
self.sql, self.args = sql, args
def fetchone(self):
if self.sql == 'SELECT * FROM jobs WHERE name=%s AND passwd=%s':
# Check completed jobs
for j in self.conn._jobs:
if self.args == (j.name, j.passwd):
return {'state': 'COMPLETED', 'name': j.name,
'passwd': j.passwd,
'archive_time': datetime.datetime(year=2099,
month=1, day=1),
- 'directory': j.directory}
+ 'directory': j.directory,
+ 'contact_email': '[email protected]'}
# Check incoming jobs
for j in self.conn._incoming_jobs:
if self.args == (j['name'], j['passwd']):
return {'state': 'INCOMING', 'name': j['name'],
'contact_email': j['email'],
'submit_time': datetime.datetime(year=2000,
month=1, day=1)}
def __iter__(self):
return iter([])
| Add support for completed-job email to mocks | ## Code Before:
import datetime
class DictCursor(object):
def __init__(self, conn):
self.conn = conn
def execute(self, sql, args=()):
self.sql, self.args = sql, args
def fetchone(self):
if self.sql == 'SELECT * FROM jobs WHERE name=%s AND passwd=%s':
# Check completed jobs
for j in self.conn._jobs:
if self.args == (j.name, j.passwd):
return {'state': 'COMPLETED', 'name': j.name,
'passwd': j.passwd,
'archive_time': datetime.datetime(year=2099,
month=1, day=1),
'directory': j.directory}
# Check incoming jobs
for j in self.conn._incoming_jobs:
if self.args == (j['name'], j['passwd']):
return {'state': 'INCOMING', 'name': j['name'],
'contact_email': j['email'],
'submit_time': datetime.datetime(year=2000,
month=1, day=1)}
def __iter__(self):
return iter([])
## Instruction:
Add support for completed-job email to mocks
## Code After:
import datetime
class DictCursor(object):
def __init__(self, conn):
self.conn = conn
def execute(self, sql, args=()):
self.sql, self.args = sql, args
def fetchone(self):
if self.sql == 'SELECT * FROM jobs WHERE name=%s AND passwd=%s':
# Check completed jobs
for j in self.conn._jobs:
if self.args == (j.name, j.passwd):
return {'state': 'COMPLETED', 'name': j.name,
'passwd': j.passwd,
'archive_time': datetime.datetime(year=2099,
month=1, day=1),
'directory': j.directory,
'contact_email': '[email protected]'}
# Check incoming jobs
for j in self.conn._incoming_jobs:
if self.args == (j['name'], j['passwd']):
return {'state': 'INCOMING', 'name': j['name'],
'contact_email': j['email'],
'submit_time': datetime.datetime(year=2000,
month=1, day=1)}
def __iter__(self):
return iter([])
| # ... existing code ...
month=1, day=1),
'directory': j.directory,
'contact_email': '[email protected]'}
# Check incoming jobs
# ... rest of the code ... |
62e5867f9dc5a758e3803e66043255881c8250c2 | democracy_club/apps/dc_members/forms.py | democracy_club/apps/dc_members/forms.py | from django.forms import ModelForm
from localflavor.gb.forms import GBPostcodeField
from .models import Member
class MemberUpdateForm(ModelForm):
class Meta:
model = Member
exclude = ['token', 'user', 'constituency', 'mapit_json']
postcode = GBPostcodeField(required=True) | from django.forms import ModelForm
from localflavor.gb.forms import GBPostcodeField
from .models import Member
class MemberUpdateForm(ModelForm):
class Meta:
model = Member
exclude = [
'token',
'user',
'constituency',
'mapit_json',
'source',
]
postcode = GBPostcodeField(required=True)
| Exclude most fields from User Profiles | Exclude most fields from User Profiles
| Python | bsd-3-clause | DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website | from django.forms import ModelForm
from localflavor.gb.forms import GBPostcodeField
from .models import Member
class MemberUpdateForm(ModelForm):
class Meta:
model = Member
- exclude = ['token', 'user', 'constituency', 'mapit_json']
+ exclude = [
+ 'token',
+ 'user',
+ 'constituency',
+ 'mapit_json',
+ 'source',
+ ]
postcode = GBPostcodeField(required=True)
+ | Exclude most fields from User Profiles | ## Code Before:
from django.forms import ModelForm
from localflavor.gb.forms import GBPostcodeField
from .models import Member
class MemberUpdateForm(ModelForm):
class Meta:
model = Member
exclude = ['token', 'user', 'constituency', 'mapit_json']
postcode = GBPostcodeField(required=True)
## Instruction:
Exclude most fields from User Profiles
## Code After:
from django.forms import ModelForm
from localflavor.gb.forms import GBPostcodeField
from .models import Member
class MemberUpdateForm(ModelForm):
class Meta:
model = Member
exclude = [
'token',
'user',
'constituency',
'mapit_json',
'source',
]
postcode = GBPostcodeField(required=True)
| ...
model = Member
exclude = [
'token',
'user',
'constituency',
'mapit_json',
'source',
]
... |
db537ab80444b9e4cc22f332577c2cba640fca0a | tasks/factory_utils.py | tasks/factory_utils.py | from factory import enums
from collections import namedtuple
import gc
# Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes
# theirs easy to override!
enums.SPLITTER = "____"
# More flexible than FactoryBoy's sequences because you can create and
# destroy them where-ever you want.
class Adder:
def __init__(self, x=0):
self.x = x
def __call__(self, value):
self.x += value
return int(self.x)
def reset(self, x):
self.x = x
# Boilerplate that every factory would need to deal with.
def SessionBase(session):
class BaseMeta:
sqlalchemy_session = session
sqlalchemy_session_persistence = "commit"
return BaseMeta
# Thin collector for the factories and a place to try to achieve better
# scalability than the create_batch function from FactoryBoy.
class Factories:
unflushed_record_counter = 0
def __init__(self, session, namespace):
self.session = session
self.factory_classes = {
key: value for key, value in namespace.items() if hasattr(value, "generate_batch")
}
def create_batch(self, classname, batchsize, **kwargs):
cls = self.factory_classes.get(classname, None)
assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?"
for _ in range(batchsize):
cls.create(**kwargs)
| from factory import enums
from collections import namedtuple
import gc
# Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes
# theirs easy to override!
enums.SPLITTER = "____"
# More flexible than FactoryBoy's sequences because you can create and
# destroy them where-ever you want.
class Adder:
def __init__(self, x=0):
self.x = x
def __call__(self, value):
self.x += value
return int(self.x)
def reset(self, x):
self.x = x
# Boilerplate that every factory would need to deal with.
def SessionBase(session):
class BaseMeta:
sqlalchemy_session = session
sqlalchemy_session_persistence = "commit"
return BaseMeta
# Thin collector for the factories and a place to try to achieve better
# scalability than the create_batch function from FactoryBoy.
class Factories:
unflushed_record_counter = 0
def __init__(self, session, namespace):
self.session = session
self.factory_classes = {
key: value for key, value in namespace.items() if hasattr(value, "generate_batch")
}
def create_batch(self, classname, batchsize, **kwargs):
cls = self.factory_classes.get(classname, None)
assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?"
for _ in range(batchsize):
cls.create(**kwargs)
def __getitem__(self, name):
return self.factory_classes[name]
| Make it easy to get a single item. | Make it easy to get a single item.
| Python | bsd-3-clause | SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus | from factory import enums
from collections import namedtuple
import gc
# Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes
# theirs easy to override!
enums.SPLITTER = "____"
# More flexible than FactoryBoy's sequences because you can create and
# destroy them where-ever you want.
class Adder:
def __init__(self, x=0):
self.x = x
def __call__(self, value):
self.x += value
return int(self.x)
def reset(self, x):
self.x = x
# Boilerplate that every factory would need to deal with.
def SessionBase(session):
class BaseMeta:
sqlalchemy_session = session
sqlalchemy_session_persistence = "commit"
return BaseMeta
# Thin collector for the factories and a place to try to achieve better
# scalability than the create_batch function from FactoryBoy.
class Factories:
unflushed_record_counter = 0
def __init__(self, session, namespace):
self.session = session
self.factory_classes = {
key: value for key, value in namespace.items() if hasattr(value, "generate_batch")
}
def create_batch(self, classname, batchsize, **kwargs):
cls = self.factory_classes.get(classname, None)
assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?"
for _ in range(batchsize):
cls.create(**kwargs)
+ def __getitem__(self, name):
+ return self.factory_classes[name]
+ | Make it easy to get a single item. | ## Code Before:
from factory import enums
from collections import namedtuple
import gc
# Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes
# theirs easy to override!
enums.SPLITTER = "____"
# More flexible than FactoryBoy's sequences because you can create and
# destroy them where-ever you want.
class Adder:
def __init__(self, x=0):
self.x = x
def __call__(self, value):
self.x += value
return int(self.x)
def reset(self, x):
self.x = x
# Boilerplate that every factory would need to deal with.
def SessionBase(session):
class BaseMeta:
sqlalchemy_session = session
sqlalchemy_session_persistence = "commit"
return BaseMeta
# Thin collector for the factories and a place to try to achieve better
# scalability than the create_batch function from FactoryBoy.
class Factories:
unflushed_record_counter = 0
def __init__(self, session, namespace):
self.session = session
self.factory_classes = {
key: value for key, value in namespace.items() if hasattr(value, "generate_batch")
}
def create_batch(self, classname, batchsize, **kwargs):
cls = self.factory_classes.get(classname, None)
assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?"
for _ in range(batchsize):
cls.create(**kwargs)
## Instruction:
Make it easy to get a single item.
## Code After:
from factory import enums
from collections import namedtuple
import gc
# Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes
# theirs easy to override!
enums.SPLITTER = "____"
# More flexible than FactoryBoy's sequences because you can create and
# destroy them where-ever you want.
class Adder:
def __init__(self, x=0):
self.x = x
def __call__(self, value):
self.x += value
return int(self.x)
def reset(self, x):
self.x = x
# Boilerplate that every factory would need to deal with.
def SessionBase(session):
class BaseMeta:
sqlalchemy_session = session
sqlalchemy_session_persistence = "commit"
return BaseMeta
# Thin collector for the factories and a place to try to achieve better
# scalability than the create_batch function from FactoryBoy.
class Factories:
unflushed_record_counter = 0
def __init__(self, session, namespace):
self.session = session
self.factory_classes = {
key: value for key, value in namespace.items() if hasattr(value, "generate_batch")
}
def create_batch(self, classname, batchsize, **kwargs):
cls = self.factory_classes.get(classname, None)
assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?"
for _ in range(batchsize):
cls.create(**kwargs)
def __getitem__(self, name):
return self.factory_classes[name]
| // ... existing code ...
cls.create(**kwargs)
def __getitem__(self, name):
return self.factory_classes[name]
// ... rest of the code ... |
08afe7e2946f4343d016f55bfacb4f7bac1d3cb2 | herana/urls.py | herana/urls.py | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| Change admin index title: 'Dashboard' | Change admin index title: 'Dashboard'
| Python | mit | Code4SA/herana,Code4SA/herana,Code4SA/herana,Code4SA/herana | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
- from django.views.generic.base import RedirectView
+ admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| Change admin index title: 'Dashboard' | ## Code Before:
from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
## Instruction:
Change admin index title: 'Dashboard'
## Code After:
from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'),
url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),
)
| // ... existing code ...
from django.contrib import admin
admin.site.index_title = 'Dashboard'
// ... rest of the code ... |
ccb774b58ab7dbe704abfb7df3fa29915fad8f8f | examples/memnn/download.py | examples/memnn/download.py |
from six.moves.urllib import request
def main():
opener = request.FancyURLopener()
opener.addheaders = [('User-Agent', '')]
opener.retrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
|
from six.moves.urllib import request
def main():
request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
| Replace deprecated URLopener in `donwload.py` | Replace deprecated URLopener in `donwload.py`
| Python | mit | niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,pfnet/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,keisuke-umezawa/chainer,hvy/chainer,hvy/chainer,tkerola/chainer,hvy/chainer,chainer/chainer,chainer/chainer,okuta/chainer,niboshi/chainer |
from six.moves.urllib import request
def main():
+ request.urlretrieve(
- opener = request.FancyURLopener()
- opener.addheaders = [('User-Agent', '')]
- opener.retrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
| Replace deprecated URLopener in `donwload.py` | ## Code Before:
from six.moves.urllib import request
def main():
opener = request.FancyURLopener()
opener.addheaders = [('User-Agent', '')]
opener.retrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
## Instruction:
Replace deprecated URLopener in `donwload.py`
## Code After:
from six.moves.urllib import request
def main():
request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
| ...
def main():
request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
... |
2f65eba48e5bdeac85b12cac014cb648d068da46 | tests/test_utils.py | tests/test_utils.py | import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2) | import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link")) | Add unit test for is_safe_url utility function | Add unit test for is_safe_url utility function
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary | import unittest
from app import create_app, db
- from app.utils import get_or_create
+ from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
+
+ def test_is_safe_url(self):
+ with self.app.test_request_context():
+ self.assertFalse(is_safe_url("http://externalsite.com"))
+ self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
+ self.assertTrue(is_safe_url("safe_internal_link")) | Add unit test for is_safe_url utility function | ## Code Before:
import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
## Instruction:
Add unit test for is_safe_url utility function
## Code After:
import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link")) | # ... existing code ...
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
# ... modified code ...
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
# ... rest of the code ... |
27839484173c4d505ddb9f949da3576f180b8266 | tests/test_short_url.py | tests/test_short_url.py |
from random import randrange
from pytest import raises
import short_url
def test_custom_alphabet():
encoder = short_url.UrlEncoder(alphabet='ab')
url = encoder.encode_url(12)
assert url == 'bbaaaaaaaaaaaaaaaaaaaa'
key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa')
assert key == 12
def test_too_short_alphabet():
with raises(AttributeError):
short_url.UrlEncoder(alphabet='aa')
with raises(AttributeError):
short_url.UrlEncoder(alphabet='a')
|
import os
from random import randrange
from pytest import raises
import short_url
TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
TEST_DATA = os.path.join(TEST_DATA, 'tests/data')
def generate_test_data(count=10000):
result = {}
for i in range(1000):
value = short_url.encode_url(i)
result[i] = value
while len(result) < count:
random_int = randrange(1000000)
value = short_url.encode_url(random_int)
result[random_int] = value
with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f:
for k, v in result.items():
f.write('%s:%s\n' % (k, v))
# generate_test_data()
def test_custom_alphabet():
encoder = short_url.UrlEncoder(alphabet='ab')
url = encoder.encode_url(12)
assert url == 'bbaaaaaaaaaaaaaaaaaaaa'
key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa')
assert key == 12
def test_too_short_alphabet():
with raises(AttributeError):
short_url.UrlEncoder(alphabet='aa')
with raises(AttributeError):
short_url.UrlEncoder(alphabet='a')
| Add function for generating test data | Add function for generating test data
| Python | mit | Alir3z4/python-short_url |
+ import os
from random import randrange
from pytest import raises
import short_url
+ TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
+ TEST_DATA = os.path.join(TEST_DATA, 'tests/data')
+
+ def generate_test_data(count=10000):
+ result = {}
+
+ for i in range(1000):
+ value = short_url.encode_url(i)
+ result[i] = value
+
+ while len(result) < count:
+ random_int = randrange(1000000)
+ value = short_url.encode_url(random_int)
+ result[random_int] = value
+
+ with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f:
+ for k, v in result.items():
+ f.write('%s:%s\n' % (k, v))
+
+ # generate_test_data()
def test_custom_alphabet():
encoder = short_url.UrlEncoder(alphabet='ab')
url = encoder.encode_url(12)
assert url == 'bbaaaaaaaaaaaaaaaaaaaa'
key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa')
assert key == 12
def test_too_short_alphabet():
with raises(AttributeError):
short_url.UrlEncoder(alphabet='aa')
with raises(AttributeError):
short_url.UrlEncoder(alphabet='a')
| Add function for generating test data | ## Code Before:
from random import randrange
from pytest import raises
import short_url
def test_custom_alphabet():
encoder = short_url.UrlEncoder(alphabet='ab')
url = encoder.encode_url(12)
assert url == 'bbaaaaaaaaaaaaaaaaaaaa'
key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa')
assert key == 12
def test_too_short_alphabet():
with raises(AttributeError):
short_url.UrlEncoder(alphabet='aa')
with raises(AttributeError):
short_url.UrlEncoder(alphabet='a')
## Instruction:
Add function for generating test data
## Code After:
import os
from random import randrange
from pytest import raises
import short_url
TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
TEST_DATA = os.path.join(TEST_DATA, 'tests/data')
def generate_test_data(count=10000):
result = {}
for i in range(1000):
value = short_url.encode_url(i)
result[i] = value
while len(result) < count:
random_int = randrange(1000000)
value = short_url.encode_url(random_int)
result[random_int] = value
with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f:
for k, v in result.items():
f.write('%s:%s\n' % (k, v))
# generate_test_data()
def test_custom_alphabet():
encoder = short_url.UrlEncoder(alphabet='ab')
url = encoder.encode_url(12)
assert url == 'bbaaaaaaaaaaaaaaaaaaaa'
key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa')
assert key == 12
def test_too_short_alphabet():
with raises(AttributeError):
short_url.UrlEncoder(alphabet='aa')
with raises(AttributeError):
short_url.UrlEncoder(alphabet='a')
| ...
import os
from random import randrange
...
TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
TEST_DATA = os.path.join(TEST_DATA, 'tests/data')
def generate_test_data(count=10000):
result = {}
for i in range(1000):
value = short_url.encode_url(i)
result[i] = value
while len(result) < count:
random_int = randrange(1000000)
value = short_url.encode_url(random_int)
result[random_int] = value
with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f:
for k, v in result.items():
f.write('%s:%s\n' % (k, v))
# generate_test_data()
... |
acd4238dce39464e99964227dca7758cffedca39 | gaphor/UML/classes/tests/test_containmentconnect.py | gaphor/UML/classes/tests/test_containmentconnect.py | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
| """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
def test_containment_package_class(create, diagram):
"""Test containment connecting to a package and a class."""
package = create(ContainmentItem, UML.Package)
line = create(ContainmentItem)
ac = create(ClassItem, UML.Class)
connect(line, line.head, package)
connect(line, line.tail, ac)
assert diagram.connections.get_connection(line.tail).connected is ac
assert len(package.subject.ownedElement) == 1
assert ac.subject in package.subject.ownedElement
| Add test for connecting containment to package and a class | Add test for connecting containment to package and a class [skip ci]
Signed-off-by: Dan Yeaw <[email protected]>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
- from gaphor.UML.classes import PackageItem
+ from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
+
+ def test_containment_package_class(create, diagram):
+ """Test containment connecting to a package and a class."""
+ package = create(ContainmentItem, UML.Package)
+ line = create(ContainmentItem)
+ ac = create(ClassItem, UML.Class)
+
+ connect(line, line.head, package)
+ connect(line, line.tail, ac)
+ assert diagram.connections.get_connection(line.tail).connected is ac
+ assert len(package.subject.ownedElement) == 1
+ assert ac.subject in package.subject.ownedElement
+ | Add test for connecting containment to package and a class | ## Code Before:
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
## Instruction:
Add test for connecting containment to package and a class
## Code After:
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
def test_containment_package_class(create, diagram):
"""Test containment connecting to a package and a class."""
package = create(ContainmentItem, UML.Package)
line = create(ContainmentItem)
ac = create(ClassItem, UML.Class)
connect(line, line.head, package)
connect(line, line.tail, ac)
assert diagram.connections.get_connection(line.tail).connected is ac
assert len(package.subject.ownedElement) == 1
assert ac.subject in package.subject.ownedElement
| // ... existing code ...
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
// ... modified code ...
assert glued
def test_containment_package_class(create, diagram):
"""Test containment connecting to a package and a class."""
package = create(ContainmentItem, UML.Package)
line = create(ContainmentItem)
ac = create(ClassItem, UML.Class)
connect(line, line.head, package)
connect(line, line.tail, ac)
assert diagram.connections.get_connection(line.tail).connected is ac
assert len(package.subject.ownedElement) == 1
assert ac.subject in package.subject.ownedElement
// ... rest of the code ... |
327413aa982dec1c56691ea0017298a2ae7af2c1 | integration_tests/hello_world/__init__.py | integration_tests/hello_world/__init__.py | integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
| integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
def check_state(state):
assert('Hello World!' in state.console)
assert('not in console' in state.console)
| Add an integration test that deliberately fails | Add an integration test that deliberately fails
| Python | bsd-2-clause | unigornel/unigornel,unigornel/unigornel | integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
+ def check_state(state):
+ assert('Hello World!' in state.console)
+ assert('not in console' in state.console)
+ | Add an integration test that deliberately fails | ## Code Before:
integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
## Instruction:
Add an integration test that deliberately fails
## Code After:
integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
def check_state(state):
assert('Hello World!' in state.console)
assert('not in console' in state.console)
| # ... existing code ...
can_shutdown = True
def check_state(state):
assert('Hello World!' in state.console)
assert('not in console' in state.console)
# ... rest of the code ... |
9c762d01b6dafd48d227c0ef927b844a257ff1b9 | joommf/energies/test_demag.py | joommf/energies/test_demag.py | from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
| from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
assert demag.__repr__() == "This is the energy class of type Demag"
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
| Increase test coverage for energy classes | Increase test coverage for energy classes
| Python | bsd-2-clause | ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python | from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
-
+ assert demag.__repr__() == "This is the energy class of type Demag"
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
| Increase test coverage for energy classes | ## Code Before:
from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
## Instruction:
Increase test coverage for energy classes
## Code After:
from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
assert demag.__repr__() == "This is the energy class of type Demag"
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string[-2] == '\n'
| ...
assert 'Specify Oxs_Demag {}' in mif_string
assert demag.__repr__() == "This is the energy class of type Demag"
... |
31e4da5e782c29d7d0c893a3fc9af48260c50a3a | src/ansible/views.py | src/ansible/views.py | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from formtools.wizard.views import SessionWizardView
from ansible.models import Github
def index(request):
return HttpResponse("200")
class PlaybookWizard(SessionWizardView):
def get_form_initial(self, step):
initial = {}
if step == '1':
prev_data = self.storage.get_step_data('0')
initial['name'] = prev_data['0-repository']
return self.initial_dict.get(step, initial)
return self.initial_dict.get(step, {})
def done(self, form_list, **kwargs):
form_data = {}
for form in form_list:
form.save()
return HttpResponseRedirect('/ansible')
| from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from formtools.wizard.views import SessionWizardView
from ansible.models import Github, Playbook
import sys
def index(request):
return HttpResponse("200")
class PlaybookWizard(SessionWizardView):
def get_form_initial(self, step):
initial = {}
if step == '1':
prev_data = self.storage.get_step_data('0')
initial['name'] = prev_data['0-repository']
return self.initial_dict.get(step, initial)
return self.initial_dict.get(step, {})
def get_form_step_data(self, form):
data = {}
if self.get_form_prefix() == '0':
github = Github()
github.repository = form.data.dict()['0-repository']
github.username = form.data.dict()['0-username']
github.save()
if self.get_form_prefix() == '1':
playbook = Playbook()
playbook.name = form.data.dict()['1-name']
playbook.inventory = form.data.dict()['1-inventory']
playbook.user = form.data.dict()['1-user']
playbook.save()
return form.data
def done(self, form_list, **kwargs):
return HttpResponseRedirect('/ansible')
| Save form data to DB on each step | Save form data to DB on each step
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from formtools.wizard.views import SessionWizardView
- from ansible.models import Github
+ from ansible.models import Github, Playbook
+ import sys
+
def index(request):
return HttpResponse("200")
+
class PlaybookWizard(SessionWizardView):
def get_form_initial(self, step):
initial = {}
if step == '1':
prev_data = self.storage.get_step_data('0')
initial['name'] = prev_data['0-repository']
return self.initial_dict.get(step, initial)
return self.initial_dict.get(step, {})
+ def get_form_step_data(self, form):
+ data = {}
+ if self.get_form_prefix() == '0':
+ github = Github()
+ github.repository = form.data.dict()['0-repository']
+ github.username = form.data.dict()['0-username']
+ github.save()
+
+ if self.get_form_prefix() == '1':
+ playbook = Playbook()
+ playbook.name = form.data.dict()['1-name']
+ playbook.inventory = form.data.dict()['1-inventory']
+ playbook.user = form.data.dict()['1-user']
+ playbook.save()
+
+ return form.data
+
+
def done(self, form_list, **kwargs):
- form_data = {}
- for form in form_list:
- form.save()
-
return HttpResponseRedirect('/ansible')
+ | Save form data to DB on each step | ## Code Before:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from formtools.wizard.views import SessionWizardView
from ansible.models import Github
def index(request):
return HttpResponse("200")
class PlaybookWizard(SessionWizardView):
def get_form_initial(self, step):
initial = {}
if step == '1':
prev_data = self.storage.get_step_data('0')
initial['name'] = prev_data['0-repository']
return self.initial_dict.get(step, initial)
return self.initial_dict.get(step, {})
def done(self, form_list, **kwargs):
form_data = {}
for form in form_list:
form.save()
return HttpResponseRedirect('/ansible')
## Instruction:
Save form data to DB on each step
## Code After:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from formtools.wizard.views import SessionWizardView
from ansible.models import Github, Playbook
import sys
def index(request):
return HttpResponse("200")
class PlaybookWizard(SessionWizardView):
def get_form_initial(self, step):
initial = {}
if step == '1':
prev_data = self.storage.get_step_data('0')
initial['name'] = prev_data['0-repository']
return self.initial_dict.get(step, initial)
return self.initial_dict.get(step, {})
def get_form_step_data(self, form):
data = {}
if self.get_form_prefix() == '0':
github = Github()
github.repository = form.data.dict()['0-repository']
github.username = form.data.dict()['0-username']
github.save()
if self.get_form_prefix() == '1':
playbook = Playbook()
playbook.name = form.data.dict()['1-name']
playbook.inventory = form.data.dict()['1-inventory']
playbook.user = form.data.dict()['1-user']
playbook.save()
return form.data
def done(self, form_list, **kwargs):
return HttpResponseRedirect('/ansible')
| // ... existing code ...
from formtools.wizard.views import SessionWizardView
from ansible.models import Github, Playbook
import sys
// ... modified code ...
return HttpResponse("200")
...
def get_form_step_data(self, form):
data = {}
if self.get_form_prefix() == '0':
github = Github()
github.repository = form.data.dict()['0-repository']
github.username = form.data.dict()['0-username']
github.save()
if self.get_form_prefix() == '1':
playbook = Playbook()
playbook.name = form.data.dict()['1-name']
playbook.inventory = form.data.dict()['1-inventory']
playbook.user = form.data.dict()['1-user']
playbook.save()
return form.data
def done(self, form_list, **kwargs):
return HttpResponseRedirect('/ansible')
// ... rest of the code ... |
84d743476261d30b352e3bfc103d76e7e8350b4c | tests/test_urls.py | tests/test_urls.py |
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from urltools import compare
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify that CAS is wired up properly when enabled"""
with self.settings(
CAS_ENABLED=True,
CAS_SERVER_URL='http://example.com/login',
):
# Because this won't actually work, we get in a redirect
# loop, or at least, best as I can tell.
response = self.client.get(reverse('cas_login'))
self.assertTrue(compare(
'http://example.com/login?'
'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F',
response['location']
))
def test_cas_disable(self):
"""Verify that when CAS is disabled, login is default"""
with self.settings(
CAS_ENABLED=False
):
response = self.client.get('/login', follow=True)
self.assertEqual(404, response.status_code)
|
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
import ssl
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access
from urltools import compare # noqa
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify that CAS is wired up properly when enabled"""
with self.settings(
CAS_ENABLED=True,
CAS_SERVER_URL='http://example.com/login',
):
# Because this won't actually work, we get in a redirect
# loop, or at least, best as I can tell.
response = self.client.get(reverse('cas_login'))
self.assertTrue(compare(
'http://example.com/login?'
'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F',
response['location']
))
def test_cas_disable(self):
"""Verify that when CAS is disabled, login is default"""
with self.settings(
CAS_ENABLED=False
):
response = self.client.get('/login', follow=True)
self.assertEqual(404, response.status_code)
| Disable SSL validation for a test which uses urltools | Disable SSL validation for a test which uses urltools
This is currently a common problem with python >= 2.7.9:
http://stackoverflow.com/questions/27835619/ssl-certificate-verify-failed-error
| Python | agpl-3.0 | mitodl/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,mitodl/lore,mitodl/lore,mitodl/lore,amir-qayyum-khan/lore,mitodl/lore |
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
+
+ import ssl
+
+ if hasattr(ssl, '_create_unverified_context'):
+ ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access
+
- from urltools import compare
+ from urltools import compare # noqa
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify that CAS is wired up properly when enabled"""
with self.settings(
CAS_ENABLED=True,
CAS_SERVER_URL='http://example.com/login',
):
# Because this won't actually work, we get in a redirect
# loop, or at least, best as I can tell.
response = self.client.get(reverse('cas_login'))
self.assertTrue(compare(
'http://example.com/login?'
'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F',
response['location']
))
def test_cas_disable(self):
"""Verify that when CAS is disabled, login is default"""
with self.settings(
CAS_ENABLED=False
):
response = self.client.get('/login', follow=True)
self.assertEqual(404, response.status_code)
| Disable SSL validation for a test which uses urltools | ## Code Before:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from urltools import compare
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify that CAS is wired up properly when enabled"""
with self.settings(
CAS_ENABLED=True,
CAS_SERVER_URL='http://example.com/login',
):
# Because this won't actually work, we get in a redirect
# loop, or at least, best as I can tell.
response = self.client.get(reverse('cas_login'))
self.assertTrue(compare(
'http://example.com/login?'
'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F',
response['location']
))
def test_cas_disable(self):
"""Verify that when CAS is disabled, login is default"""
with self.settings(
CAS_ENABLED=False
):
response = self.client.get('/login', follow=True)
self.assertEqual(404, response.status_code)
## Instruction:
Disable SSL validation for a test which uses urltools
## Code After:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
import ssl
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access
from urltools import compare # noqa
class TestURLs(TestCase):
"""Verify project level URL configuration."""
def test_cas_enabled(self):
"""Verify that CAS is wired up properly when enabled"""
with self.settings(
CAS_ENABLED=True,
CAS_SERVER_URL='http://example.com/login',
):
# Because this won't actually work, we get in a redirect
# loop, or at least, best as I can tell.
response = self.client.get(reverse('cas_login'))
self.assertTrue(compare(
'http://example.com/login?'
'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F',
response['location']
))
def test_cas_disable(self):
"""Verify that when CAS is disabled, login is default"""
with self.settings(
CAS_ENABLED=False
):
response = self.client.get('/login', follow=True)
self.assertEqual(404, response.status_code)
| # ... existing code ...
from django.test import TestCase
import ssl
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access
from urltools import compare # noqa
# ... rest of the code ... |
f61c0a33a79fa4670874f4469e7ceb76c644bf4b | lambda_local/environment_variables.py | lambda_local/environment_variables.py | import json
import os
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
```
:param json_file_path: path to flat json file
:type json_file_path: str
"""
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
for env_name, env_value in env_vars.items():
os.environ[str(env_name)] = str(env_value)
| import json
import os
def export_variables(environment_variables):
for env_name, env_value in environment_variables.items():
os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
```
:param json_file_path: path to flat json file
:type json_file_path: str
"""
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
export_variables(env_vars)
| Split the parsing of input and the exporting of the variables for reuse | Split the parsing of input and the exporting of the variables for
reuse
| Python | mit | HDE/python-lambda-local,HDE/python-lambda-local | import json
import os
+
+
+ def export_variables(environment_variables):
+ for env_name, env_value in environment_variables.items():
+ os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
```
:param json_file_path: path to flat json file
:type json_file_path: str
"""
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
+ export_variables(env_vars)
- for env_name, env_value in env_vars.items():
- os.environ[str(env_name)] = str(env_value)
| Split the parsing of input and the exporting of the variables for reuse | ## Code Before:
import json
import os
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
```
:param json_file_path: path to flat json file
:type json_file_path: str
"""
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
for env_name, env_value in env_vars.items():
os.environ[str(env_name)] = str(env_value)
## Instruction:
Split the parsing of input and the exporting of the variables for reuse
## Code After:
import json
import os
def export_variables(environment_variables):
for env_name, env_value in environment_variables.items():
os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
```
:param json_file_path: path to flat json file
:type json_file_path: str
"""
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
export_variables(env_vars)
| # ... existing code ...
import os
def export_variables(environment_variables):
for env_name, env_value in environment_variables.items():
os.environ[str(env_name)] = str(env_value)
# ... modified code ...
export_variables(env_vars)
# ... rest of the code ... |
2c5fb5a0bcf47e49c9862891730615f6c180462f | crmapp/subscribers/forms.py | crmapp/subscribers/forms.py | from django import forms
from django.contrib.auth.forms import UserCreationForm
class SubscriberForm(UserCreationForm):
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
| from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Subscriber
class AddressMixin(forms.ModelForm):
class Meta:
model = Subscriber
fields = ('address_one', 'address_two', 'city', 'state',)
widgets = {
'address_one': forms.TextInput(attrs={'class':'form-control'}),
'address_two': forms.TextInput(attrs={'class':'form-control'}),
'city': forms.TextInput(attrs={'class':'form-control'}),
'state': forms.TextInput(attrs={'class':'form-control'}),
}
class SubscriberForm(AddressMixin, UserCreationForm):
first_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
last_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
| Create the Subscriber Form - Part II > Update the Form | Create the Subscriber Form - Part II > Update the Form
| Python | mit | tabdon/crmeasyapp,tabdon/crmeasyapp,deenaariff/Django | from django import forms
from django.contrib.auth.forms import UserCreationForm
+ from .models import Subscriber
+
+
+ class AddressMixin(forms.ModelForm):
+ class Meta:
+ model = Subscriber
+ fields = ('address_one', 'address_two', 'city', 'state',)
+ widgets = {
+ 'address_one': forms.TextInput(attrs={'class':'form-control'}),
+ 'address_two': forms.TextInput(attrs={'class':'form-control'}),
+ 'city': forms.TextInput(attrs={'class':'form-control'}),
+ 'state': forms.TextInput(attrs={'class':'form-control'}),
+ }
+
- class SubscriberForm(UserCreationForm):
+ class SubscriberForm(AddressMixin, UserCreationForm):
+ first_name = forms.CharField(
+ required=True, widget=forms.TextInput(attrs={'class':'form-control'})
+ )
+ last_name = forms.CharField(
+ required=True, widget=forms.TextInput(attrs={'class':'form-control'})
+ )
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
| Create the Subscriber Form - Part II > Update the Form | ## Code Before:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class SubscriberForm(UserCreationForm):
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
## Instruction:
Create the Subscriber Form - Part II > Update the Form
## Code After:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Subscriber
class AddressMixin(forms.ModelForm):
class Meta:
model = Subscriber
fields = ('address_one', 'address_two', 'city', 'state',)
widgets = {
'address_one': forms.TextInput(attrs={'class':'form-control'}),
'address_two': forms.TextInput(attrs={'class':'form-control'}),
'city': forms.TextInput(attrs={'class':'form-control'}),
'state': forms.TextInput(attrs={'class':'form-control'}),
}
class SubscriberForm(AddressMixin, UserCreationForm):
first_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
last_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
| # ... existing code ...
from .models import Subscriber
class AddressMixin(forms.ModelForm):
class Meta:
model = Subscriber
fields = ('address_one', 'address_two', 'city', 'state',)
widgets = {
'address_one': forms.TextInput(attrs={'class':'form-control'}),
'address_two': forms.TextInput(attrs={'class':'form-control'}),
'city': forms.TextInput(attrs={'class':'form-control'}),
'state': forms.TextInput(attrs={'class':'form-control'}),
}
class SubscriberForm(AddressMixin, UserCreationForm):
first_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
last_name = forms.CharField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
email = forms.EmailField(
# ... rest of the code ... |
c9c618cfcd8caeac9ba23ec1c53d3ebdf32d563d | src/cli/_errors.py | src/cli/_errors.py |
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
|
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
| Add an exception useful for prototyping. | Add an exception useful for prototyping.
Signed-off-by: mulhern <[email protected]>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli |
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
+
+ class StratisCliValueUnimplementedError(StratisCliValueError):
+ """
+ Raised if a parameter is not intrinsically bad but functionality
+ is unimplemented for this value.
+ """
+ pass
+ | Add an exception useful for prototyping. | ## Code Before:
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
## Instruction:
Add an exception useful for prototyping.
## Code After:
class StratisCliError(Exception):
"""
Top-level stratis cli error.
"""
pass
class StratisCliValueError(StratisCliError):
""" Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
""" Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self): # pragma: no cover
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
else:
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
| # ... existing code ...
return self._FMT_STR % (self._value, self._param)
class StratisCliValueUnimplementedError(StratisCliValueError):
"""
Raised if a parameter is not intrinsically bad but functionality
is unimplemented for this value.
"""
pass
# ... rest of the code ... |
a6a81790d43442f88738e5ae141f6b9c6d0efc74 | authentication/urls.py | authentication/urls.py | from django.conf.urls import patterns, url
from authentication.views import user_login, user_logout
from authentication.views import approve, UnapprovedUsers, CustomAdminIndex
from authentication.views import BeneficiaryRegistrationView, DonorRegistrationView
urlpatterns = patterns('',
url(r'^register/donor$', DonorRegistrationView.as_view(), name='donor'),
url(r'^register/beneficiary$',
BeneficiaryRegistrationView.as_view(), name='beneficiary'),
url(r'^login/$', user_login, name='login'),
url(r'^logout/$', user_logout, name='logout'),
url(r'^$', CustomAdminIndex.as_view(), name='customadmin_index'),
url(r'^unapproved-users$', UnapprovedUsers.as_view(), name='unapproved'),
url(r'^approve/(?P<user_id>\d+)$', approve, name='approve'),
)
| from django.conf.urls import patterns, url
from .views import user_login, user_logout
from .views import approve, UnapprovedUsers, CustomAdminIndex
from .views import BeneficiaryRegistrationView, DonorRegistrationView
urlpatterns = patterns('',
url(r'^register/donor$', DonorRegistrationView.as_view(), name='donor'),
url(r'^register/beneficiary$',
BeneficiaryRegistrationView.as_view(), name='beneficiary'),
url(r'^login/$', user_login, name='login'),
url(r'^logout/$', user_logout, name='logout'),
url(r'^$', CustomAdminIndex.as_view(), name='customadmin_index'),
url(r'^unapproved-users$', UnapprovedUsers.as_view(), name='unapproved'),
url(r'^approve/(?P<user_id>\d+)$', approve, name='approve'),
)
| Use relative import for files inside the same package | Use relative import for files inside the same package
| Python | bsd-3-clause | agiliq/fundraiser,febinstephen/django-fundrasiser-app,agiliq/fundraiser,febinstephen/django-fundrasiser-app,febinstephen/django-fundrasiser-app,agiliq/fundraiser | from django.conf.urls import patterns, url
- from authentication.views import user_login, user_logout
+ from .views import user_login, user_logout
- from authentication.views import approve, UnapprovedUsers, CustomAdminIndex
+ from .views import approve, UnapprovedUsers, CustomAdminIndex
- from authentication.views import BeneficiaryRegistrationView, DonorRegistrationView
+ from .views import BeneficiaryRegistrationView, DonorRegistrationView
urlpatterns = patterns('',
url(r'^register/donor$', DonorRegistrationView.as_view(), name='donor'),
url(r'^register/beneficiary$',
BeneficiaryRegistrationView.as_view(), name='beneficiary'),
url(r'^login/$', user_login, name='login'),
url(r'^logout/$', user_logout, name='logout'),
url(r'^$', CustomAdminIndex.as_view(), name='customadmin_index'),
url(r'^unapproved-users$', UnapprovedUsers.as_view(), name='unapproved'),
url(r'^approve/(?P<user_id>\d+)$', approve, name='approve'),
)
| Use relative import for files inside the same package | ## Code Before:
from django.conf.urls import patterns, url
from authentication.views import user_login, user_logout
from authentication.views import approve, UnapprovedUsers, CustomAdminIndex
from authentication.views import BeneficiaryRegistrationView, DonorRegistrationView
urlpatterns = patterns('',
url(r'^register/donor$', DonorRegistrationView.as_view(), name='donor'),
url(r'^register/beneficiary$',
BeneficiaryRegistrationView.as_view(), name='beneficiary'),
url(r'^login/$', user_login, name='login'),
url(r'^logout/$', user_logout, name='logout'),
url(r'^$', CustomAdminIndex.as_view(), name='customadmin_index'),
url(r'^unapproved-users$', UnapprovedUsers.as_view(), name='unapproved'),
url(r'^approve/(?P<user_id>\d+)$', approve, name='approve'),
)
## Instruction:
Use relative import for files inside the same package
## Code After:
from django.conf.urls import patterns, url
from .views import user_login, user_logout
from .views import approve, UnapprovedUsers, CustomAdminIndex
from .views import BeneficiaryRegistrationView, DonorRegistrationView
urlpatterns = patterns('',
url(r'^register/donor$', DonorRegistrationView.as_view(), name='donor'),
url(r'^register/beneficiary$',
BeneficiaryRegistrationView.as_view(), name='beneficiary'),
url(r'^login/$', user_login, name='login'),
url(r'^logout/$', user_logout, name='logout'),
url(r'^$', CustomAdminIndex.as_view(), name='customadmin_index'),
url(r'^unapproved-users$', UnapprovedUsers.as_view(), name='unapproved'),
url(r'^approve/(?P<user_id>\d+)$', approve, name='approve'),
)
| # ... existing code ...
from .views import user_login, user_logout
from .views import approve, UnapprovedUsers, CustomAdminIndex
from .views import BeneficiaryRegistrationView, DonorRegistrationView
# ... rest of the code ... |
9c0d1f252bad1837545fa848c39786a98e6fd0ea | setup.py | setup.py | from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='[email protected]',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
| from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='[email protected]',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
| Add client part of package | Add client part of package
| Python | mit | Tatsh/xirvik-tools | from distutils.core import setup
setup(
name='xirvik-tools',
- version='0.0.1',
+ version='0.0.2',
author='Fa An',
author_email='[email protected]',
- packages=['xirvik'],
+ packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
| Add client part of package | ## Code Before:
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='[email protected]',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
## Instruction:
Add client part of package
## Code After:
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='[email protected]',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
| // ... existing code ...
name='xirvik-tools',
version='0.0.2',
author='Fa An',
// ... modified code ...
author_email='[email protected]',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
// ... rest of the code ... |
25af2e47b5b107ce4a0be4963b70bbf04b22c142 | tests/test_element.py | tests/test_element.py | import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
| import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| Add basic element pickle cycle test | Add basic element pickle cycle test
| Python | lgpl-2.1 | dwhswenson/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,gph82/mdtraj,dwhswenson/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,leeping/mdtraj,gph82/mdtraj,leeping/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,dwhswenson/mdtraj,mdtraj/mdtraj,gph82/mdtraj,leeping/mdtraj,leeping/mdtraj,mattwthompson/mdtraj,mdtraj/mdtraj,mdtraj/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj | import mdtraj as md
import pytest
+ import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
+
+ def test_element_pickle():
+ """Test that every Element object can pickle and de-pickle"""
+ for el in dir(element):
+ if isinstance(el, element.Element):
+ assert el == pickle.loads(pickle.dumps(el))
+ | Add basic element pickle cycle test | ## Code Before:
import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
## Instruction:
Add basic element pickle cycle test
## Code After:
import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| // ... existing code ...
import pytest
import pickle
from mdtraj import element
// ... modified code ...
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
// ... rest of the code ... |
85db39e36c99e800e1008605213d1c25108b035d | angr/paths.py | angr/paths.py | import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
| import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s, jumpkind=jumpkind)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
| Allow specifying jumpkind with creating a Path via PathGenerator.blank_path() | Allow specifying jumpkind with creating a Path via PathGenerator.blank_path()
| Python | bsd-2-clause | angr/angr,GuardianRG/angr,iamahuman/angr,cureHsu/angr,tyb0807/angr,mingderwang/angr,fjferrer/angr,angr/angr,zhuyue1314/angr,axt/angr,cureHsu/angr,chubbymaggie/angr,schieb/angr,lowks/angr,fjferrer/angr,zhuyue1314/angr,schieb/angr,chubbymaggie/angr,GuardianRG/angr,axt/angr,mingderwang/angr,avain/angr,schieb/angr,angr/angr,lowks/angr,haylesr/angr,iamahuman/angr,axt/angr,iamahuman/angr,f-prettyland/angr,xurantju/angr,chubbymaggie/angr,tyb0807/angr,xurantju/angr,avain/angr,f-prettyland/angr,haylesr/angr,terry2012/angr,tyb0807/angr,terry2012/angr,f-prettyland/angr | import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
- def blank_path(self, state=None, *args, **kwargs):
+ def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
- return Path(self._project, s)
+ return Path(self._project, s, jumpkind=jumpkind)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
| Allow specifying jumpkind with creating a Path via PathGenerator.blank_path() | ## Code Before:
import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
## Instruction:
Allow specifying jumpkind with creating a Path via PathGenerator.blank_path()
## Code After:
import logging
l = logging.getLogger('angr.states')
class PathGenerator(object):
def __init__(self, project):
self._project = project
def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s, jumpkind=jumpkind)
def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
| # ... existing code ...
def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
'''
# ... modified code ...
s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s, jumpkind=jumpkind)
# ... rest of the code ... |
1a98b29293ccfab6534a48402414e89726d8e5bb | Python/pomodoro.py | Python/pomodoro.py |
import datetime
import subprocess as spr
import time
def main():
start = datetime.datetime.now()
spr.call(['notify-send', 'Started new pomodoro'])
time.sleep(30 * 60)
end = datetime.datetime.now()
duration = (end - start).total_seconds() // 60
for i in range(5):
time.sleep(3)
spr.call(
['notify-send',
'POMO: {0:.0f} minute passed.\tFrom {1}'.format(
duration,
start.strftime("%H:%M:%S"))
]
)
if __name__ == "__main__":
main()
|
import datetime
import subprocess as spr
import time
def main():
start = datetime.datetime.now()
start_str = start.strftime("%H:%M:%S")
spr.call(['notify-send',
'--app-name', 'POMODORO',
'--icon', 'dialog-information',
'New pomodoro', 'From: {}'.format(start_str)])
time.sleep(30 * 60)
end = datetime.datetime.now()
duration = (end - start).total_seconds() // 60
for i in range(5):
time.sleep(3)
spr.call(
['notify-send',
'POMO: {0:.0f} minute passed.\tFrom {1}'.format(
duration,
start_str
)
]
)
if __name__ == "__main__":
main()
| Set icon, summary for notification | Set icon, summary for notification
| Python | bsd-2-clause | familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG |
import datetime
import subprocess as spr
import time
def main():
start = datetime.datetime.now()
- spr.call(['notify-send', 'Started new pomodoro'])
+ start_str = start.strftime("%H:%M:%S")
+ spr.call(['notify-send',
+ '--app-name', 'POMODORO',
+ '--icon', 'dialog-information',
+ 'New pomodoro', 'From: {}'.format(start_str)])
time.sleep(30 * 60)
end = datetime.datetime.now()
duration = (end - start).total_seconds() // 60
for i in range(5):
time.sleep(3)
spr.call(
['notify-send',
'POMO: {0:.0f} minute passed.\tFrom {1}'.format(
duration,
- start.strftime("%H:%M:%S"))
+ start_str
+ )
]
)
if __name__ == "__main__":
main()
| Set icon, summary for notification | ## Code Before:
import datetime
import subprocess as spr
import time
def main():
start = datetime.datetime.now()
spr.call(['notify-send', 'Started new pomodoro'])
time.sleep(30 * 60)
end = datetime.datetime.now()
duration = (end - start).total_seconds() // 60
for i in range(5):
time.sleep(3)
spr.call(
['notify-send',
'POMO: {0:.0f} minute passed.\tFrom {1}'.format(
duration,
start.strftime("%H:%M:%S"))
]
)
if __name__ == "__main__":
main()
## Instruction:
Set icon, summary for notification
## Code After:
import datetime
import subprocess as spr
import time
def main():
start = datetime.datetime.now()
start_str = start.strftime("%H:%M:%S")
spr.call(['notify-send',
'--app-name', 'POMODORO',
'--icon', 'dialog-information',
'New pomodoro', 'From: {}'.format(start_str)])
time.sleep(30 * 60)
end = datetime.datetime.now()
duration = (end - start).total_seconds() // 60
for i in range(5):
time.sleep(3)
spr.call(
['notify-send',
'POMO: {0:.0f} minute passed.\tFrom {1}'.format(
duration,
start_str
)
]
)
if __name__ == "__main__":
main()
| ...
start = datetime.datetime.now()
start_str = start.strftime("%H:%M:%S")
spr.call(['notify-send',
'--app-name', 'POMODORO',
'--icon', 'dialog-information',
'New pomodoro', 'From: {}'.format(start_str)])
time.sleep(30 * 60)
...
duration,
start_str
)
]
... |
bfaf9d326fc0a2fc72a6f7b6ed92640c3fe9b87b | hirlite/__init__.py | hirlite/__init__.py | from .hirlite import Rlite, HirliteError
from .version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
| import functools
from hirlite.hirlite import Rlite as RliteExtension, HirliteError
from hirlite.version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
class Rlite(RliteExtension):
def __getattr__(self, command):
return functools.partial(self.command, command)
| Add support for calling commands by attr access | Add support for calling commands by attr access
| Python | bsd-2-clause | seppo0010/rlite-py,seppo0010/rlite-py,pombredanne/rlite-py,pombredanne/rlite-py | + import functools
+
- from .hirlite import Rlite, HirliteError
+ from hirlite.hirlite import Rlite as RliteExtension, HirliteError
- from .version import __version__
+ from hirlite.version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
+
+ class Rlite(RliteExtension):
+ def __getattr__(self, command):
+ return functools.partial(self.command, command)
+ | Add support for calling commands by attr access | ## Code Before:
from .hirlite import Rlite, HirliteError
from .version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
## Instruction:
Add support for calling commands by attr access
## Code After:
import functools
from hirlite.hirlite import Rlite as RliteExtension, HirliteError
from hirlite.version import __version__
__all__ = ["Rlite", "HirliteError", "__version__"]
class Rlite(RliteExtension):
def __getattr__(self, command):
return functools.partial(self.command, command)
| ...
import functools
from hirlite.hirlite import Rlite as RliteExtension, HirliteError
from hirlite.version import __version__
...
__all__ = ["Rlite", "HirliteError", "__version__"]
class Rlite(RliteExtension):
def __getattr__(self, command):
return functools.partial(self.command, command)
... |
5edddcc85b0e21bb576b71db63d082c8ace5cf70 | examples/boilerplates/samples/google_test.py | examples/boilerplates/samples/google_test.py | '''
Google.com testing example
'''
from seleniumbase import BaseCase
from google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open('http://www.google.com')
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.update_text(HomePage.search_box, "github\n")
self.assert_text("github.com", ResultsPage.search_results)
self.assert_element(ResultsPage.google_logo)
self.click_link_text("Images")
self.assert_element('img[alt="Image result for github"]')
| '''
Google.com testing example
'''
from seleniumbase import BaseCase
from google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open('http://www.google.com')
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.update_text(HomePage.search_box, "github\n")
self.assert_text("github.com", ResultsPage.search_results)
self.click_link_text("Images")
self.assert_element('img[alt="Image result for github"]')
| Update Google boilerplate test. (Logo frequently changes) | Update Google boilerplate test. (Logo frequently changes)
| Python | mit | seleniumbase/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase | '''
Google.com testing example
'''
from seleniumbase import BaseCase
from google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open('http://www.google.com')
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.update_text(HomePage.search_box, "github\n")
self.assert_text("github.com", ResultsPage.search_results)
- self.assert_element(ResultsPage.google_logo)
self.click_link_text("Images")
self.assert_element('img[alt="Image result for github"]')
| Update Google boilerplate test. (Logo frequently changes) | ## Code Before:
'''
Google.com testing example
'''
from seleniumbase import BaseCase
from google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open('http://www.google.com')
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.update_text(HomePage.search_box, "github\n")
self.assert_text("github.com", ResultsPage.search_results)
self.assert_element(ResultsPage.google_logo)
self.click_link_text("Images")
self.assert_element('img[alt="Image result for github"]')
## Instruction:
Update Google boilerplate test. (Logo frequently changes)
## Code After:
'''
Google.com testing example
'''
from seleniumbase import BaseCase
from google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open('http://www.google.com')
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.update_text(HomePage.search_box, "github\n")
self.assert_text("github.com", ResultsPage.search_results)
self.click_link_text("Images")
self.assert_element('img[alt="Image result for github"]')
| # ... existing code ...
self.assert_text("github.com", ResultsPage.search_results)
self.click_link_text("Images")
# ... rest of the code ... |
751f40ef23250cf9fad1374359393588edee477a | back/blog/models/base.py | back/blog/models/base.py | from sqlalchemy.ext.declarative import declared_attr
from blog.lib.database import db
class ModelMixin(object):
"""A base mixin for all models."""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def __str__(self):
return '<{} (id={})>'.format(self.__class__.__name__, self.id_)
def __repr__(self):
return str(self)
id_ = db.Column('id', db.Integer, primary_key=True)
def get_dictionary(self):
d = {}
for column in self.__table__.columns:
key = 'id_' if column.key == 'id' else column.key
d[key] = getattr(self, key)
return d
def update(self, d):
for column in self.__table__.columns:
if column.key == 'id_':
continue
setattr(
self, column.key, d.get(
column.key, getattr(self, column.key)
)
)
| from sqlalchemy.ext.declarative import declared_attr
from blog.lib.database import db
class ModelMixin(object):
"""A base mixin for all models."""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def __str__(self):
return '<{} (id={})>'.format(self.__class__.__name__, self.id_)
def __repr__(self):
return str(self)
id_ = db.Column('id', db.Integer, primary_key=True)
def get_dictionary(self):
d = {}
for column in self.__table__.columns:
if column.key == 'id':
d['id'] = getattr(self, 'id_')
else:
d[column.key] = getattr(self, column.key)
return d
def update(self, d):
for column in self.__table__.columns:
if column.key == 'id_':
continue
setattr(
self, column.key, d.get(
column.key, getattr(self, column.key)
)
)
| Return "id" key to front instead of "id_". | Return "id" key to front instead of "id_".
| Python | mit | astex/living-with-django,astex/living-with-django,astex/living-with-django | from sqlalchemy.ext.declarative import declared_attr
from blog.lib.database import db
class ModelMixin(object):
"""A base mixin for all models."""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def __str__(self):
return '<{} (id={})>'.format(self.__class__.__name__, self.id_)
def __repr__(self):
return str(self)
id_ = db.Column('id', db.Integer, primary_key=True)
def get_dictionary(self):
d = {}
for column in self.__table__.columns:
- key = 'id_' if column.key == 'id' else column.key
+ if column.key == 'id':
+ d['id'] = getattr(self, 'id_')
+ else:
- d[key] = getattr(self, key)
+ d[column.key] = getattr(self, column.key)
return d
def update(self, d):
for column in self.__table__.columns:
if column.key == 'id_':
continue
setattr(
self, column.key, d.get(
column.key, getattr(self, column.key)
)
)
| Return "id" key to front instead of "id_". | ## Code Before:
from sqlalchemy.ext.declarative import declared_attr
from blog.lib.database import db
class ModelMixin(object):
"""A base mixin for all models."""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def __str__(self):
return '<{} (id={})>'.format(self.__class__.__name__, self.id_)
def __repr__(self):
return str(self)
id_ = db.Column('id', db.Integer, primary_key=True)
def get_dictionary(self):
d = {}
for column in self.__table__.columns:
key = 'id_' if column.key == 'id' else column.key
d[key] = getattr(self, key)
return d
def update(self, d):
for column in self.__table__.columns:
if column.key == 'id_':
continue
setattr(
self, column.key, d.get(
column.key, getattr(self, column.key)
)
)
## Instruction:
Return "id" key to front instead of "id_".
## Code After:
from sqlalchemy.ext.declarative import declared_attr
from blog.lib.database import db
class ModelMixin(object):
"""A base mixin for all models."""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def __str__(self):
return '<{} (id={})>'.format(self.__class__.__name__, self.id_)
def __repr__(self):
return str(self)
id_ = db.Column('id', db.Integer, primary_key=True)
def get_dictionary(self):
d = {}
for column in self.__table__.columns:
if column.key == 'id':
d['id'] = getattr(self, 'id_')
else:
d[column.key] = getattr(self, column.key)
return d
def update(self, d):
for column in self.__table__.columns:
if column.key == 'id_':
continue
setattr(
self, column.key, d.get(
column.key, getattr(self, column.key)
)
)
| ...
for column in self.__table__.columns:
if column.key == 'id':
d['id'] = getattr(self, 'id_')
else:
d[column.key] = getattr(self, column.key)
return d
... |
858c61a5d23685b62e590d28c896002291817bb1 | pygotham/admin/schedule.py | pygotham/admin/schedule.py | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
| """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
| Change admin columns for slots | Change admin columns for slots
| Python | bsd-3-clause | pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
+ column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
| Change admin columns for slots | ## Code Before:
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
## Instruction:
Change admin columns for slots
## Code After:
"""Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
| # ... existing code ...
CATEGORY,
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
# ... rest of the code ... |
bc7b1fc053150728095ec5d0a41611aa4d4ede45 | kerrokantasi/settings/__init__.py | kerrokantasi/settings/__init__.py | from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
| from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
| Remove JWT_AUTH check from settings | Remove JWT_AUTH check from settings
JWT settings has been removed in OpenID change and currently there isn't use for this.
| Python | mit | City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi | from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
-
- if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
- raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
| Remove JWT_AUTH check from settings | ## Code Before:
from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
## Instruction:
Remove JWT_AUTH check from settings
## Code After:
from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
| // ... existing code ...
load_secret_key(settings)
// ... rest of the code ... |
303bd2c3cd605581bd46410b3680f2ec5d193429 | peripydic/util/functions.py | peripydic/util/functions.py | import numpy as np
from ..util import linalgebra
def w(problem,X,type):
if type == "ONE":
return 1.
if type == "EXP":
len = linalgebra.norm(X)
return np.exp(- (len*len) / problem.neighbors.horizon)
return 1. | import numpy as np
from ..util import linalgebra
def w(problem,X,type):
if type == "ONE":
return 1.
if type == "EXP":
len = linalgebra.norm(X)
return np.exp(- (len*len) / problem.neighbors.horizon / problem.neighbors.horizon)
if type == "NORM":
return 1. / linalgebra.norm(X)
return 1. | Add NORM as influence function | Add NORM as influence function
| Python | mit | ilyasst/peridynamics_1D,lm2-poly/peridynamics_1D,lm2-poly/peridynamics_1D | import numpy as np
from ..util import linalgebra
def w(problem,X,type):
if type == "ONE":
return 1.
if type == "EXP":
len = linalgebra.norm(X)
- return np.exp(- (len*len) / problem.neighbors.horizon)
+ return np.exp(- (len*len) / problem.neighbors.horizon / problem.neighbors.horizon)
+ if type == "NORM":
+ return 1. / linalgebra.norm(X)
return 1. | Add NORM as influence function | ## Code Before:
import numpy as np
from ..util import linalgebra
def w(problem,X,type):
if type == "ONE":
return 1.
if type == "EXP":
len = linalgebra.norm(X)
return np.exp(- (len*len) / problem.neighbors.horizon)
return 1.
## Instruction:
Add NORM as influence function
## Code After:
import numpy as np
from ..util import linalgebra
def w(problem,X,type):
if type == "ONE":
return 1.
if type == "EXP":
len = linalgebra.norm(X)
return np.exp(- (len*len) / problem.neighbors.horizon / problem.neighbors.horizon)
if type == "NORM":
return 1. / linalgebra.norm(X)
return 1. | ...
len = linalgebra.norm(X)
return np.exp(- (len*len) / problem.neighbors.horizon / problem.neighbors.horizon)
if type == "NORM":
return 1. / linalgebra.norm(X)
... |
70f167d3d5a7540fb3521b82ec70bf7c6db09a99 | tests/test_contrib.py | tests/test_contrib.py | from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
| from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus) | Add test for recursive agg | Add test for recursive agg
| Python | bsd-3-clause | mirnylab/cooler | from __future__ import print_function
import cooler.contrib.higlass as cch
+ import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
+
+ def test_recursive_agg():
+ infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
+ outfile = '/tmp/bla.cool'
+ chunksize = int(10e6)
+ n_zooms = 2
+ n_cpus = 8
+ ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
+ ra.balance(outfile, n_zooms, chunksize, n_cpus) | Add test for recursive agg | ## Code Before:
from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
## Instruction:
Add test for recursive agg
## Code After:
from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus) | ...
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
...
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus)
... |
8cf555f2c8424cc8460228bac07940a19cf1a6a5 | zinnia_akismet/__init__.py | zinnia_akismet/__init__.py | """Spam checker backends for Zinnia based on Akismet"""
| """Spam checker backends for Zinnia based on Akismet"""
__version__ = '1.0.dev'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = '[email protected]'
__url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet'
| Move package metadatas at the code level | Move package metadatas at the code level
| Python | bsd-3-clause | django-blog-zinnia/zinnia-spam-checker-akismet | """Spam checker backends for Zinnia based on Akismet"""
+ __version__ = '1.0.dev'
+ __license__ = 'BSD License'
+ __author__ = 'Fantomas42'
+ __email__ = '[email protected]'
+
+ __url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet'
+ | Move package metadatas at the code level | ## Code Before:
"""Spam checker backends for Zinnia based on Akismet"""
## Instruction:
Move package metadatas at the code level
## Code After:
"""Spam checker backends for Zinnia based on Akismet"""
__version__ = '1.0.dev'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = '[email protected]'
__url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet'
| # ... existing code ...
"""Spam checker backends for Zinnia based on Akismet"""
__version__ = '1.0.dev'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = '[email protected]'
__url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet'
# ... rest of the code ... |
648189583d78efef9ec8f65e861e1321c397c1a6 | app/views/main_view.py | app/views/main_view.py | from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
| from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
PostModel.set_query()
PostModel.query.order = ['-updated', 'title']
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
| Set index main view to return post ordered by updated and title field | Set index main view to return post ordered by updated and title field
| Python | mit | oldani/nanodegree-blog,oldani/nanodegree-blog,oldani/nanodegree-blog | from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
+ PostModel.set_query()
+ PostModel.query.order = ['-updated', 'title']
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
| Set index main view to return post ordered by updated and title field | ## Code Before:
from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
## Instruction:
Set index main view to return post ordered by updated and title field
## Code After:
from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
PostModel.set_query()
PostModel.query.order = ['-updated', 'title']
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
| # ... existing code ...
def index(self):
PostModel.set_query()
PostModel.query.order = ['-updated', 'title']
posts = PostModel.fetch()
# ... rest of the code ... |
afb58da6ecc11a1c92d230bc2dcbb06464cc4f32 | percept/workflows/commands/run_flow.py | percept/workflows/commands/run_flow.py |
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
import logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
args = 'config_file'
def command(self, *args, **options):
config_file = args[0]
wrapper = WorkflowWrapper(config_file, NaiveWorkflow)
wrapper.run()
|
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
from optparse import make_option
import IPython
import logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
args = 'config_file'
option_list = BaseCommand.option_list + (make_option('--shell',
help='Whether or not to load a shell afterwards".'),)
def command(self, *args, **options):
config_file = args[0]
wrapper = WorkflowWrapper(config_file, NaiveWorkflow)
wrapper.run()
if '--shell' in options:
ns = {
'flow' : wrapper.workflow,
'tasks' : wrapper.workflow.tasks
}
IPython.embed(user_ns=ns)
| Add in a way to start a shell using the results of a workflow | Add in a way to start a shell using the results of a workflow
| Python | apache-2.0 | VikParuchuri/percept,VikParuchuri/percept |
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
+ from optparse import make_option
+ import IPython
import logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
args = 'config_file'
+ option_list = BaseCommand.option_list + (make_option('--shell',
+ help='Whether or not to load a shell afterwards".'),)
+
def command(self, *args, **options):
config_file = args[0]
wrapper = WorkflowWrapper(config_file, NaiveWorkflow)
wrapper.run()
+ if '--shell' in options:
+ ns = {
+ 'flow' : wrapper.workflow,
+ 'tasks' : wrapper.workflow.tasks
+ }
+ IPython.embed(user_ns=ns)
+
+ | Add in a way to start a shell using the results of a workflow | ## Code Before:
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
import logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
args = 'config_file'
def command(self, *args, **options):
config_file = args[0]
wrapper = WorkflowWrapper(config_file, NaiveWorkflow)
wrapper.run()
## Instruction:
Add in a way to start a shell using the results of a workflow
## Code After:
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
from optparse import make_option
import IPython
import logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
args = 'config_file'
option_list = BaseCommand.option_list + (make_option('--shell',
help='Whether or not to load a shell afterwards".'),)
def command(self, *args, **options):
config_file = args[0]
wrapper = WorkflowWrapper(config_file, NaiveWorkflow)
wrapper.run()
if '--shell' in options:
ns = {
'flow' : wrapper.workflow,
'tasks' : wrapper.workflow.tasks
}
IPython.embed(user_ns=ns)
| // ... existing code ...
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
from optparse import make_option
import IPython
// ... modified code ...
option_list = BaseCommand.option_list + (make_option('--shell',
help='Whether or not to load a shell afterwards".'),)
def command(self, *args, **options):
...
if '--shell' in options:
ns = {
'flow' : wrapper.workflow,
'tasks' : wrapper.workflow.tasks
}
IPython.embed(user_ns=ns)
// ... rest of the code ... |
c977e1c235ccb040f28bc03c63d2667924d5edd3 | pythonforandroid/recipes/xeddsa/__init__.py | pythonforandroid/recipes/xeddsa/__init__.py | from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
# the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
# or simply `_crypto_sign.so` depending on the platform/distribution
sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| Fix xeddsa crypto_sign shared lib copy | Fix xeddsa crypto_sign shared lib copy
Could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so` or simply `_crypto_sign.so` depending on the platform/distribution | Python | mit | germn/python-for-android,rnixx/python-for-android,rnixx/python-for-android,germn/python-for-android,rnixx/python-for-android,kivy/python-for-android,PKRoma/python-for-android,germn/python-for-android,germn/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,germn/python-for-android,kronenpj/python-for-android,kivy/python-for-android,PKRoma/python-for-android,kivy/python-for-android,rnixx/python-for-android,kronenpj/python-for-android,germn/python-for-android,rnixx/python-for-android,PKRoma/python-for-android,rnixx/python-for-android,PKRoma/python-for-android | from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
+ # the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
+ # or simply `_crypto_sign.so` depending on the platform/distribution
- shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
+ sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| Fix xeddsa crypto_sign shared lib copy | ## Code Before:
from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
## Instruction:
Fix xeddsa crypto_sign shared lib copy
## Code After:
from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
# the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
# or simply `_crypto_sign.so` depending on the platform/distribution
sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| # ... existing code ...
)
# the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
# or simply `_crypto_sign.so` depending on the platform/distribution
sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
# ... rest of the code ... |
f90cd0883a9a9301f359c7a238aba223756c6765 | klustakwik2/numerics/cylib/compute_cluster_masks.py | klustakwik2/numerics/cylib/compute_cluster_masks.py | from .compute_cluster_masks_cy import doaccum
__all__ = ['accumulate_cluster_mask_sum']
def accumulate_cluster_mask_sum(kk, cluster_mask_sum):
data = kk.data
doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end,
data.masks, data.values_start, data.values_end, cluster_mask_sum,
kk.num_special_clusters)
| from .compute_cluster_masks_cy import doaccum
__all__ = ['accumulate_cluster_mask_sum']
def accumulate_cluster_mask_sum(kk, cluster_mask_sum):
data = kk.data
doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end,
data.masks, data.values_start, data.values_end, cluster_mask_sum,
kk.clusters.dtype.type(kk.num_special_clusters))
| Fix for some version of py64 on win64 | Fix for some version of py64 on win64
| Python | bsd-3-clause | benvermaercke/klustakwik2,kwikteam/klustakwik2 | from .compute_cluster_masks_cy import doaccum
__all__ = ['accumulate_cluster_mask_sum']
def accumulate_cluster_mask_sum(kk, cluster_mask_sum):
data = kk.data
doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end,
data.masks, data.values_start, data.values_end, cluster_mask_sum,
- kk.num_special_clusters)
+ kk.clusters.dtype.type(kk.num_special_clusters))
| Fix for some version of py64 on win64 | ## Code Before:
from .compute_cluster_masks_cy import doaccum
__all__ = ['accumulate_cluster_mask_sum']
def accumulate_cluster_mask_sum(kk, cluster_mask_sum):
data = kk.data
doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end,
data.masks, data.values_start, data.values_end, cluster_mask_sum,
kk.num_special_clusters)
## Instruction:
Fix for some version of py64 on win64
## Code After:
from .compute_cluster_masks_cy import doaccum
__all__ = ['accumulate_cluster_mask_sum']
def accumulate_cluster_mask_sum(kk, cluster_mask_sum):
data = kk.data
doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end,
data.masks, data.values_start, data.values_end, cluster_mask_sum,
kk.clusters.dtype.type(kk.num_special_clusters))
| ...
data.masks, data.values_start, data.values_end, cluster_mask_sum,
kk.clusters.dtype.type(kk.num_special_clusters))
... |
f0ef4f5e269d7f2d7fd347e8f458c1c9ce1ffb34 | mqueue/hooks/redis/__init__.py | mqueue/hooks/redis/__init__.py | import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
name = DOMAIN+"_event"+str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data) | import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
global event_num
global R
name = DOMAIN + "_event" + str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
event_num += 1
| Fix bug in redis hook | Fix bug in redis hook
| Python | mit | synw/django-mqueue,synw/django-mqueue,synw/django-mqueue | import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
- event_num = int(time.time())
+ event_num = int(time.time())
+
def save(event, conf):
+ global event_num
+ global R
- name = DOMAIN+"_event"+str(event_num)
+ name = DOMAIN + "_event" + str(event_num)
event.request = event.request.replace("\n", "//")
- data = serializer.Pack(event)
+ data = serializer.Pack(event)
R.set(name, data)
+ event_num += 1
+ | Fix bug in redis hook | ## Code Before:
import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
name = DOMAIN+"_event"+str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
## Instruction:
Fix bug in redis hook
## Code After:
import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
global event_num
global R
name = DOMAIN + "_event" + str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
event_num += 1
| ...
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
...
def save(event, conf):
global event_num
global R
name = DOMAIN + "_event" + str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
event_num += 1
... |
90dfa38014ba91de2e8c0c75d63788aab3c95f38 | Python/python2_version/klampt/__init__.py | Python/python2_version/klampt/__init__.py | from robotsim import *
import atexit
atexit.register(destroy)
__all__ = ['WorldModel','RobotModel','RobotModelLink','RigidObjectModel','TerrainModel','Mass','ContactParameters',
'SimRobotController','SimRobotSensor','SimBody','Simulator',
'Geometry3D','Appearance','DistanceQuerySettings','DistanceQueryResult','TriangleMesh','PointCloud','GeometricPrimitive','VolumeGrid',
'IKObjective','IKSolver','GeneralizedIKObjective','GeneralizedIKSolver',
'model','math','io','plan','sim']
| from __future__ import print_function,division
from robotsim import *
import atexit
atexit.register(destroy)
__all__ = ['WorldModel','RobotModel','RobotModelLink','RigidObjectModel','TerrainModel','Mass','ContactParameters',
'SimRobotController','SimRobotSensor','SimBody','Simulator',
'Geometry3D','Appearance','DistanceQuerySettings','DistanceQueryResult','TriangleMesh','PointCloud','GeometricPrimitive','VolumeGrid',
'IKObjective','IKSolver','GeneralizedIKObjective','GeneralizedIKSolver',
'model','math','io','plan','sim']
| Allow some compatibility between python2 and updated python 3 files | Allow some compatibility between python2 and updated python 3 files
| Python | bsd-3-clause | krishauser/Klampt,krishauser/Klampt,krishauser/Klampt,krishauser/Klampt,krishauser/Klampt,krishauser/Klampt | + from __future__ import print_function,division
from robotsim import *
import atexit
atexit.register(destroy)
__all__ = ['WorldModel','RobotModel','RobotModelLink','RigidObjectModel','TerrainModel','Mass','ContactParameters',
'SimRobotController','SimRobotSensor','SimBody','Simulator',
'Geometry3D','Appearance','DistanceQuerySettings','DistanceQueryResult','TriangleMesh','PointCloud','GeometricPrimitive','VolumeGrid',
'IKObjective','IKSolver','GeneralizedIKObjective','GeneralizedIKSolver',
'model','math','io','plan','sim']
| Allow some compatibility between python2 and updated python 3 files | ## Code Before:
from robotsim import *
import atexit
atexit.register(destroy)
__all__ = ['WorldModel','RobotModel','RobotModelLink','RigidObjectModel','TerrainModel','Mass','ContactParameters',
'SimRobotController','SimRobotSensor','SimBody','Simulator',
'Geometry3D','Appearance','DistanceQuerySettings','DistanceQueryResult','TriangleMesh','PointCloud','GeometricPrimitive','VolumeGrid',
'IKObjective','IKSolver','GeneralizedIKObjective','GeneralizedIKSolver',
'model','math','io','plan','sim']
## Instruction:
Allow some compatibility between python2 and updated python 3 files
## Code After:
from __future__ import print_function,division
from robotsim import *
import atexit
atexit.register(destroy)
__all__ = ['WorldModel','RobotModel','RobotModelLink','RigidObjectModel','TerrainModel','Mass','ContactParameters',
'SimRobotController','SimRobotSensor','SimBody','Simulator',
'Geometry3D','Appearance','DistanceQuerySettings','DistanceQueryResult','TriangleMesh','PointCloud','GeometricPrimitive','VolumeGrid',
'IKObjective','IKSolver','GeneralizedIKObjective','GeneralizedIKSolver',
'model','math','io','plan','sim']
| # ... existing code ...
from __future__ import print_function,division
from robotsim import *
# ... rest of the code ... |
49a1548399fa822515920d910ec6ea6a6c813bca | threadpool.py | threadpool.py | from __future__ import with_statement
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
@threado.stream
def run(inner, self, func, *args, **keys):
with self.lock:
if self.threads:
thread, queue = self.threads.pop()
else:
queue = Queue.Queue()
thread = threading.Thread(target=self._thread, args=(queue,))
thread.setDaemon(True)
channel = threado.Channel()
queue.put((channel, func, args, keys))
if not thread.isAlive():
thread.start()
result = yield channel
inner.finish(result)
def _thread(self, queue):
item = threading.currentThread(), queue
while True:
try:
task = queue.get(True, self.idle_time)
except Queue.Empty:
with self.lock:
if item not in self.threads:
continue
self.threads.remove(item)
return
if task is None:
return
channel, func, args, keys = task
try:
result = func(*args, **keys)
except:
self.threads.append(item)
channel.rethrow()
else:
self.threads.append(item)
channel.finish(result)
thread_pool = ThreadPool()
run = thread_pool.run
| from __future__ import with_statement
import sys
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
def run(self, func, *args, **keys):
with self.lock:
if self.threads:
thread, queue = self.threads.pop()
else:
queue = Queue.Queue()
thread = threading.Thread(target=self._thread, args=(queue,))
thread.setDaemon(True)
channel = threado.Channel()
queue.put((channel, func, args, keys))
if not thread.isAlive():
thread.start()
return channel
def _thread(self, queue):
item = threading.currentThread(), queue
while True:
try:
task = queue.get(True, self.idle_time)
except Queue.Empty:
with self.lock:
if item not in self.threads:
continue
self.threads.remove(item)
return
if task is None:
return
channel, func, args, keys = task
try:
result = func(*args, **keys)
except:
self.threads.append(item)
channel.rethrow()
else:
self.threads.append(item)
channel.finish(result)
thread_pool = ThreadPool()
run = thread_pool.run
| Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None. | Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None.
| Python | mit | abusesa/idiokit | from __future__ import with_statement
+ import sys
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
- @threado.stream
- def run(inner, self, func, *args, **keys):
+ def run(self, func, *args, **keys):
with self.lock:
if self.threads:
thread, queue = self.threads.pop()
else:
queue = Queue.Queue()
thread = threading.Thread(target=self._thread, args=(queue,))
thread.setDaemon(True)
channel = threado.Channel()
queue.put((channel, func, args, keys))
if not thread.isAlive():
thread.start()
+ return channel
- result = yield channel
- inner.finish(result)
def _thread(self, queue):
item = threading.currentThread(), queue
while True:
try:
task = queue.get(True, self.idle_time)
except Queue.Empty:
with self.lock:
if item not in self.threads:
continue
self.threads.remove(item)
return
if task is None:
return
channel, func, args, keys = task
try:
result = func(*args, **keys)
except:
self.threads.append(item)
channel.rethrow()
else:
self.threads.append(item)
channel.finish(result)
thread_pool = ThreadPool()
run = thread_pool.run
| Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None. | ## Code Before:
from __future__ import with_statement
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
@threado.stream
def run(inner, self, func, *args, **keys):
with self.lock:
if self.threads:
thread, queue = self.threads.pop()
else:
queue = Queue.Queue()
thread = threading.Thread(target=self._thread, args=(queue,))
thread.setDaemon(True)
channel = threado.Channel()
queue.put((channel, func, args, keys))
if not thread.isAlive():
thread.start()
result = yield channel
inner.finish(result)
def _thread(self, queue):
item = threading.currentThread(), queue
while True:
try:
task = queue.get(True, self.idle_time)
except Queue.Empty:
with self.lock:
if item not in self.threads:
continue
self.threads.remove(item)
return
if task is None:
return
channel, func, args, keys = task
try:
result = func(*args, **keys)
except:
self.threads.append(item)
channel.rethrow()
else:
self.threads.append(item)
channel.finish(result)
thread_pool = ThreadPool()
run = thread_pool.run
## Instruction:
Fix a weird situation when a function run in a thread raises StopIteration, which was erroneusly interpreted that the thread returned None.
## Code After:
from __future__ import with_statement
import sys
import threado
import threading
import Queue
class ThreadPool(object):
def __init__(self, idle_time=5.0):
self.lock = threading.Lock()
self.threads = list()
self.idle_time = idle_time
def run(self, func, *args, **keys):
with self.lock:
if self.threads:
thread, queue = self.threads.pop()
else:
queue = Queue.Queue()
thread = threading.Thread(target=self._thread, args=(queue,))
thread.setDaemon(True)
channel = threado.Channel()
queue.put((channel, func, args, keys))
if not thread.isAlive():
thread.start()
return channel
def _thread(self, queue):
item = threading.currentThread(), queue
while True:
try:
task = queue.get(True, self.idle_time)
except Queue.Empty:
with self.lock:
if item not in self.threads:
continue
self.threads.remove(item)
return
if task is None:
return
channel, func, args, keys = task
try:
result = func(*args, **keys)
except:
self.threads.append(item)
channel.rethrow()
else:
self.threads.append(item)
channel.finish(result)
thread_pool = ThreadPool()
run = thread_pool.run
| // ... existing code ...
from __future__ import with_statement
import sys
import threado
// ... modified code ...
def run(self, func, *args, **keys):
with self.lock:
...
return channel
// ... rest of the code ... |
6af31da53a43bcd2e45ea4242892a4831b2fb2f8 | asyncio_irc/listeners.py | asyncio_irc/listeners.py | class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
# class RegexListener(Listener):
# def __init__(self, regex, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.regex = regex
| class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
| Remove commented code for the mo | Remove commented code for the mo
| Python | bsd-2-clause | meshy/framewirc | class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
-
- # class RegexListener(Listener):
- # def __init__(self, regex, *args, **kwargs):
- # super().__init__(*args, **kwargs)
- # self.regex = regex
- | Remove commented code for the mo | ## Code Before:
class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
# class RegexListener(Listener):
# def __init__(self, regex, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.regex = regex
## Instruction:
Remove commented code for the mo
## Code After:
class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
| ...
super().handle(connection, message)
... |
6cd3e11f6ec84cffc0ea71d15d2e164f499529cf | gidget/util/tumorTypeConfig.py | gidget/util/tumorTypeConfig.py |
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
|
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
| Make sure tumor-type config ignores spaces | Make sure tumor-type config ignores spaces
| Python | mit | cancerregulome/gidget,cancerregulome/gidget,cancerregulome/gidget |
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
- csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
+ csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
| Make sure tumor-type config ignores spaces | ## Code Before:
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
## Instruction:
Make sure tumor-type config ignores spaces
## Code After:
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
| // ... existing code ...
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
// ... rest of the code ... |
fd4539942dafe622d3f7a7d183db3d69f95a00c4 | shop/urls/cart.py | shop/urls/cart.py | from django.conf.urls.defaults import url, patterns
from shop.views.cart import CartDetails, CartItemDetail
urlpatterns = patterns('',
url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE
name='cart_delete'),
url('^item/$', CartDetails.as_view(action='post'), # POST
name='cart_item_add'),
url(r'^$', CartDetails.as_view(), name='cart'), # GET
url(r'^update/$', CartDetails.as_view(action='put'),
name='cart_update'),
# CartItems
url('^item/(?P<id>[0-9A-Za-z-_.//]+)$', CartItemDetail.as_view(),
name='cart_item'),
url('^item/(?P<id>[0-9A-Za-z-_.//]+)/delete$',
CartItemDetail.as_view(action='delete'),
name='cart_item_delete'),
)
| from django.conf.urls.defaults import url, patterns
from shop.views.cart import CartDetails, CartItemDetail
urlpatterns = patterns('',
url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE
name='cart_delete'),
url('^item/$', CartDetails.as_view(action='post'), # POST
name='cart_item_add'),
url(r'^$', CartDetails.as_view(), name='cart'), # GET
url(r'^update/$', CartDetails.as_view(action='put'),
name='cart_update'),
# CartItems
url('^item/(?P<id>[0-9]+)$', CartItemDetail.as_view(),
name='cart_item'),
url('^item/(?P<id>[0-9]+)/delete$',
CartItemDetail.as_view(action='delete'),
name='cart_item_delete'),
)
| Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex). | Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex). | Python | bsd-3-clause | schacki/django-shop,khchine5/django-shop,khchine5/django-shop,dwx9/test,febsn/django-shop,DavideyLee/django-shop,awesto/django-shop,jrief/django-shop,dwx9/test,thenewguy/django-shop,thenewguy/django-shop,bmihelac/django-shop,pjdelport/django-shop,creimers/django-shop,creimers/django-shop,jrief/django-shop,bmihelac/django-shop,awesto/django-shop,awesto/django-shop,febsn/django-shop,febsn/django-shop,nimbis/django-shop,khchine5/django-shop,pjdelport/django-shop,rfleschenberg/django-shop,rfleschenberg/django-shop,dwx9/test,rfleschenberg/django-shop,fusionbox/django-shop,chriscauley/django-shop,jrief/django-shop,divio/django-shop,creimers/django-shop,DavideyLee/django-shop,pjdelport/django-shop,schacki/django-shop,schacki/django-shop,nimbis/django-shop,atheiste/django-shop,nimbis/django-shop,katomaso/django-shop,fusionbox/django-shop,chriscauley/django-shop,atheiste/django-shop,chriscauley/django-shop,jrutila/django-shop,jrutila/django-shop,khchine5/django-shop,schacki/django-shop,nimbis/django-shop,jrutila/django-shop,divio/django-shop,divio/django-shop,katomaso/django-shop,katomaso/django-shop,rfleschenberg/django-shop,atheiste/django-shop,jrief/django-shop | from django.conf.urls.defaults import url, patterns
from shop.views.cart import CartDetails, CartItemDetail
urlpatterns = patterns('',
url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE
name='cart_delete'),
url('^item/$', CartDetails.as_view(action='post'), # POST
name='cart_item_add'),
url(r'^$', CartDetails.as_view(), name='cart'), # GET
url(r'^update/$', CartDetails.as_view(action='put'),
name='cart_update'),
# CartItems
- url('^item/(?P<id>[0-9A-Za-z-_.//]+)$', CartItemDetail.as_view(),
+ url('^item/(?P<id>[0-9]+)$', CartItemDetail.as_view(),
name='cart_item'),
- url('^item/(?P<id>[0-9A-Za-z-_.//]+)/delete$',
+ url('^item/(?P<id>[0-9]+)/delete$',
CartItemDetail.as_view(action='delete'),
name='cart_item_delete'),
)
| Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex). | ## Code Before:
from django.conf.urls.defaults import url, patterns
from shop.views.cart import CartDetails, CartItemDetail
urlpatterns = patterns('',
url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE
name='cart_delete'),
url('^item/$', CartDetails.as_view(action='post'), # POST
name='cart_item_add'),
url(r'^$', CartDetails.as_view(), name='cart'), # GET
url(r'^update/$', CartDetails.as_view(action='put'),
name='cart_update'),
# CartItems
url('^item/(?P<id>[0-9A-Za-z-_.//]+)$', CartItemDetail.as_view(),
name='cart_item'),
url('^item/(?P<id>[0-9A-Za-z-_.//]+)/delete$',
CartItemDetail.as_view(action='delete'),
name='cart_item_delete'),
)
## Instruction:
Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex).
## Code After:
from django.conf.urls.defaults import url, patterns
from shop.views.cart import CartDetails, CartItemDetail
urlpatterns = patterns('',
url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE
name='cart_delete'),
url('^item/$', CartDetails.as_view(action='post'), # POST
name='cart_item_add'),
url(r'^$', CartDetails.as_view(), name='cart'), # GET
url(r'^update/$', CartDetails.as_view(action='put'),
name='cart_update'),
# CartItems
url('^item/(?P<id>[0-9]+)$', CartItemDetail.as_view(),
name='cart_item'),
url('^item/(?P<id>[0-9]+)/delete$',
CartItemDetail.as_view(action='delete'),
name='cart_item_delete'),
)
| ...
# CartItems
url('^item/(?P<id>[0-9]+)$', CartItemDetail.as_view(),
name='cart_item'),
url('^item/(?P<id>[0-9]+)/delete$',
CartItemDetail.as_view(action='delete'),
... |
0af3b589c6c271d07ad4e204fa41aa0fed167a94 | thinglang/parser/constructs/cast_operation.py | thinglang/parser/constructs/cast_operation.py | from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
class CastOperation(object):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@staticmethod
def create(source: Identifier, destination: Identifier) -> MethodCall:
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
| from thinglang.lexer.operators.casts import LexicalCast
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
from thinglang.utils.type_descriptors import ValueType
class CastOperation(BaseNode):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@staticmethod
def create(source: Identifier, destination: Identifier) -> MethodCall:
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
@staticmethod
@ParserRule.mark
def parse_inline_cast_op(value: ValueType, _: LexicalCast, target_type: Identifier):
return MethodCall(Access([value, Identifier('convert_') + target_type]), [])
| Add explicit parsing rule for cast operations | Add explicit parsing rule for cast operations
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | + from thinglang.lexer.operators.casts import LexicalCast
from thinglang.lexer.values.identifier import Identifier
+ from thinglang.parser.nodes import BaseNode
+ from thinglang.parser.rule import ParserRule
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
+ from thinglang.utils.type_descriptors import ValueType
- class CastOperation(object):
+ class CastOperation(BaseNode):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@staticmethod
def create(source: Identifier, destination: Identifier) -> MethodCall:
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
+ @staticmethod
+ @ParserRule.mark
+ def parse_inline_cast_op(value: ValueType, _: LexicalCast, target_type: Identifier):
+ return MethodCall(Access([value, Identifier('convert_') + target_type]), [])
+ | Add explicit parsing rule for cast operations | ## Code Before:
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
class CastOperation(object):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@staticmethod
def create(source: Identifier, destination: Identifier) -> MethodCall:
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
## Instruction:
Add explicit parsing rule for cast operations
## Code After:
from thinglang.lexer.operators.casts import LexicalCast
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.parser.values.access import Access
from thinglang.parser.values.method_call import MethodCall
from thinglang.utils.type_descriptors import ValueType
class CastOperation(BaseNode):
"""
Explicitly cast from one type to another
Expects a conversion method on the source class
"""
@staticmethod
def create(source: Identifier, destination: Identifier) -> MethodCall:
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
@staticmethod
@ParserRule.mark
def parse_inline_cast_op(value: ValueType, _: LexicalCast, target_type: Identifier):
return MethodCall(Access([value, Identifier('convert_') + target_type]), [])
| // ... existing code ...
from thinglang.lexer.operators.casts import LexicalCast
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.parser.values.access import Access
// ... modified code ...
from thinglang.parser.values.method_call import MethodCall
from thinglang.utils.type_descriptors import ValueType
...
class CastOperation(BaseNode):
"""
...
return MethodCall(Access([source, Identifier('convert_') + destination]), MethodCall.STACK_ARGS)
@staticmethod
@ParserRule.mark
def parse_inline_cast_op(value: ValueType, _: LexicalCast, target_type: Identifier):
return MethodCall(Access([value, Identifier('convert_') + target_type]), [])
// ... rest of the code ... |
3ac6f578397235e8eda686fe3589cda780af53d5 | ginga/qtw/Plot.py | ginga/qtw/Plot.py | from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
if toolkit in ('qt', 'qt4'):
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
elif toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
| from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
if toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
else:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
| Fix for import error with matplotlib Qt4Agg backend | Fix for import error with matplotlib Qt4Agg backend
| Python | bsd-3-clause | stscieisenhamer/ginga,ejeschke/ginga,sosey/ginga,Cadair/ginga,rupak0577/ginga,eteq/ginga,rajul/ginga,ejeschke/ginga,pllim/ginga,ejeschke/ginga,sosey/ginga,naojsoft/ginga,naojsoft/ginga,Cadair/ginga,rupak0577/ginga,rajul/ginga,eteq/ginga,stscieisenhamer/ginga,rupak0577/ginga,pllim/ginga,sosey/ginga,stscieisenhamer/ginga,pllim/ginga,Cadair/ginga,rajul/ginga,naojsoft/ginga,eteq/ginga | from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
- if toolkit in ('qt', 'qt4'):
- from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
- as FigureCanvas
- elif toolkit == 'qt5':
+ if toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
+ as FigureCanvas
+ else:
+ from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
| Fix for import error with matplotlib Qt4Agg backend | ## Code Before:
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
if toolkit in ('qt', 'qt4'):
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
elif toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
## Instruction:
Fix for import error with matplotlib Qt4Agg backend
## Code After:
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
if toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
else:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
| ...
import matplotlib
if toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
...
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
else:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
... |
2e3119b5f45a65f585e34b1239764d73b41c65fd | misp_modules/modules/expansion/__init__.py | misp_modules/modules/expansion/__init__.py | from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns',
'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache',
'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| Add domaintools to the import list | Add domaintools to the import list
| Python | agpl-3.0 | Rafiot/misp-modules,MISP/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,MISP/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,MISP/misp-modules | from . import _vmray
- __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns',
+ __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl',
- 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
+ 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache',
+ 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| Add domaintools to the import list | ## Code Before:
from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns',
'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
## Instruction:
Add domaintools to the import list
## Code After:
from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache',
'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| # ... existing code ...
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache',
'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
# ... rest of the code ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.