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
1bc61edde0e41ec3f2fe66758654b55ed51ec36a
test/test_repo.py
test/test_repo.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from asv import config from asv import repo def test_repo(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "https://github.com/spacetelescope/asv.git" r = repo.get_repo(conf) r.checkout("master") r.checkout("gh-pages") r.checkout("master") hashes = r.get_hashes_from_range("ae0c27b65741..e6f382a704f7") assert len(hashes) == 4 dates = [r.get_date(hash) for hash in hashes] assert dates == sorted(dates)[::-1] tags = r.get_tags() for tag in tags: r.get_date_from_tag(tag)
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from asv import config from asv import repo def _test_generic_repo(conf, hash_range="ae0c27b65741..e6f382a704f7", master="master", branch="gh-pages"): r = repo.get_repo(conf) r.checkout(master) r.checkout(branch) r.checkout(master) hashes = r.get_hashes_from_range(hash_range) assert len(hashes) == 4 dates = [r.get_date(hash) for hash in hashes] assert dates == sorted(dates)[::-1] tags = r.get_tags() for tag in tags: r.get_date_from_tag(tag) def test_repo_git(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "https://github.com/spacetelescope/asv.git" _test_generic_repo(conf) def test_repo_hg(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "hg+https://bitbucket.org/nds-org/nds-labs" _test_generic_repo(conf, hash_range="a8ca24ac6b77:9dc758deba8", master="tip", branch="dev")
Add test for mercurial repo
Add test for mercurial repo
Python
bsd-3-clause
pv/asv,waylonflinn/asv,airspeed-velocity/asv,pv/asv,qwhelan/asv,mdboom/asv,waylonflinn/asv,waylonflinn/asv,ericdill/asv,giltis/asv,ericdill/asv,airspeed-velocity/asv,mdboom/asv,qwhelan/asv,giltis/asv,airspeed-velocity/asv,qwhelan/asv,edisongustavo/asv,mdboom/asv,spacetelescope/asv,edisongustavo/asv,ericdill/asv,pv/asv,ericdill/asv,giltis/asv,spacetelescope/asv,spacetelescope/asv,mdboom/asv,qwhelan/asv,pv/asv,edisongustavo/asv,spacetelescope/asv,airspeed-velocity/asv
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from asv import config from asv import repo + def _test_generic_repo(conf, + hash_range="ae0c27b65741..e6f382a704f7", + master="master", + branch="gh-pages"): - def test_repo(tmpdir): - conf = config.Config() - - conf.project = six.text_type(tmpdir.join("repo")) - conf.repo = "https://github.com/spacetelescope/asv.git" r = repo.get_repo(conf) - r.checkout("master") + r.checkout(master) - r.checkout("gh-pages") + r.checkout(branch) - r.checkout("master") + r.checkout(master) - hashes = r.get_hashes_from_range("ae0c27b65741..e6f382a704f7") + hashes = r.get_hashes_from_range(hash_range) assert len(hashes) == 4 dates = [r.get_date(hash) for hash in hashes] assert dates == sorted(dates)[::-1] tags = r.get_tags() for tag in tags: r.get_date_from_tag(tag) + + def test_repo_git(tmpdir): + conf = config.Config() + + conf.project = six.text_type(tmpdir.join("repo")) + conf.repo = "https://github.com/spacetelescope/asv.git" + _test_generic_repo(conf) + + + def test_repo_hg(tmpdir): + conf = config.Config() + + conf.project = six.text_type(tmpdir.join("repo")) + conf.repo = "hg+https://bitbucket.org/nds-org/nds-labs" + _test_generic_repo(conf, hash_range="a8ca24ac6b77:9dc758deba8", + master="tip", branch="dev") +
Add test for mercurial repo
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) import six from asv import config from asv import repo def test_repo(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "https://github.com/spacetelescope/asv.git" r = repo.get_repo(conf) r.checkout("master") r.checkout("gh-pages") r.checkout("master") hashes = r.get_hashes_from_range("ae0c27b65741..e6f382a704f7") assert len(hashes) == 4 dates = [r.get_date(hash) for hash in hashes] assert dates == sorted(dates)[::-1] tags = r.get_tags() for tag in tags: r.get_date_from_tag(tag) ## Instruction: Add test for mercurial repo ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) import six from asv import config from asv import repo def _test_generic_repo(conf, hash_range="ae0c27b65741..e6f382a704f7", master="master", branch="gh-pages"): r = repo.get_repo(conf) r.checkout(master) r.checkout(branch) r.checkout(master) hashes = r.get_hashes_from_range(hash_range) assert len(hashes) == 4 dates = [r.get_date(hash) for hash in hashes] assert dates == sorted(dates)[::-1] tags = r.get_tags() for tag in tags: r.get_date_from_tag(tag) def test_repo_git(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "https://github.com/spacetelescope/asv.git" _test_generic_repo(conf) def test_repo_hg(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "hg+https://bitbucket.org/nds-org/nds-labs" _test_generic_repo(conf, hash_range="a8ca24ac6b77:9dc758deba8", master="tip", branch="dev")
# ... existing code ... def _test_generic_repo(conf, hash_range="ae0c27b65741..e6f382a704f7", master="master", branch="gh-pages"): # ... modified code ... r = repo.get_repo(conf) r.checkout(master) r.checkout(branch) r.checkout(master) hashes = r.get_hashes_from_range(hash_range) assert len(hashes) == 4 ... r.get_date_from_tag(tag) def test_repo_git(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "https://github.com/spacetelescope/asv.git" _test_generic_repo(conf) def test_repo_hg(tmpdir): conf = config.Config() conf.project = six.text_type(tmpdir.join("repo")) conf.repo = "hg+https://bitbucket.org/nds-org/nds-labs" _test_generic_repo(conf, hash_range="a8ca24ac6b77:9dc758deba8", master="tip", branch="dev") # ... rest of the code ...
5d2a4ac0e48d404a16b81d2f290be5ec13bdf8f1
logintokens/forms.py
logintokens/forms.py
from django import forms from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = forms.EmailField(label="Email", max_length=254) def generate_login_link(self, email, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(email) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ email = self.cleaned_data['email'] body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(email, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = UsernameField( max_length=254, widget=forms.TextInput(attrs={'autofocus': True}), ) def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ username = self.cleaned_data['email'] try: user = USER._default_manager.get_by_natural_key(username) email = getattr(user, USER.EMAIL_FIELD) except USER.DoesNotExist: email = username body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(username, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
Update form to pass new test
Update form to pass new test
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
from django import forms from django.contrib.auth import get_user_model + from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): - email = forms.EmailField(label="Email", max_length=254) + email = UsernameField( + max_length=254, + widget=forms.TextInput(attrs={'autofocus': True}), + ) - def generate_login_link(self, email, request): + def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') - token = default_token_generator.make_token(email) + token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ - email = self.cleaned_data['email'] + username = self.cleaned_data['email'] + try: + user = USER._default_manager.get_by_natural_key(username) + email = getattr(user, USER.EMAIL_FIELD) + except USER.DoesNotExist: + email = username body = 'To complete the login process, simply click on this link: {}' - login_link = self.generate_login_link(email, request) + login_link = self.generate_login_link(username, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
Update form to pass new test
## Code Before: from django import forms from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = forms.EmailField(label="Email", max_length=254) def generate_login_link(self, email, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(email) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ email = self.cleaned_data['email'] body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(email, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send() ## Instruction: Update form to pass new test ## Code After: from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = UsernameField( max_length=254, widget=forms.TextInput(attrs={'autofocus': True}), ) def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ username = self.cleaned_data['email'] try: user = USER._default_manager.get_by_natural_key(username) email = getattr(user, USER.EMAIL_FIELD) except USER.DoesNotExist: email = username body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(username, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
# ... existing code ... from django.contrib.auth import get_user_model from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives # ... modified code ... class TokenLoginForm(forms.Form): email = UsernameField( max_length=254, widget=forms.TextInput(attrs={'autofocus': True}), ) def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' ... url = reverse_lazy('token_login') token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) ... """ username = self.cleaned_data['email'] try: user = USER._default_manager.get_by_natural_key(username) email = getattr(user, USER.EMAIL_FIELD) except USER.DoesNotExist: email = username body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(username, request) # ... rest of the code ...
d9ce6cc440019ecfc73f1c82e41da4e9ce02a234
smart_open/__init__.py
smart_open/__init__.py
import logging from smart_open import version from .smart_open_lib import open, parse_uri, smart_open, register_compressor from .s3 import iter_bucket as s3_iter_bucket __all__ = [ 'open', 'parse_uri', 'register_compressor', 's3_iter_bucket', 'smart_open', ] __version__ = version.__version__ logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler())
import logging from smart_open import version logger = logging.getLogger(__name__) if len(logger.handlers) == 0: logger.addHandler(logging.NullHandler()) from .smart_open_lib import open, parse_uri, smart_open, register_compressor from .s3 import iter_bucket as s3_iter_bucket __all__ = [ 'open', 'parse_uri', 'register_compressor', 's3_iter_bucket', 'smart_open', ] __version__ = version.__version__
Configure logging handlers before submodule imports
Configure logging handlers before submodule imports - Fix #474 - Fix #475
Python
mit
RaRe-Technologies/smart_open,RaRe-Technologies/smart_open,piskvorky/smart_open
import logging from smart_open import version + + logger = logging.getLogger(__name__) + if len(logger.handlers) == 0: + logger.addHandler(logging.NullHandler()) from .smart_open_lib import open, parse_uri, smart_open, register_compressor from .s3 import iter_bucket as s3_iter_bucket __all__ = [ 'open', 'parse_uri', 'register_compressor', 's3_iter_bucket', 'smart_open', ] - __version__ = version.__version__ - logger = logging.getLogger(__name__) - logger.addHandler(logging.NullHandler()) -
Configure logging handlers before submodule imports
## Code Before: import logging from smart_open import version from .smart_open_lib import open, parse_uri, smart_open, register_compressor from .s3 import iter_bucket as s3_iter_bucket __all__ = [ 'open', 'parse_uri', 'register_compressor', 's3_iter_bucket', 'smart_open', ] __version__ = version.__version__ logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) ## Instruction: Configure logging handlers before submodule imports ## Code After: import logging from smart_open import version logger = logging.getLogger(__name__) if len(logger.handlers) == 0: logger.addHandler(logging.NullHandler()) from .smart_open_lib import open, parse_uri, smart_open, register_compressor from .s3 import iter_bucket as s3_iter_bucket __all__ = [ 'open', 'parse_uri', 'register_compressor', 's3_iter_bucket', 'smart_open', ] __version__ = version.__version__
... from smart_open import version logger = logging.getLogger(__name__) if len(logger.handlers) == 0: logger.addHandler(logging.NullHandler()) ... __version__ = version.__version__ ...
e081646028e4f3283fb9c7278fed89c3e42cc4d3
server/tests/api/test_user_api.py
server/tests/api/test_user_api.py
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response = self.test_client.get('/api/users') assert response.status_code is 200 def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': '[email protected]', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 0 assert response.status_code is 200 @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 1 assert response.status_code is 200 @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': '[email protected]', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
Implement tests for getting empty users list and single user list
Implement tests for getting empty users list and single user list
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" - response = self.test_client.get('/api/users') + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 0 assert response.status_code is 200 + @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" + response, data = self.api_request('get', '/api/users') + assert data['num_results'] is 1 + assert response.status_code is 200 + @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" + @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" + @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': '[email protected]', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
Implement tests for getting empty users list and single user list
## Code Before: import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response = self.test_client.get('/api/users') assert response.status_code is 200 def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': '[email protected]', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201 ## Instruction: Implement tests for getting empty users list and single user list ## Code After: import json from tests.helpers import FlaskTestCase, fixtures class TestUserAPI(FlaskTestCase): @fixtures('base.json') def test_get_empty_users(self): """Test GET /api/users endpoint with no data""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 0 assert response.status_code is 200 @fixtures('single_user.json') def test_get_one_user(self): """Test GET /api/users endpoint with a single user""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 1 assert response.status_code is 200 @fixtures('many_users.json') def test_get_multiple_users(self): """Test GET /api/users endpoint with multple users""" @fixtures('many_users.json') def test_get_no_user_by_id(self): """Test GET /api/users/(int:id) for missing user""" @fixtures('many_users.json') def test_user_by_id(self): """Test GET /api/users(int:id) for existing user""" @fixtures('base.json') def test_post_user(self): data = { 'name': 'Giancarlo Anemone', 'username': 'ganemone', 'email': '[email protected]', 'password': 'password', 'confirm': 'password' } response = self.app.post( '/api/users', data=json.dumps(data) ) assert response.status_code is 201
// ... existing code ... """Test GET /api/users endpoint with no data""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 0 assert response.status_code is 200 // ... modified code ... @fixtures('single_user.json') def test_get_one_user(self): ... """Test GET /api/users endpoint with a single user""" response, data = self.api_request('get', '/api/users') assert data['num_results'] is 1 assert response.status_code is 200 @fixtures('many_users.json') def test_get_multiple_users(self): ... @fixtures('many_users.json') def test_get_no_user_by_id(self): ... @fixtures('many_users.json') def test_user_by_id(self): // ... rest of the code ...
539c7a85a84fdb2fbe8ee3f5803778baf0c66841
wmt/flask/__init__.py
wmt/flask/__init__.py
import os from flask import Flask from flask_login import LoginManager from passlib.context import CryptContext from .core import db from .blueprints import register_blueprints from .errors import ERROR_HANDLERS class User(object): def __init__(self, id): self._id = id def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self._id def create_app(settings_override=None, register_security_blueprint=True): app = Flask(__name__, instance_relative_config=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(userid): return User(userid) @app.before_first_request def create_database(): db.create_all() app.config.from_object('wmt.flask.settings') app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) app.config['pw'] = CryptContext.from_string( app.config['CRYPT_INI_CONTENTS'], section='passlib') db.init_app(app) register_blueprints(app, __name__, __path__) for error, func in ERROR_HANDLERS: app.errorhandler(error)(func) return app
import os from flask import Flask from flask_login import LoginManager from passlib.context import CryptContext from .settings import WmtSettings from .core import db from .blueprints import register_blueprints from .errors import ERROR_HANDLERS class User(object): def __init__(self, id): self._id = id def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self._id def create_app(settings_override=None, register_security_blueprint=True, wmt_root_path=None): app = Flask(__name__, instance_relative_config=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(userid): return User(userid) @app.before_first_request def create_database(): db.create_all() app.config.from_object(WmtSettings( os.path.join(wmt_root_path or app.root_path, 'db'))) #app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db')) app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) app.config['pw'] = CryptContext.from_string( app.config['CRYPT_INI_CONTENTS'], section='passlib') db.init_app(app) register_blueprints(app, __name__, __path__) for error, func in ERROR_HANDLERS: app.errorhandler(error)(func) return app
Use settings classes and set wmt_root_path.
Use settings classes and set wmt_root_path.
Python
mit
mcflugen/wmt-rest,mcflugen/wmt-rest
import os from flask import Flask from flask_login import LoginManager from passlib.context import CryptContext + from .settings import WmtSettings from .core import db from .blueprints import register_blueprints from .errors import ERROR_HANDLERS class User(object): def __init__(self, id): self._id = id def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self._id - def create_app(settings_override=None, register_security_blueprint=True): + def create_app(settings_override=None, register_security_blueprint=True, + wmt_root_path=None): app = Flask(__name__, instance_relative_config=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(userid): return User(userid) @app.before_first_request def create_database(): db.create_all() - app.config.from_object('wmt.flask.settings') + app.config.from_object(WmtSettings( + os.path.join(wmt_root_path or app.root_path, 'db'))) + #app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db')) app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) app.config['pw'] = CryptContext.from_string( app.config['CRYPT_INI_CONTENTS'], section='passlib') db.init_app(app) register_blueprints(app, __name__, __path__) for error, func in ERROR_HANDLERS: app.errorhandler(error)(func) return app
Use settings classes and set wmt_root_path.
## Code Before: import os from flask import Flask from flask_login import LoginManager from passlib.context import CryptContext from .core import db from .blueprints import register_blueprints from .errors import ERROR_HANDLERS class User(object): def __init__(self, id): self._id = id def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self._id def create_app(settings_override=None, register_security_blueprint=True): app = Flask(__name__, instance_relative_config=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(userid): return User(userid) @app.before_first_request def create_database(): db.create_all() app.config.from_object('wmt.flask.settings') app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) app.config['pw'] = CryptContext.from_string( app.config['CRYPT_INI_CONTENTS'], section='passlib') db.init_app(app) register_blueprints(app, __name__, __path__) for error, func in ERROR_HANDLERS: app.errorhandler(error)(func) return app ## Instruction: Use settings classes and set wmt_root_path. ## Code After: import os from flask import Flask from flask_login import LoginManager from passlib.context import CryptContext from .settings import WmtSettings from .core import db from .blueprints import register_blueprints from .errors import ERROR_HANDLERS class User(object): def __init__(self, id): self._id = id def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self._id def create_app(settings_override=None, register_security_blueprint=True, wmt_root_path=None): app = Flask(__name__, instance_relative_config=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(userid): return User(userid) @app.before_first_request def create_database(): db.create_all() app.config.from_object(WmtSettings( os.path.join(wmt_root_path or app.root_path, 'db'))) #app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db')) app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) app.config['pw'] = CryptContext.from_string( app.config['CRYPT_INI_CONTENTS'], section='passlib') db.init_app(app) register_blueprints(app, __name__, __path__) for error, func in ERROR_HANDLERS: app.errorhandler(error)(func) return app
// ... existing code ... from .settings import WmtSettings from .core import db // ... modified code ... def create_app(settings_override=None, register_security_blueprint=True, wmt_root_path=None): app = Flask(__name__, instance_relative_config=True) ... app.config.from_object(WmtSettings( os.path.join(wmt_root_path or app.root_path, 'db'))) #app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db')) app.config.from_pyfile('settings.cfg', silent=True) // ... rest of the code ...
71cdbeada7e11634e1168ca2e825167cbe87b4de
spacy/lang/de/norm_exceptions.py
spacy/lang/de/norm_exceptions.py
from __future__ import unicode_literals # Here we only want to include the absolute most common words. Otherwise, # this list would get impossibly long for German – especially considering the # old vs. new spelling rules, and all possible cases. _exc = { "daß": "dass" } NORM_EXCEPTIONS = {} for string, norm in _exc.items(): NORM_EXCEPTIONS[string] = norm NORM_EXCEPTIONS[string.title()] = norm
from __future__ import unicode_literals # Here we only want to include the absolute most common words. Otherwise, # this list would get impossibly long for German – especially considering the # old vs. new spelling rules, and all possible cases. _exc = { "daß": "dass" } NORM_EXCEPTIONS = {} for string, norm in _exc.items(): NORM_EXCEPTIONS[string.title()] = norm
Revert "Also include lowercase norm exceptions"
Revert "Also include lowercase norm exceptions" This reverts commit 70f4e8adf37cfcfab60be2b97d6deae949b30e9e.
Python
mit
aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy
from __future__ import unicode_literals # Here we only want to include the absolute most common words. Otherwise, # this list would get impossibly long for German – especially considering the # old vs. new spelling rules, and all possible cases. _exc = { "daß": "dass" } NORM_EXCEPTIONS = {} for string, norm in _exc.items(): - NORM_EXCEPTIONS[string] = norm NORM_EXCEPTIONS[string.title()] = norm
Revert "Also include lowercase norm exceptions"
## Code Before: from __future__ import unicode_literals # Here we only want to include the absolute most common words. Otherwise, # this list would get impossibly long for German – especially considering the # old vs. new spelling rules, and all possible cases. _exc = { "daß": "dass" } NORM_EXCEPTIONS = {} for string, norm in _exc.items(): NORM_EXCEPTIONS[string] = norm NORM_EXCEPTIONS[string.title()] = norm ## Instruction: Revert "Also include lowercase norm exceptions" ## Code After: from __future__ import unicode_literals # Here we only want to include the absolute most common words. Otherwise, # this list would get impossibly long for German – especially considering the # old vs. new spelling rules, and all possible cases. _exc = { "daß": "dass" } NORM_EXCEPTIONS = {} for string, norm in _exc.items(): NORM_EXCEPTIONS[string.title()] = norm
# ... existing code ... for string, norm in _exc.items(): NORM_EXCEPTIONS[string.title()] = norm # ... rest of the code ...
87cd4025aed62d76e3c64ba939f5241307b4478f
CascadeCount.py
CascadeCount.py
from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep(mapper_init=self.mapper_init, mapper=self.mapper ) ] if __name__ == '__main__': MRJobNetworkX.run()
from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep(mapper_init=self.mapper_init, mapper=self.mapper ) ] if __name__ == '__main__': CascadeCount.run()
Load from the pre processed data
Load from the pre processed data
Python
mit
danjamker/DiffusionSimulation
from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep(mapper_init=self.mapper_init, mapper=self.mapper ) ] if __name__ == '__main__': - MRJobNetworkX.run() + CascadeCount.run()
Load from the pre processed data
## Code Before: from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep(mapper_init=self.mapper_init, mapper=self.mapper ) ] if __name__ == '__main__': MRJobNetworkX.run() ## Instruction: Load from the pre processed data ## Code After: from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep(mapper_init=self.mapper_init, mapper=self.mapper ) ] if __name__ == '__main__': CascadeCount.run()
# ... existing code ... if __name__ == '__main__': CascadeCount.run() # ... rest of the code ...
8affeda715b1facf12de1dab1d445bbe54616306
oscar/core/ajax.py
oscar/core/ajax.py
import six from django.contrib import messages from six.moves import map class FlashMessages(object): """ Intermediate container for flash messages. This is useful as, at the time of creating the message, we don't know whether the response is an AJAX response or not. """ def __init__(self): self.msgs = {} def add_message(self, level, message): self.msgs.setdefault(level, []).append(message) def add_messages(self, level, messages): for msg in messages: self.add_message(level, msg) def info(self, message): self.add_message(messages.INFO, message) def warning(self, message): self.add_message(messages.WARNING, message) def error(self, message): self.add_message(messages.ERROR, message) def success(self, message): self.add_message(messages.SUCCESS, message) def to_json(self): payload = {} for level, msgs in self.msgs.items(): tag = messages.DEFAULT_TAGS.get(level, 'info') payload[tag] = map(six.text_type, msgs) return payload def apply_to_request(self, request): for level, msgs in self.msgs.items(): for msg in msgs: messages.add_message(request, level, msg)
import six from django.contrib import messages from six.moves import map class FlashMessages(object): """ Intermediate container for flash messages. This is useful as, at the time of creating the message, we don't know whether the response is an AJAX response or not. """ def __init__(self): self.msgs = {} def add_message(self, level, message): self.msgs.setdefault(level, []).append(message) def add_messages(self, level, messages): for msg in messages: self.add_message(level, msg) def info(self, message): self.add_message(messages.INFO, message) def warning(self, message): self.add_message(messages.WARNING, message) def error(self, message): self.add_message(messages.ERROR, message) def success(self, message): self.add_message(messages.SUCCESS, message) def to_json(self): payload = {} for level, msgs in self.msgs.items(): tag = messages.DEFAULT_TAGS.get(level, 'info') payload[tag] = [six.text_type(msg) for msg in msgs] return payload def apply_to_request(self, request): for level, msgs in self.msgs.items(): for msg in msgs: messages.add_message(request, level, msg)
Fix JSON serialisation problem with AJAX basket
Fix JSON serialisation problem with AJAX basket six.moves.map returns itertools.imap which won't serialize to JSON. This commit unpacks the list into a normal list of strings to circumvent the issue.
Python
bsd-3-clause
jmt4/django-oscar,jmt4/django-oscar,dongguangming/django-oscar,lijoantony/django-oscar,kapt/django-oscar,okfish/django-oscar,vovanbo/django-oscar,bnprk/django-oscar,Bogh/django-oscar,sasha0/django-oscar,ahmetdaglarbas/e-commerce,solarissmoke/django-oscar,bnprk/django-oscar,spartonia/django-oscar,WillisXChen/django-oscar,spartonia/django-oscar,WillisXChen/django-oscar,taedori81/django-oscar,elliotthill/django-oscar,sasha0/django-oscar,ka7eh/django-oscar,ademuk/django-oscar,josesanch/django-oscar,Bogh/django-oscar,jinnykoo/wuyisj,solarissmoke/django-oscar,pasqualguerrero/django-oscar,ka7eh/django-oscar,jlmadurga/django-oscar,michaelkuty/django-oscar,saadatqadri/django-oscar,pdonadeo/django-oscar,jlmadurga/django-oscar,binarydud/django-oscar,anentropic/django-oscar,rocopartners/django-oscar,manevant/django-oscar,mexeniz/django-oscar,adamend/django-oscar,django-oscar/django-oscar,monikasulik/django-oscar,okfish/django-oscar,kapari/django-oscar,DrOctogon/unwash_ecom,WadeYuChen/django-oscar,dongguangming/django-oscar,taedori81/django-oscar,solarissmoke/django-oscar,DrOctogon/unwash_ecom,saadatqadri/django-oscar,ka7eh/django-oscar,vovanbo/django-oscar,nickpack/django-oscar,WillisXChen/django-oscar,WillisXChen/django-oscar,sasha0/django-oscar,faratro/django-oscar,adamend/django-oscar,saadatqadri/django-oscar,binarydud/django-oscar,Jannes123/django-oscar,anentropic/django-oscar,faratro/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,eddiep1101/django-oscar,okfish/django-oscar,Bogh/django-oscar,thechampanurag/django-oscar,faratro/django-oscar,kapari/django-oscar,amirrpp/django-oscar,ademuk/django-oscar,marcoantoniooliveira/labweb,DrOctogon/unwash_ecom,mexeniz/django-oscar,manevant/django-oscar,josesanch/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,marcoantoniooliveira/labweb,machtfit/django-oscar,pdonadeo/django-oscar,ademuk/django-oscar,manevant/django-oscar,binarydud/django-oscar,bschuon/django-oscar,marcoantoniooliveira/labweb,saadatqadri/django-oscar,jlmadurga/django-oscar,kapt/django-oscar,pasqualguerrero/django-oscar,Jannes123/django-oscar,eddiep1101/django-oscar,nickpack/django-oscar,dongguangming/django-oscar,jinnykoo/wuyisj.com,jinnykoo/wuyisj.com,marcoantoniooliveira/labweb,MatthewWilkes/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,django-oscar/django-oscar,pasqualguerrero/django-oscar,itbabu/django-oscar,jmt4/django-oscar,pasqualguerrero/django-oscar,elliotthill/django-oscar,anentropic/django-oscar,WillisXChen/django-oscar,monikasulik/django-oscar,WadeYuChen/django-oscar,amirrpp/django-oscar,MatthewWilkes/django-oscar,vovanbo/django-oscar,QLGu/django-oscar,bschuon/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj,kapt/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,vovanbo/django-oscar,adamend/django-oscar,machtfit/django-oscar,monikasulik/django-oscar,rocopartners/django-oscar,faratro/django-oscar,nfletton/django-oscar,QLGu/django-oscar,kapari/django-oscar,monikasulik/django-oscar,spartonia/django-oscar,itbabu/django-oscar,itbabu/django-oscar,Jannes123/django-oscar,rocopartners/django-oscar,binarydud/django-oscar,taedori81/django-oscar,jinnykoo/christmas,pdonadeo/django-oscar,elliotthill/django-oscar,amirrpp/django-oscar,sonofatailor/django-oscar,nfletton/django-oscar,solarissmoke/django-oscar,manevant/django-oscar,itbabu/django-oscar,jinnykoo/wuyisj.com,thechampanurag/django-oscar,sonofatailor/django-oscar,nickpack/django-oscar,michaelkuty/django-oscar,lijoantony/django-oscar,django-oscar/django-oscar,ka7eh/django-oscar,ahmetdaglarbas/e-commerce,jinnykoo/wuyisj,anentropic/django-oscar,ahmetdaglarbas/e-commerce,thechampanurag/django-oscar,Bogh/django-oscar,QLGu/django-oscar,john-parton/django-oscar,michaelkuty/django-oscar,pdonadeo/django-oscar,eddiep1101/django-oscar,ahmetdaglarbas/e-commerce,thechampanurag/django-oscar,jmt4/django-oscar,spartonia/django-oscar,jlmadurga/django-oscar,michaelkuty/django-oscar,bschuon/django-oscar,mexeniz/django-oscar,ademuk/django-oscar,sonofatailor/django-oscar,dongguangming/django-oscar,nickpack/django-oscar,taedori81/django-oscar,adamend/django-oscar,jinnykoo/christmas,amirrpp/django-oscar,Jannes123/django-oscar,bschuon/django-oscar,QLGu/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,nfletton/django-oscar,kapari/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,john-parton/django-oscar,jinnykoo/christmas,MatthewWilkes/django-oscar,eddiep1101/django-oscar,josesanch/django-oscar,bnprk/django-oscar,john-parton/django-oscar,WadeYuChen/django-oscar,rocopartners/django-oscar,lijoantony/django-oscar,bnprk/django-oscar,john-parton/django-oscar
import six from django.contrib import messages from six.moves import map class FlashMessages(object): """ Intermediate container for flash messages. This is useful as, at the time of creating the message, we don't know whether the response is an AJAX response or not. """ def __init__(self): self.msgs = {} def add_message(self, level, message): self.msgs.setdefault(level, []).append(message) def add_messages(self, level, messages): for msg in messages: self.add_message(level, msg) def info(self, message): self.add_message(messages.INFO, message) def warning(self, message): self.add_message(messages.WARNING, message) def error(self, message): self.add_message(messages.ERROR, message) def success(self, message): self.add_message(messages.SUCCESS, message) def to_json(self): payload = {} for level, msgs in self.msgs.items(): tag = messages.DEFAULT_TAGS.get(level, 'info') - payload[tag] = map(six.text_type, msgs) + payload[tag] = [six.text_type(msg) for msg in msgs] return payload def apply_to_request(self, request): for level, msgs in self.msgs.items(): for msg in msgs: messages.add_message(request, level, msg)
Fix JSON serialisation problem with AJAX basket
## Code Before: import six from django.contrib import messages from six.moves import map class FlashMessages(object): """ Intermediate container for flash messages. This is useful as, at the time of creating the message, we don't know whether the response is an AJAX response or not. """ def __init__(self): self.msgs = {} def add_message(self, level, message): self.msgs.setdefault(level, []).append(message) def add_messages(self, level, messages): for msg in messages: self.add_message(level, msg) def info(self, message): self.add_message(messages.INFO, message) def warning(self, message): self.add_message(messages.WARNING, message) def error(self, message): self.add_message(messages.ERROR, message) def success(self, message): self.add_message(messages.SUCCESS, message) def to_json(self): payload = {} for level, msgs in self.msgs.items(): tag = messages.DEFAULT_TAGS.get(level, 'info') payload[tag] = map(six.text_type, msgs) return payload def apply_to_request(self, request): for level, msgs in self.msgs.items(): for msg in msgs: messages.add_message(request, level, msg) ## Instruction: Fix JSON serialisation problem with AJAX basket ## Code After: import six from django.contrib import messages from six.moves import map class FlashMessages(object): """ Intermediate container for flash messages. This is useful as, at the time of creating the message, we don't know whether the response is an AJAX response or not. """ def __init__(self): self.msgs = {} def add_message(self, level, message): self.msgs.setdefault(level, []).append(message) def add_messages(self, level, messages): for msg in messages: self.add_message(level, msg) def info(self, message): self.add_message(messages.INFO, message) def warning(self, message): self.add_message(messages.WARNING, message) def error(self, message): self.add_message(messages.ERROR, message) def success(self, message): self.add_message(messages.SUCCESS, message) def to_json(self): payload = {} for level, msgs in self.msgs.items(): tag = messages.DEFAULT_TAGS.get(level, 'info') payload[tag] = [six.text_type(msg) for msg in msgs] return payload def apply_to_request(self, request): for level, msgs in self.msgs.items(): for msg in msgs: messages.add_message(request, level, msg)
# ... existing code ... tag = messages.DEFAULT_TAGS.get(level, 'info') payload[tag] = [six.text_type(msg) for msg in msgs] return payload # ... rest of the code ...
18b0ddbbca429778a70f1e9b7f7d5140eb88d68f
tests/test_fs.py
tests/test_fs.py
from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize("/a/b/") == "/a/b" assert _normalize("/a//b") == "/a/b" assert _normalize("/a//b//") == "/a/b" def test_normalize_relative(): assert _normalize("a") == "a" assert _normalize("a/") == "a" assert _normalize("a/b") == "a/b" assert _normalize("a/b/") == "a/b" assert _normalize("a//b") == "a/b" assert _normalize("a//b//") == "a/b" def test_userPath2Path(): assert up2p("c", Path("/a/b")) == Path("/a/b/c") assert up2p("/c", Path("/a/b")) == Path("/c")
from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize("/a/b/") == "/a/b" assert _normalize("/a//b") == "/a/b" assert _normalize("/a//b//") == "/a/b" def test_normalize_relative(): assert _normalize("a") == "a" assert _normalize("a/") == "a" assert _normalize("a/b") == "a/b" assert _normalize("a/b/") == "a/b" assert _normalize("a//b") == "a/b" assert _normalize("a//b//") == "a/b" def test_userPath2Path(): assert up2p("c", Path("/a/b")) == Path("/a/b/c") assert up2p("/c", Path("/a/b")) == Path("/c") def test_cmp(): assert Path("/a/b") < Path("/a/c") assert Path("/a/c") > Path("/a/b") assert Path("/a/2") < Path("/b/1")
Add test to Path compare.
Add test to Path compare.
Python
mit
andrewguy9/farmfs,andrewguy9/farmfs
from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize("/a/b/") == "/a/b" assert _normalize("/a//b") == "/a/b" assert _normalize("/a//b//") == "/a/b" def test_normalize_relative(): assert _normalize("a") == "a" assert _normalize("a/") == "a" assert _normalize("a/b") == "a/b" assert _normalize("a/b/") == "a/b" assert _normalize("a//b") == "a/b" assert _normalize("a//b//") == "a/b" def test_userPath2Path(): assert up2p("c", Path("/a/b")) == Path("/a/b/c") assert up2p("/c", Path("/a/b")) == Path("/c") + def test_cmp(): + assert Path("/a/b") < Path("/a/c") + assert Path("/a/c") > Path("/a/b") + assert Path("/a/2") < Path("/b/1")
Add test to Path compare.
## Code Before: from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize("/a/b/") == "/a/b" assert _normalize("/a//b") == "/a/b" assert _normalize("/a//b//") == "/a/b" def test_normalize_relative(): assert _normalize("a") == "a" assert _normalize("a/") == "a" assert _normalize("a/b") == "a/b" assert _normalize("a/b/") == "a/b" assert _normalize("a//b") == "a/b" assert _normalize("a//b//") == "a/b" def test_userPath2Path(): assert up2p("c", Path("/a/b")) == Path("/a/b/c") assert up2p("/c", Path("/a/b")) == Path("/c") ## Instruction: Add test to Path compare. ## Code After: from farmfs.fs import normpath as _normalize from farmfs.fs import userPath2Path as up2p from farmfs.fs import Path def test_normalize_abs(): assert _normalize("/") == "/" assert _normalize("/a") == "/a" assert _normalize("/a/") == "/a" assert _normalize("/a/b") == "/a/b" assert _normalize("/a/b/") == "/a/b" assert _normalize("/a//b") == "/a/b" assert _normalize("/a//b//") == "/a/b" def test_normalize_relative(): assert _normalize("a") == "a" assert _normalize("a/") == "a" assert _normalize("a/b") == "a/b" assert _normalize("a/b/") == "a/b" assert _normalize("a//b") == "a/b" assert _normalize("a//b//") == "a/b" def test_userPath2Path(): assert up2p("c", Path("/a/b")) == Path("/a/b/c") assert up2p("/c", Path("/a/b")) == Path("/c") def test_cmp(): assert Path("/a/b") < Path("/a/c") assert Path("/a/c") > Path("/a/b") assert Path("/a/2") < Path("/b/1")
... def test_cmp(): assert Path("/a/b") < Path("/a/c") assert Path("/a/c") > Path("/a/b") assert Path("/a/2") < Path("/b/1") ...
b79ed827f7211efbcdef95286bf2d4113d6e8b88
posts/views.py
posts/views.py
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return Entry.objects.filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return super().get_queryset().filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
Fix ordering of category view
Fix ordering of category view Signed-off-by: Michal Čihař <[email protected]>
Python
agpl-3.0
nijel/photoblog,nijel/photoblog
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): - return Entry.objects.filter(category=self.kwargs['category']) + return super().get_queryset().filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
Fix ordering of category view
## Code Before: from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return Entry.objects.filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) ## Instruction: Fix ordering of category view ## Code After: from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 template_name = 'posts/entry_category.html' def get(self, request, slug, **kwargs): self.kwargs['category'] = get_object_or_404(Category, slug=slug) return super().get(request, kwargs) def get_queryset(self): return super().get_queryset().filter(category=self.kwargs['category']) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result['category'] = self.kwargs['category'] return result class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/kontakt/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form)
# ... existing code ... def get_queryset(self): return super().get_queryset().filter(category=self.kwargs['category']) # ... rest of the code ...
9aaf3bd6c376f608911b232d5f811e0b7964022f
tests/django_mysql_tests/tests.py
tests/django_mysql_tests/tests.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create()
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create()
Add second test, trying to trigger travis
Add second test, trying to trigger travis
Python
mit
nickmeharry/django-mysql,nickmeharry/django-mysql,arnau126/django-mysql,adamchainz/django-mysql,arnau126/django-mysql,graingert/django-mysql,graingert/django-mysql
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() + def test_two(self): + MyModel.objects.create() + MyModel.objects.create() +
Add second test, trying to trigger travis
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() ## Instruction: Add second test, trying to trigger travis ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create()
// ... existing code ... MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create() // ... rest of the code ...
494e7ff2e249a8202c8a71172be7f1870f56f9c3
mcavatar/views/public/__init__.py
mcavatar/views/public/__init__.py
from flask import Blueprint public = Blueprint('public', __name__, template_folder='templates') @public.route('/') def index(): return 'Hello World'
from flask import Blueprint public = Blueprint('public', __name__) @public.route('/') def index(): return 'Hello World'
Remove blueprint specific template directories.
Remove blueprint specific template directories.
Python
mit
joealcorn/MCAvatar
from flask import Blueprint - public = Blueprint('public', __name__, template_folder='templates') + public = Blueprint('public', __name__) @public.route('/') def index(): return 'Hello World'
Remove blueprint specific template directories.
## Code Before: from flask import Blueprint public = Blueprint('public', __name__, template_folder='templates') @public.route('/') def index(): return 'Hello World' ## Instruction: Remove blueprint specific template directories. ## Code After: from flask import Blueprint public = Blueprint('public', __name__) @public.route('/') def index(): return 'Hello World'
# ... existing code ... public = Blueprint('public', __name__) # ... rest of the code ...
a39a7eb7d43282337d3e3df10921a1b0d9f0e3e4
odeintw/__init__.py
odeintw/__init__.py
from numpy.testing import Tester as _Tester from ._odeintw import odeintw __version__ = "0.1.2.dev3" test = _Tester().test
from ._odeintw import odeintw __version__ = "0.1.2.dev3"
Remove some unused test infrastructure
MAINT: Remove some unused test infrastructure
Python
bsd-3-clause
WarrenWeckesser/odeintw
- from numpy.testing import Tester as _Tester from ._odeintw import odeintw __version__ = "0.1.2.dev3" - test = _Tester().test -
Remove some unused test infrastructure
## Code Before: from numpy.testing import Tester as _Tester from ._odeintw import odeintw __version__ = "0.1.2.dev3" test = _Tester().test ## Instruction: Remove some unused test infrastructure ## Code After: from ._odeintw import odeintw __version__ = "0.1.2.dev3"
... ... __version__ = "0.1.2.dev3" ...
547e002534d3a9757c84bad7e125b9186dd78078
tests/test_common.py
tests/test_common.py
import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/etc/slack'] self.config = ConfigParser.ConfigParser() self.config.read(search_paths) if self.config.has_section('Slack'): self.access_token = self.config.get('Slack', 'token') elif 'SLACK_TOKEN' in os.environ: self.access_token = os.environ['SLACK_TOKEN'] else: print('Authorization token not detected! The token is pulled from '\ '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') self.test_channel = self.config.get('Slack', 'test-channel') def set_up_slack(self): self.slack = slack.Slack(self.access_token)
import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/etc/slack'] self.config = ConfigParser.ConfigParser() self.config.read(search_paths) if self.config.has_section('Slack'): self.access_token = self.config.get('Slack', 'token') elif 'SLACK_TOKEN' in os.environ: self.access_token = os.environ['SLACK_TOKEN'] else: print('Authorization token not detected! The token is pulled from '\ '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') self.test_channel = self.config.get('Slack', 'test-channel') self.test_channel_name = self.config.get('Slack', 'test-channel-name') def set_up_slack(self): self.slack = slack.Slack(self.access_token)
Add new channel name for test.
Add new channel name for test.
Python
mit
nabetama/slacky
import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/etc/slack'] self.config = ConfigParser.ConfigParser() self.config.read(search_paths) if self.config.has_section('Slack'): self.access_token = self.config.get('Slack', 'token') elif 'SLACK_TOKEN' in os.environ: self.access_token = os.environ['SLACK_TOKEN'] else: print('Authorization token not detected! The token is pulled from '\ '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') - self.test_channel = self.config.get('Slack', 'test-channel') + self.test_channel = self.config.get('Slack', 'test-channel') + self.test_channel_name = self.config.get('Slack', 'test-channel-name') def set_up_slack(self): self.slack = slack.Slack(self.access_token)
Add new channel name for test.
## Code Before: import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/etc/slack'] self.config = ConfigParser.ConfigParser() self.config.read(search_paths) if self.config.has_section('Slack'): self.access_token = self.config.get('Slack', 'token') elif 'SLACK_TOKEN' in os.environ: self.access_token = os.environ['SLACK_TOKEN'] else: print('Authorization token not detected! The token is pulled from '\ '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') self.test_channel = self.config.get('Slack', 'test-channel') def set_up_slack(self): self.slack = slack.Slack(self.access_token) ## Instruction: Add new channel name for test. ## Code After: import os, os.path import ConfigParser package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) import slack class TestSlack(object): def setup(self): self.set_up_config() self.set_up_slack() def set_up_config(self): search_paths = [os.path.expanduser('~/.slack'), '/etc/slack'] self.config = ConfigParser.ConfigParser() self.config.read(search_paths) if self.config.has_section('Slack'): self.access_token = self.config.get('Slack', 'token') elif 'SLACK_TOKEN' in os.environ: self.access_token = os.environ['SLACK_TOKEN'] else: print('Authorization token not detected! The token is pulled from '\ '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') self.test_channel = self.config.get('Slack', 'test-channel') self.test_channel_name = self.config.get('Slack', 'test-channel-name') def set_up_slack(self): self.slack = slack.Slack(self.access_token)
# ... existing code ... '~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.') self.test_channel = self.config.get('Slack', 'test-channel') self.test_channel_name = self.config.get('Slack', 'test-channel-name') # ... rest of the code ...
be9d58ffcf23e4fb47d2c09e869368ab9ec738c9
localore/localore/embeds.py
localore/localore/embeds.py
from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(url, max_width=None): domain = urlparse(url).netloc # work around Embedly missing embedding HTML for Twitter and Instagram URLs if domain.endswith(( 'instagram.com', 'twitter.com', )): return oembed(url, max_width) embed_dict = get_default_finder()(url, max_width) if domain.endswith('soundcloud.com'): embed_dict['html'] = ( embed_dict['html'] .replace('visual%3Dtrue', 'visual%3Dfalse') .replace('width="500"', 'width="100%"') .replace('height="500"', 'height="166"') ) embed_dict['width'] = '100%' embed_dict['height'] = '166' return embed_dict
from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(url, max_width=None): domain = urlparse(url).netloc # work around Embedly missing embedding HTML for Twitter and Instagram URLs if domain.endswith(( 'instagram.com', 'twitter.com', )): return oembed(url, max_width) embed_dict = get_default_finder()(url, max_width) if domain.endswith('soundcloud.com'): embed_dict['html'] = ( embed_dict['html'] .replace('visual%3Dtrue', 'visual%3Dfalse') .replace('width="%s"' % embed_dict['width'], 'width="100%"') .replace('height="%s"' % embed_dict['height'], 'height="166"') ) embed_dict['width'] = None embed_dict['height'] = 166 return embed_dict
Fix SoundCloud embed width/height replacement.
Fix SoundCloud embed width/height replacement. SoundCloud embeds aren't always 500x500. Also, don't set the "width" embed dict key to '100%': "width"/"height" keys expect integers only.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(url, max_width=None): domain = urlparse(url).netloc # work around Embedly missing embedding HTML for Twitter and Instagram URLs if domain.endswith(( 'instagram.com', 'twitter.com', )): return oembed(url, max_width) embed_dict = get_default_finder()(url, max_width) if domain.endswith('soundcloud.com'): embed_dict['html'] = ( embed_dict['html'] .replace('visual%3Dtrue', 'visual%3Dfalse') - .replace('width="500"', 'width="100%"') + .replace('width="%s"' % embed_dict['width'], 'width="100%"') - .replace('height="500"', 'height="166"') + .replace('height="%s"' % embed_dict['height'], 'height="166"') ) - embed_dict['width'] = '100%' + embed_dict['width'] = None - embed_dict['height'] = '166' + embed_dict['height'] = 166 return embed_dict
Fix SoundCloud embed width/height replacement.
## Code Before: from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(url, max_width=None): domain = urlparse(url).netloc # work around Embedly missing embedding HTML for Twitter and Instagram URLs if domain.endswith(( 'instagram.com', 'twitter.com', )): return oembed(url, max_width) embed_dict = get_default_finder()(url, max_width) if domain.endswith('soundcloud.com'): embed_dict['html'] = ( embed_dict['html'] .replace('visual%3Dtrue', 'visual%3Dfalse') .replace('width="500"', 'width="100%"') .replace('height="500"', 'height="166"') ) embed_dict['width'] = '100%' embed_dict['height'] = '166' return embed_dict ## Instruction: Fix SoundCloud embed width/height replacement. ## Code After: from urllib.parse import urlparse from django.conf import settings from wagtail.wagtailembeds.finders.embedly import embedly from wagtail.wagtailembeds.finders.oembed import oembed def get_default_finder(): if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'): return embedly return oembed def finder(url, max_width=None): domain = urlparse(url).netloc # work around Embedly missing embedding HTML for Twitter and Instagram URLs if domain.endswith(( 'instagram.com', 'twitter.com', )): return oembed(url, max_width) embed_dict = get_default_finder()(url, max_width) if domain.endswith('soundcloud.com'): embed_dict['html'] = ( embed_dict['html'] .replace('visual%3Dtrue', 'visual%3Dfalse') .replace('width="%s"' % embed_dict['width'], 'width="100%"') .replace('height="%s"' % embed_dict['height'], 'height="166"') ) embed_dict['width'] = None embed_dict['height'] = 166 return embed_dict
// ... existing code ... .replace('visual%3Dtrue', 'visual%3Dfalse') .replace('width="%s"' % embed_dict['width'], 'width="100%"') .replace('height="%s"' % embed_dict['height'], 'height="166"') ) embed_dict['width'] = None embed_dict['height'] = 166 // ... rest of the code ...
daeabec6f055ca232903f50f307b5ab8a518b1aa
apps/domain/src/main/core/manager/environment_manager.py
apps/domain/src/main/core/manager/environment_manager.py
from typing import List from typing import Union from .database_manager import DatabaseManager from ..database.environment.environment import Environment from ..database.environment.user_environment import UserEnvironment from ..exceptions import ( EnvironmentNotFoundError, ) class EnvironmentManager(DatabaseManager): schema = Environment user_env_association_schema = UserEnvironment def __init__(self, database): self._schema = EnvironmentManager.schema self._association_schema = EnvironmentManager.user_env_association_schema self.db = database def association(self, user_id: str, env_id: str): new_association_obj = self._association_schema(user=user_id, environment=env_id) self.db.session.add(new_association_obj) self.db.session.commit() def get_environments(self, **kwargs): objects = ( self.db.session.query(self._association_schema).filter_by(**kwargs).all() ) return objects def first(self, **kwargs) -> Union[None, List]: result = super().first(**kwargs) if not result: raise EnvironmentNotFoundError return result def query(self, **kwargs) -> Union[None, List]: results = super().query(**kwargs) if len(results) == 0: raise EnvironmentNotFoundError return results
from typing import List from typing import Union from .database_manager import DatabaseManager from ..database.environment.environment import Environment from ..database.environment.user_environment import UserEnvironment from ..exceptions import ( EnvironmentNotFoundError, ) class EnvironmentManager(DatabaseManager): schema = Environment user_env_association_schema = UserEnvironment def __init__(self, database): self._schema = EnvironmentManager.schema self._association_schema = EnvironmentManager.user_env_association_schema self.db = database def association(self, user_id: str, env_id: str): new_association_obj = self._association_schema(user=user_id, environment=env_id) self.db.session.add(new_association_obj) self.db.session.commit() def get_environments(self, **kwargs): objects = ( self.db.session.query(self._association_schema).filter_by(**kwargs).all() ) return objects def delete_associations(self, environment_id): # Delete User environment Association associations = ( self.db.session.query(self._association_schema) .filter_by(environment=environment_id) .all() ) for association in associations: self.db.session.delete(association) self.db.session.commit() def first(self, **kwargs) -> Union[None, List]: result = super().first(**kwargs) if not result: raise EnvironmentNotFoundError return result def query(self, **kwargs) -> Union[None, List]: results = super().query(**kwargs) if len(results) == 0: raise EnvironmentNotFoundError return results
ADD delete_associations method at EnvironmentManager
ADD delete_associations method at EnvironmentManager
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from typing import List from typing import Union from .database_manager import DatabaseManager from ..database.environment.environment import Environment from ..database.environment.user_environment import UserEnvironment from ..exceptions import ( EnvironmentNotFoundError, ) class EnvironmentManager(DatabaseManager): schema = Environment user_env_association_schema = UserEnvironment def __init__(self, database): self._schema = EnvironmentManager.schema self._association_schema = EnvironmentManager.user_env_association_schema self.db = database def association(self, user_id: str, env_id: str): new_association_obj = self._association_schema(user=user_id, environment=env_id) self.db.session.add(new_association_obj) self.db.session.commit() def get_environments(self, **kwargs): objects = ( self.db.session.query(self._association_schema).filter_by(**kwargs).all() ) return objects + def delete_associations(self, environment_id): + # Delete User environment Association + associations = ( + self.db.session.query(self._association_schema) + .filter_by(environment=environment_id) + .all() + ) + for association in associations: + self.db.session.delete(association) + + self.db.session.commit() + def first(self, **kwargs) -> Union[None, List]: result = super().first(**kwargs) if not result: raise EnvironmentNotFoundError return result def query(self, **kwargs) -> Union[None, List]: results = super().query(**kwargs) if len(results) == 0: raise EnvironmentNotFoundError return results
ADD delete_associations method at EnvironmentManager
## Code Before: from typing import List from typing import Union from .database_manager import DatabaseManager from ..database.environment.environment import Environment from ..database.environment.user_environment import UserEnvironment from ..exceptions import ( EnvironmentNotFoundError, ) class EnvironmentManager(DatabaseManager): schema = Environment user_env_association_schema = UserEnvironment def __init__(self, database): self._schema = EnvironmentManager.schema self._association_schema = EnvironmentManager.user_env_association_schema self.db = database def association(self, user_id: str, env_id: str): new_association_obj = self._association_schema(user=user_id, environment=env_id) self.db.session.add(new_association_obj) self.db.session.commit() def get_environments(self, **kwargs): objects = ( self.db.session.query(self._association_schema).filter_by(**kwargs).all() ) return objects def first(self, **kwargs) -> Union[None, List]: result = super().first(**kwargs) if not result: raise EnvironmentNotFoundError return result def query(self, **kwargs) -> Union[None, List]: results = super().query(**kwargs) if len(results) == 0: raise EnvironmentNotFoundError return results ## Instruction: ADD delete_associations method at EnvironmentManager ## Code After: from typing import List from typing import Union from .database_manager import DatabaseManager from ..database.environment.environment import Environment from ..database.environment.user_environment import UserEnvironment from ..exceptions import ( EnvironmentNotFoundError, ) class EnvironmentManager(DatabaseManager): schema = Environment user_env_association_schema = UserEnvironment def __init__(self, database): self._schema = EnvironmentManager.schema self._association_schema = EnvironmentManager.user_env_association_schema self.db = database def association(self, user_id: str, env_id: str): new_association_obj = self._association_schema(user=user_id, environment=env_id) self.db.session.add(new_association_obj) self.db.session.commit() def get_environments(self, **kwargs): objects = ( self.db.session.query(self._association_schema).filter_by(**kwargs).all() ) return objects def delete_associations(self, environment_id): # Delete User environment Association associations = ( self.db.session.query(self._association_schema) .filter_by(environment=environment_id) .all() ) for association in associations: self.db.session.delete(association) self.db.session.commit() def first(self, **kwargs) -> Union[None, List]: result = super().first(**kwargs) if not result: raise EnvironmentNotFoundError return result def query(self, **kwargs) -> Union[None, List]: results = super().query(**kwargs) if len(results) == 0: raise EnvironmentNotFoundError return results
# ... existing code ... def delete_associations(self, environment_id): # Delete User environment Association associations = ( self.db.session.query(self._association_schema) .filter_by(environment=environment_id) .all() ) for association in associations: self.db.session.delete(association) self.db.session.commit() def first(self, **kwargs) -> Union[None, List]: # ... rest of the code ...
f9a1ac08fdffc464010c7c493c43a475342c821b
bot.py
bot.py
import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
Move imports to their own line
Move imports to their own line
Python
mit
wolfy1339/Python-IRC-Bot
- import zirc, ssl, socket + import zirc + import ssl + import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
Move imports to their own line
## Code Before: import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot() ## Instruction: Move imports to their own line ## Code After: import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
... import zirc import ssl import socket ...
50072e2e2fa2f650dd1899b14aaaecb2dfe909ef
tests/test_plugins.py
tests/test_plugins.py
import os from sigal.gallery import Gallery from sigal import init_plugins CURRENT_DIR = os.path.dirname(__file__) def test_plugins(settings, tmpdir): settings['destination'] = str(tmpdir) if "sigal.plugins.nomedia" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.nomedia"] if "sigal.plugins.media_page" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.media_page"] init_plugins(settings) gal = Gallery(settings) gal.build() out_html = os.path.join(settings['destination'], 'dir2', 'exo20101028-b-full.jpg.html') assert os.path.isfile(out_html) for path, dirs, files in os.walk(os.path.join(str(tmpdir), "nomedia")): assert "ignore" not in path for file in files: assert "ignore" not in file
import blinker import os from sigal.gallery import Gallery from sigal import init_plugins, signals CURRENT_DIR = os.path.dirname(__file__) def test_plugins(settings, tmpdir): settings['destination'] = str(tmpdir) if "sigal.plugins.nomedia" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.nomedia"] if "sigal.plugins.media_page" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.media_page"] try: init_plugins(settings) gal = Gallery(settings) gal.build() finally: # Reset plugins for name in dir(signals): if not name.startswith('_'): try: sig = getattr(signals, name) if isinstance(sig, blinker.Signal): sig.receivers.clear() except Exception: pass out_html = os.path.join(settings['destination'], 'dir2', 'exo20101028-b-full.jpg.html') assert os.path.isfile(out_html) for path, dirs, files in os.walk(os.path.join(str(tmpdir), "nomedia")): assert "ignore" not in path for file in files: assert "ignore" not in file
Clear signals after testing plugins
Clear signals after testing plugins
Python
mit
xouillet/sigal,t-animal/sigal,xouillet/sigal,saimn/sigal,xouillet/sigal,jasuarez/sigal,t-animal/sigal,t-animal/sigal,jasuarez/sigal,saimn/sigal,jasuarez/sigal,saimn/sigal
+ import blinker import os from sigal.gallery import Gallery - from sigal import init_plugins + from sigal import init_plugins, signals CURRENT_DIR = os.path.dirname(__file__) def test_plugins(settings, tmpdir): settings['destination'] = str(tmpdir) if "sigal.plugins.nomedia" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.nomedia"] if "sigal.plugins.media_page" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.media_page"] + try: - init_plugins(settings) + init_plugins(settings) - gal = Gallery(settings) + gal = Gallery(settings) - gal.build() + gal.build() + finally: + # Reset plugins + for name in dir(signals): + if not name.startswith('_'): + try: + sig = getattr(signals, name) + if isinstance(sig, blinker.Signal): + sig.receivers.clear() + except Exception: + pass out_html = os.path.join(settings['destination'], 'dir2', 'exo20101028-b-full.jpg.html') assert os.path.isfile(out_html) for path, dirs, files in os.walk(os.path.join(str(tmpdir), "nomedia")): assert "ignore" not in path for file in files: assert "ignore" not in file
Clear signals after testing plugins
## Code Before: import os from sigal.gallery import Gallery from sigal import init_plugins CURRENT_DIR = os.path.dirname(__file__) def test_plugins(settings, tmpdir): settings['destination'] = str(tmpdir) if "sigal.plugins.nomedia" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.nomedia"] if "sigal.plugins.media_page" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.media_page"] init_plugins(settings) gal = Gallery(settings) gal.build() out_html = os.path.join(settings['destination'], 'dir2', 'exo20101028-b-full.jpg.html') assert os.path.isfile(out_html) for path, dirs, files in os.walk(os.path.join(str(tmpdir), "nomedia")): assert "ignore" not in path for file in files: assert "ignore" not in file ## Instruction: Clear signals after testing plugins ## Code After: import blinker import os from sigal.gallery import Gallery from sigal import init_plugins, signals CURRENT_DIR = os.path.dirname(__file__) def test_plugins(settings, tmpdir): settings['destination'] = str(tmpdir) if "sigal.plugins.nomedia" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.nomedia"] if "sigal.plugins.media_page" not in settings["plugins"]: settings['plugins'] += ["sigal.plugins.media_page"] try: init_plugins(settings) gal = Gallery(settings) gal.build() finally: # Reset plugins for name in dir(signals): if not name.startswith('_'): try: sig = getattr(signals, name) if isinstance(sig, blinker.Signal): sig.receivers.clear() except Exception: pass out_html = os.path.join(settings['destination'], 'dir2', 'exo20101028-b-full.jpg.html') assert os.path.isfile(out_html) for path, dirs, files in os.walk(os.path.join(str(tmpdir), "nomedia")): assert "ignore" not in path for file in files: assert "ignore" not in file
# ... existing code ... import blinker import os # ... modified code ... from sigal.gallery import Gallery from sigal import init_plugins, signals ... try: init_plugins(settings) gal = Gallery(settings) gal.build() finally: # Reset plugins for name in dir(signals): if not name.startswith('_'): try: sig = getattr(signals, name) if isinstance(sig, blinker.Signal): sig.receivers.clear() except Exception: pass # ... rest of the code ...
67d4f376586c912f852b98c75f7de04aeb05979a
pag/words.py
pag/words.py
"""Get words from files in "src/dictionary/".""" import os def get_word_list(filepath): """ Get a list of words from a file. Input: file name Output: dict with formula {word: [synonym, synonym]}""" filepath = os.path.abspath(filepath) assert os.path.isfile(filepath), 'Must be a file' f = open(filepath, 'r') contents = f.read() txt = contents.strip().split('\n') if ':' in contents: ntxt = txt[:] for line in txt: if line[0] == '#': ntxt.remove(ntxt[ntxt.index(line)]) elif ':' not in line: ntxt[ntxt.index(line)] = line + ':' txt = ntxt words = {} for line in txt: index = line.split(':')[0] words[index] = line.split(':')[1].split(',') for syn in words[index]: if syn == '': words[index].remove(syn) else: words = [word.strip() for word in txt] f.close() return words verbs = get_word_list('dictionary/verbs.txt') nouns = get_word_list('dictionary/nouns.txt') extras = get_word_list('dictionary/extras.txt') directions = get_word_list('dictionary/directions.txt')
"""Get words from files in "src/dictionary/".""" import os def get_word_list(filepath): """ Get a list of words from a file. Input: file name Output: dict with formula {word: [synonym, synonym]}""" filepath = os.path.abspath(filepath) assert os.path.isfile(filepath), 'Must be a file' f = open(filepath, 'r') contents = f.read() txt = contents.strip().split('\n') ntxt = txt[:] for line in txt: if line[0] == '#': ntxt.remove(ntxt[ntxt.index(line)]) elif ':' not in line: ntxt[ntxt.index(line)] = line + ':' txt = ntxt words = {} for line in txt: index = line.split(':')[0] words[index] = line.split(':')[1].split(',') for syn in words[index]: if syn == '': words[index].remove(syn) f.close() return words verbs = get_word_list('dictionary/verbs.txt') nouns = get_word_list('dictionary/nouns.txt') extras = get_word_list('dictionary/extras.txt') directions = get_word_list('dictionary/directions.txt')
Remove useless and confusing code
Remove useless and confusing code
Python
mit
allanburleson/python-adventure-game,disorientedperson/python-adventure-game
"""Get words from files in "src/dictionary/".""" import os def get_word_list(filepath): """ Get a list of words from a file. Input: file name Output: dict with formula {word: [synonym, synonym]}""" filepath = os.path.abspath(filepath) assert os.path.isfile(filepath), 'Must be a file' f = open(filepath, 'r') contents = f.read() txt = contents.strip().split('\n') - if ':' in contents: - ntxt = txt[:] + ntxt = txt[:] - for line in txt: + for line in txt: - if line[0] == '#': + if line[0] == '#': - ntxt.remove(ntxt[ntxt.index(line)]) + ntxt.remove(ntxt[ntxt.index(line)]) - elif ':' not in line: + elif ':' not in line: - ntxt[ntxt.index(line)] = line + ':' + ntxt[ntxt.index(line)] = line + ':' - txt = ntxt + txt = ntxt - words = {} + words = {} - for line in txt: + for line in txt: - index = line.split(':')[0] + index = line.split(':')[0] - words[index] = line.split(':')[1].split(',') + words[index] = line.split(':')[1].split(',') - for syn in words[index]: + for syn in words[index]: - if syn == '': + if syn == '': - words[index].remove(syn) + words[index].remove(syn) - else: - words = [word.strip() for word in txt] f.close() return words verbs = get_word_list('dictionary/verbs.txt') nouns = get_word_list('dictionary/nouns.txt') extras = get_word_list('dictionary/extras.txt') directions = get_word_list('dictionary/directions.txt')
Remove useless and confusing code
## Code Before: """Get words from files in "src/dictionary/".""" import os def get_word_list(filepath): """ Get a list of words from a file. Input: file name Output: dict with formula {word: [synonym, synonym]}""" filepath = os.path.abspath(filepath) assert os.path.isfile(filepath), 'Must be a file' f = open(filepath, 'r') contents = f.read() txt = contents.strip().split('\n') if ':' in contents: ntxt = txt[:] for line in txt: if line[0] == '#': ntxt.remove(ntxt[ntxt.index(line)]) elif ':' not in line: ntxt[ntxt.index(line)] = line + ':' txt = ntxt words = {} for line in txt: index = line.split(':')[0] words[index] = line.split(':')[1].split(',') for syn in words[index]: if syn == '': words[index].remove(syn) else: words = [word.strip() for word in txt] f.close() return words verbs = get_word_list('dictionary/verbs.txt') nouns = get_word_list('dictionary/nouns.txt') extras = get_word_list('dictionary/extras.txt') directions = get_word_list('dictionary/directions.txt') ## Instruction: Remove useless and confusing code ## Code After: """Get words from files in "src/dictionary/".""" import os def get_word_list(filepath): """ Get a list of words from a file. Input: file name Output: dict with formula {word: [synonym, synonym]}""" filepath = os.path.abspath(filepath) assert os.path.isfile(filepath), 'Must be a file' f = open(filepath, 'r') contents = f.read() txt = contents.strip().split('\n') ntxt = txt[:] for line in txt: if line[0] == '#': ntxt.remove(ntxt[ntxt.index(line)]) elif ':' not in line: ntxt[ntxt.index(line)] = line + ':' txt = ntxt words = {} for line in txt: index = line.split(':')[0] words[index] = line.split(':')[1].split(',') for syn in words[index]: if syn == '': words[index].remove(syn) f.close() return words verbs = get_word_list('dictionary/verbs.txt') nouns = get_word_list('dictionary/nouns.txt') extras = get_word_list('dictionary/extras.txt') directions = get_word_list('dictionary/directions.txt')
# ... existing code ... txt = contents.strip().split('\n') ntxt = txt[:] for line in txt: if line[0] == '#': ntxt.remove(ntxt[ntxt.index(line)]) elif ':' not in line: ntxt[ntxt.index(line)] = line + ':' txt = ntxt words = {} for line in txt: index = line.split(':')[0] words[index] = line.split(':')[1].split(',') for syn in words[index]: if syn == '': words[index].remove(syn) f.close() # ... rest of the code ...
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a
deen/main.py
deen/main.py
import sys import logging import pathlib from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = str(pathlib.PurePath(__file__).parent / 'icon.png') LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
import sys import logging import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
Use os.path instead of pathlib
Use os.path instead of pathlib
Python
apache-2.0
takeshixx/deen,takeshixx/deen
import sys import logging - import pathlib + import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen - ICON = str(pathlib.PurePath(__file__).parent / 'icon.png') + ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
Use os.path instead of pathlib
## Code Before: import sys import logging import pathlib from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = str(pathlib.PurePath(__file__).parent / 'icon.png') LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_() ## Instruction: Use os.path instead of pathlib ## Code After: import sys import logging import os.path from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from deen.widgets.core import Deen ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s') def main(): app = QApplication(sys.argv) ex = Deen() ex.setWindowIcon(QIcon(ICON)) LOGGER.addHandler(ex.log) return app.exec_()
... import logging import os.path ... ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png' LOGGER = logging.getLogger() ...
8baa86cb381aaf52b16c7e0647a0b50cdbbd677a
st2common/st2common/util/db.py
st2common/st2common/util/db.py
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) if isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} if isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
Use if-elif instead of multiple if statements to check types
Use if-elif instead of multiple if statements to check types Use if-elif instead of multiple if statements to check types when converting from MongoDB BaseDict and BaseList to python dict and list types. Once the value is converted, use another if-elif block to recursively evaluate and convert the values of dict and list.
Python
apache-2.0
nzlosh/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2
from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): + # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) - - if isinstance(value, mongoengine.base.datastructures.BaseList): + elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) + # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} - - if isinstance(value, list): + elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
Use if-elif instead of multiple if statements to check types
## Code Before: from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) if isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} if isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value ## Instruction: Use if-elif instead of multiple if statements to check types ## Code After: from __future__ import absolute_import import mongoengine import six def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): value = dict(value) elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) # Recursively traverse the dict and list to convert values. if isinstance(value, dict): value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] return value
... def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongoengine.base.datastructures.BaseDict): ... value = dict(value) elif isinstance(value, mongoengine.base.datastructures.BaseList): value = list(value) ... # Recursively traverse the dict and list to convert values. if isinstance(value, dict): ... value = {k: mongodb_to_python_types(v) for k, v in six.iteritems(value)} elif isinstance(value, list): value = [mongodb_to_python_types(v) for v in value] ...
3a3997b19966560b828efb1699ee29a58cacbfc8
spriteworld/configs/cobra/common.py
spriteworld/configs/cobra/common.py
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
Remove noise from default COBRA configs.
Remove noise from default COBRA configs. PiperOrigin-RevId: 265733849 Change-Id: Ie0e7c0385497852fd85c769ee85c951542c14463
Python
apache-2.0
deepmind/spriteworld
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): - return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) + return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
Remove noise from default COBRA configs.
## Code Before: """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) } ## Instruction: Remove noise from default COBRA configs. ## Code After: """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
// ... existing code ... def action_space(): return action_spaces.SelectMove(scale=0.25) // ... rest of the code ...
0078bb14b85df519744371df89e243822a86ed4c
generate.py
generate.py
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print(bytes(random.sample(population, 256)))
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print('WIRING') print(bytes(random.sample(population, 256))) print('NOTCHES') print(random.sample(population, 3))
Add a little more detail to the generator
Add a little more detail to the generator
Python
mit
spgill/bitnigma
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': + print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': + print('WIRING') print(bytes(random.sample(population, 256))) + print('NOTCHES') + print(random.sample(population, 3))
Add a little more detail to the generator
## Code Before: import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print(bytes(random.sample(population, 256))) ## Instruction: Add a little more detail to the generator ## Code After: import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print('WIRING') print(bytes(random.sample(population, 256))) print('NOTCHES') print(random.sample(population, 3))
# ... existing code ... if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) # ... modified code ... elif sys.argv[1] == 'rotor': print('WIRING') print(bytes(random.sample(population, 256))) print('NOTCHES') print(random.sample(population, 3)) # ... rest of the code ...
b28ceb8631446b57abb48be6c76db843ec747221
demo/set-sas-token.py
demo/set-sas-token.py
from __future__ import print_function import os from subprocess import check_output from sys import argv, stdout RSGRP = "travistestresourcegroup" STACC = "travistestresourcegr3014" def run(command): command = command.replace('az ', '', 1) cmd = 'python -m azure.cli {}'.format(command) print(cmd) out = check_output(cmd) return out.decode('utf-8') # get storage account connection string out = run('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string sas_token = run('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None) os.environ['AZURE_STORAGE_ACCOUNT'] = STACC os.environ['AZURE_SAS_TOKEN'] = sas_token print('\n=== Listing storage containers...===') print(run('az storage container list')) print('\n=== Trying to list storage shares *SHOULD FAIL*... ===') print('az storage container list --sas-token \"{}\"'.format(sas_token)) print(run('az storage share list')) exit(0)
from __future__ import print_function import os from subprocess import check_output from sys import argv, stdout RSGRP = "travistestresourcegroup" STACC = "travistestresourcegr3014" def cmd(command): """ Accepts a command line command as a string and returns stdout in UTF-8 format """ return check_output([str(x) for x in command.split()]).decode('utf-8') # get storage account connection string out = cmd('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string sas_token = cmd('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None) os.environ['AZURE_STORAGE_ACCOUNT'] = STACC os.environ['AZURE_SAS_TOKEN'] = sas_token print('\n=== Listing storage containers...===') print(cmd('az storage container list')) print('\n=== Trying to list storage shares *SHOULD FAIL*... ===') print('az storage container list --sas-token \"{}\"'.format(sas_token)) print(cmd('az storage share list')) exit(0)
Update python scripts to run on OSX.
Update python scripts to run on OSX.
Python
mit
QingChenmsft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure-cli,BurtBiel/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli
from __future__ import print_function import os from subprocess import check_output from sys import argv, stdout RSGRP = "travistestresourcegroup" STACC = "travistestresourcegr3014" - def run(command): + def cmd(command): + """ Accepts a command line command as a string and returns stdout in UTF-8 format """ + return check_output([str(x) for x in command.split()]).decode('utf-8') - command = command.replace('az ', '', 1) - cmd = 'python -m azure.cli {}'.format(command) - print(cmd) - out = check_output(cmd) - return out.decode('utf-8') # get storage account connection string - out = run('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) + out = cmd('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string - sas_token = run('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' + sas_token = cmd('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None) os.environ['AZURE_STORAGE_ACCOUNT'] = STACC os.environ['AZURE_SAS_TOKEN'] = sas_token print('\n=== Listing storage containers...===') - print(run('az storage container list')) + print(cmd('az storage container list')) print('\n=== Trying to list storage shares *SHOULD FAIL*... ===') print('az storage container list --sas-token \"{}\"'.format(sas_token)) - print(run('az storage share list')) + print(cmd('az storage share list')) exit(0)
Update python scripts to run on OSX.
## Code Before: from __future__ import print_function import os from subprocess import check_output from sys import argv, stdout RSGRP = "travistestresourcegroup" STACC = "travistestresourcegr3014" def run(command): command = command.replace('az ', '', 1) cmd = 'python -m azure.cli {}'.format(command) print(cmd) out = check_output(cmd) return out.decode('utf-8') # get storage account connection string out = run('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string sas_token = run('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None) os.environ['AZURE_STORAGE_ACCOUNT'] = STACC os.environ['AZURE_SAS_TOKEN'] = sas_token print('\n=== Listing storage containers...===') print(run('az storage container list')) print('\n=== Trying to list storage shares *SHOULD FAIL*... ===') print('az storage container list --sas-token \"{}\"'.format(sas_token)) print(run('az storage share list')) exit(0) ## Instruction: Update python scripts to run on OSX. ## Code After: from __future__ import print_function import os from subprocess import check_output from sys import argv, stdout RSGRP = "travistestresourcegroup" STACC = "travistestresourcegr3014" def cmd(command): """ Accepts a command line command as a string and returns stdout in UTF-8 format """ return check_output([str(x) for x in command.split()]).decode('utf-8') # get storage account connection string out = cmd('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') os.environ['AZURE_STORAGE_CONNECTION_STRING'] = connection_string sas_token = cmd('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() os.environ.pop('AZURE_STORAGE_CONNECTION_STRING', None) os.environ['AZURE_STORAGE_ACCOUNT'] = STACC os.environ['AZURE_SAS_TOKEN'] = sas_token print('\n=== Listing storage containers...===') print(cmd('az storage container list')) print('\n=== Trying to list storage shares *SHOULD FAIL*... ===') print('az storage container list --sas-token \"{}\"'.format(sas_token)) print(cmd('az storage share list')) exit(0)
# ... existing code ... def cmd(command): """ Accepts a command line command as a string and returns stdout in UTF-8 format """ return check_output([str(x) for x in command.split()]).decode('utf-8') # ... modified code ... # get storage account connection string out = cmd('az storage account connection-string -g {} -n {}'.format(RSGRP, STACC)) connection_string = out.replace('Connection String : ', '') ... sas_token = cmd('az storage account generate-sas --services b --resource-types sco --permission rwdl --expiry 2017-01-01T00:00Z' .format(connection_string)).strip() ... print('\n=== Listing storage containers...===') print(cmd('az storage container list')) ... print('az storage container list --sas-token \"{}\"'.format(sas_token)) print(cmd('az storage share list')) # ... rest of the code ...
b2cac05be3f6c510edfaf1ae478fabdcf06fd19a
mgsv_names.py
mgsv_names.py
import random global adjectives, animals, rares with open('adjectives.txt') as f: adjectives = f.readlines() with open('animals.txt') as f: animals = f.readlines() with open('rares.txt') as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def get_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(get_name())
import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
Load text files from the same dir as the script.
Load text files from the same dir as the script. Also renamed our name generator.
Python
unlicense
rotated8/mgsv_names
- import random + import random, os global adjectives, animals, rares - with open('adjectives.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() - with open('animals.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() - with open('rares.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } - def get_name(): + def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': - print(get_name()) + print(generate_name())
Load text files from the same dir as the script.
## Code Before: import random global adjectives, animals, rares with open('adjectives.txt') as f: adjectives = f.readlines() with open('animals.txt') as f: animals = f.readlines() with open('rares.txt') as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def get_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(get_name()) ## Instruction: Load text files from the same dir as the script. ## Code After: import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
// ... existing code ... import random, os // ... modified code ... with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() ... with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() ... with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() ... def generate_name(): adj = random.choice(adjectives).strip() ... if __name__ == '__main__': print(generate_name()) // ... rest of the code ...
6c2354a1e56477eb983b0adbcc2d15223c158184
foodsaving/subscriptions/consumers.py
foodsaving/subscriptions/consumers.py
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) message.reply_channel.send({"accept": True}) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() message.reply_channel.send({"accept": True})
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete()
Remove redundant ws accept replies
Remove redundant ws accept replies It's only relevent on connection
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) - message.reply_channel.send({"accept": True}) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() - message.reply_channel.send({"accept": True})
Remove redundant ws accept replies
## Code Before: from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) message.reply_channel.send({"accept": True}) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() message.reply_channel.send({"accept": True}) ## Instruction: Remove redundant ws accept replies ## Code After: from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete()
# ... existing code ... ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) # ... modified code ... ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() # ... rest of the code ...
8f04b56a842fa1a84e704af3c5b724c14006315e
server/models/user.py
server/models/user.py
from app_factory import db from models.session import Session class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column('name', db.String(50)) username = db.Column('username', db.String(50)) password = db.Column('password', db.String(50)) email = db.Column('email', db.String(128)) session = db.relationship( Session, uselist=False, backref=db.backref('user', order_by=id) ) def __repr__(self): return '' '<User(name={name}, username={username}, ' 'password={password}, email={email})>'.format( name=self.name, username=self.username, password=self.password, email=self.email ) def __init__(self, name, username, password, email): self.name = name self.username = username self.password = password self.email = email
from app_factory import db from models.session import Session class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column('name', db.String(50)) username = db.Column('username', db.String(50)) password = db.Column('password', db.String(50)) email = db.Column('email', db.String(128)) session = db.relationship( Session, uselist=False, backref=db.backref('user', order_by=id) ) def __init__(self, name, username, password, email): self.name = name self.username = username self.password = password self.email = email def __repr__(self): return '' '<User(name={name}, username={username}, ' 'password={password}, email={email})>'.format( name=self.name, username=self.username, password=self.password, email=self.email ) def is_authenticated(self): return (hasattr(self.session.session_id) and self.session.session_id is not None) def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id
Implement properties and methods for the User model class to enable the Flask-Login module
Implement properties and methods for the User model class to enable the Flask-Login module
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
from app_factory import db from models.session import Session class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column('name', db.String(50)) username = db.Column('username', db.String(50)) password = db.Column('password', db.String(50)) email = db.Column('email', db.String(128)) session = db.relationship( Session, uselist=False, backref=db.backref('user', order_by=id) ) + def __init__(self, name, username, password, email): + self.name = name + self.username = username + self.password = password + self.email = email + def __repr__(self): return '' '<User(name={name}, username={username}, ' 'password={password}, email={email})>'.format( name=self.name, username=self.username, password=self.password, email=self.email ) + def is_authenticated(self): + return (hasattr(self.session.session_id) and + self.session.session_id is not None) - def __init__(self, name, username, password, email): - self.name = name - self.username = username - self.password = password - self.email = email + def is_active(self): + return True + + def is_anonymous(self): + return False + + def get_id(self): + return self.id +
Implement properties and methods for the User model class to enable the Flask-Login module
## Code Before: from app_factory import db from models.session import Session class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column('name', db.String(50)) username = db.Column('username', db.String(50)) password = db.Column('password', db.String(50)) email = db.Column('email', db.String(128)) session = db.relationship( Session, uselist=False, backref=db.backref('user', order_by=id) ) def __repr__(self): return '' '<User(name={name}, username={username}, ' 'password={password}, email={email})>'.format( name=self.name, username=self.username, password=self.password, email=self.email ) def __init__(self, name, username, password, email): self.name = name self.username = username self.password = password self.email = email ## Instruction: Implement properties and methods for the User model class to enable the Flask-Login module ## Code After: from app_factory import db from models.session import Session class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column('name', db.String(50)) username = db.Column('username', db.String(50)) password = db.Column('password', db.String(50)) email = db.Column('email', db.String(128)) session = db.relationship( Session, uselist=False, backref=db.backref('user', order_by=id) ) def __init__(self, name, username, password, email): self.name = name self.username = username self.password = password self.email = email def __repr__(self): return '' '<User(name={name}, username={username}, ' 'password={password}, email={email})>'.format( name=self.name, username=self.username, password=self.password, email=self.email ) def is_authenticated(self): return (hasattr(self.session.session_id) and self.session.session_id is not None) def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id
// ... existing code ... def __init__(self, name, username, password, email): self.name = name self.username = username self.password = password self.email = email def __repr__(self): // ... modified code ... def is_authenticated(self): return (hasattr(self.session.session_id) and self.session.session_id is not None) def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id // ... rest of the code ...
7b2db239b0862db256722f57241c74d4cc9b42ff
diss/__init__.py
diss/__init__.py
import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(filepath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(filepath).decode(), 'mimetype': magic.from_file(filepath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length)
import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." # Resolve symlinks realpath = os.path.realpath(filepath) if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(realpath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(realpath).decode(), 'mimetype': magic.from_file(realpath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length)
Fix mimetype detection on symlink
Fix mimetype detection on symlink
Python
agpl-3.0
hoh/Billabong,hoh/Billabong
import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." + # Resolve symlinks + realpath = os.path.realpath(filepath) + if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), - 'size': os.path.getsize(filepath), + 'size': os.path.getsize(realpath), 'timestamp': datetime.now(), 'id': id_, 'info': { - 'type': magic.from_file(filepath).decode(), + 'type': magic.from_file(realpath).decode(), - 'mimetype': magic.from_file(filepath, mime=True).decode(), + 'mimetype': magic.from_file(realpath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length)
Fix mimetype detection on symlink
## Code Before: import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(filepath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(filepath).decode(), 'mimetype': magic.from_file(filepath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length) ## Instruction: Fix mimetype detection on symlink ## Code After: import os import hashlib import magic from base64 import b64encode, b64decode from datetime import datetime from .settings import inventory from .encryption import random_key, copy_and_encrypt, decrypt_blob hashing = hashlib.sha256 def add_file(filepath, *, key=None): "Import a file into Dis." # Resolve symlinks realpath = os.path.realpath(filepath) if not os.path.isfile(filepath): raise FileNotFoundError if key is None: key = random_key() file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) id_ = copy_and_encrypt(filepath, key) meta = { 'key': b64encode(key), 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(realpath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(realpath).decode(), 'mimetype': magic.from_file(realpath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } inventory.save_record(meta) return meta def get_content(id_, *, offset=0, length=None): key = b64decode(inventory.get_record(id_)['key']) return decrypt_blob(id_, key, offset=offset, length=length)
... # Resolve symlinks realpath = os.path.realpath(filepath) if not os.path.isfile(filepath): ... 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(realpath), 'timestamp': datetime.now(), ... 'info': { 'type': magic.from_file(realpath).decode(), 'mimetype': magic.from_file(realpath, mime=True).decode(), 'filename': os.path.basename(filepath), ...
e1acfc8a05f1a131dc4b146837e007efa58a2ebf
theano/learning_rates.py
theano/learning_rates.py
""" Classes that simplify learning rate modification. """ import theano import theano.tensor as TT class _LearningRate(object): """ Suplerclass for learning rates. """ def __init__(self, initial_rate): """ Args: initial_rate: Initial value of the learning rate. """ self._rate = initial_rate def get(self, cycle): """ Args: cycle: The symbolic global step. Returns: The learning rate to use for this cycle. """ return self.__rate class Fixed(_LearningRate): """ The simplest type of learning rate. It is just a fixed value. """ pass class ExponentialDecay(_LearningRate): """ A learning rate that decays exponentially with time. """ def __init__(self, decay_rate, decay_steps, *args, **kwargs): """ Args: decay_rate: Number of steps needed to decay by decay_rate. decay_steps: The decay rate. """ super(ExponentialDecay, self).__init__(*args, **kwargs) self.__decay_steps = decay_steps self.__decay_rate = decay_rate def get(self, cycle): rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps)) return TT.cast(rate, theano.config.floatX)
""" Classes that simplify learning rate modification. """ import theano import theano.tensor as TT class _LearningRate(object): """ Suplerclass for learning rates. """ def __init__(self, initial_rate): """ Args: initial_rate: Initial value of the learning rate. """ self._rate = initial_rate def get(self, cycle): """ Args: cycle: The symbolic global step. Returns: The learning rate to use for this cycle. """ return TT.as_tensor_variable(self._rate, name="lr") class Fixed(_LearningRate): """ The simplest type of learning rate. It is just a fixed value. """ pass class ExponentialDecay(_LearningRate): """ A learning rate that decays exponentially with time. """ def __init__(self, decay_rate, decay_steps, *args, **kwargs): """ Args: decay_rate: Number of steps needed to decay by decay_rate. decay_steps: The decay rate. """ super(ExponentialDecay, self).__init__(*args, **kwargs) self.__decay_steps = decay_steps self.__decay_rate = decay_rate def get(self, cycle): rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps)) return TT.cast(rate, theano.config.floatX)
Make fixed learning rates not crash.
Make fixed learning rates not crash. There was a slight bug in this code before, which I fixed.
Python
mit
djpetti/rpinets,djpetti/rpinets
""" Classes that simplify learning rate modification. """ import theano import theano.tensor as TT class _LearningRate(object): """ Suplerclass for learning rates. """ def __init__(self, initial_rate): """ Args: initial_rate: Initial value of the learning rate. """ self._rate = initial_rate def get(self, cycle): """ Args: cycle: The symbolic global step. Returns: The learning rate to use for this cycle. """ - return self.__rate + return TT.as_tensor_variable(self._rate, name="lr") class Fixed(_LearningRate): """ The simplest type of learning rate. It is just a fixed value. """ pass class ExponentialDecay(_LearningRate): """ A learning rate that decays exponentially with time. """ def __init__(self, decay_rate, decay_steps, *args, **kwargs): """ Args: decay_rate: Number of steps needed to decay by decay_rate. decay_steps: The decay rate. """ super(ExponentialDecay, self).__init__(*args, **kwargs) self.__decay_steps = decay_steps self.__decay_rate = decay_rate def get(self, cycle): rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps)) return TT.cast(rate, theano.config.floatX)
Make fixed learning rates not crash.
## Code Before: """ Classes that simplify learning rate modification. """ import theano import theano.tensor as TT class _LearningRate(object): """ Suplerclass for learning rates. """ def __init__(self, initial_rate): """ Args: initial_rate: Initial value of the learning rate. """ self._rate = initial_rate def get(self, cycle): """ Args: cycle: The symbolic global step. Returns: The learning rate to use for this cycle. """ return self.__rate class Fixed(_LearningRate): """ The simplest type of learning rate. It is just a fixed value. """ pass class ExponentialDecay(_LearningRate): """ A learning rate that decays exponentially with time. """ def __init__(self, decay_rate, decay_steps, *args, **kwargs): """ Args: decay_rate: Number of steps needed to decay by decay_rate. decay_steps: The decay rate. """ super(ExponentialDecay, self).__init__(*args, **kwargs) self.__decay_steps = decay_steps self.__decay_rate = decay_rate def get(self, cycle): rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps)) return TT.cast(rate, theano.config.floatX) ## Instruction: Make fixed learning rates not crash. ## Code After: """ Classes that simplify learning rate modification. """ import theano import theano.tensor as TT class _LearningRate(object): """ Suplerclass for learning rates. """ def __init__(self, initial_rate): """ Args: initial_rate: Initial value of the learning rate. """ self._rate = initial_rate def get(self, cycle): """ Args: cycle: The symbolic global step. Returns: The learning rate to use for this cycle. """ return TT.as_tensor_variable(self._rate, name="lr") class Fixed(_LearningRate): """ The simplest type of learning rate. It is just a fixed value. """ pass class ExponentialDecay(_LearningRate): """ A learning rate that decays exponentially with time. """ def __init__(self, decay_rate, decay_steps, *args, **kwargs): """ Args: decay_rate: Number of steps needed to decay by decay_rate. decay_steps: The decay rate. """ super(ExponentialDecay, self).__init__(*args, **kwargs) self.__decay_steps = decay_steps self.__decay_rate = decay_rate def get(self, cycle): rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps)) return TT.cast(rate, theano.config.floatX)
// ... existing code ... The learning rate to use for this cycle. """ return TT.as_tensor_variable(self._rate, name="lr") // ... rest of the code ...
0563882d0d1bfdf4e64a65bcd91e8d6d4ab6ed8f
core/polyaxon/polypod/compiler/lineage/artifacts_collector.py
core/polyaxon/polypod/compiler/lineage/artifacts_collector.py
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name), kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
Fix artifacts name sanitization for root folders
Fix artifacts name sanitization for root folders
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( - name=to_fqn_name(name), + name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
Fix artifacts name sanitization for root folders
## Code Before: import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name), kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, ) ## Instruction: Fix artifacts name sanitization for root folders ## Code After: import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
# ... existing code ... return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, # ... rest of the code ...
0b797d14a609172d4965320aa30eae9e9c1f892e
tests/test_strutils.py
tests/test_strutils.py
from boltons import strutils def test_asciify(): ref = u'Beyoncé' b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' def test_indent(): to_indent = '\nabc\ndef\n\nxyz\n' ref = '\n abc\n def\n\n xyz\n' assert strutils.indent(to_indent, ' ') == ref
import uuid from boltons import strutils def test_asciify(): ref = u'Beyoncé' b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' def test_indent(): to_indent = '\nabc\ndef\n\nxyz\n' ref = '\n abc\n def\n\n xyz\n' assert strutils.indent(to_indent, ' ') == ref def test_is_uuid(): assert strutils.is_uuid(uuid.uuid4()) == True assert strutils.is_uuid(uuid.uuid4(), version=1) == False assert strutils.is_uuid(str(uuid.uuid4())) == True assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False assert strutils.is_uuid(set('garbage')) == False
Add is_uuid unit-tests, including garbage types.
Add is_uuid unit-tests, including garbage types.
Python
bsd-3-clause
zeroSteiner/boltons,doublereedkurt/boltons,markrwilliams/boltons
+ + import uuid from boltons import strutils def test_asciify(): ref = u'Beyoncé' b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' def test_indent(): to_indent = '\nabc\ndef\n\nxyz\n' ref = '\n abc\n def\n\n xyz\n' assert strutils.indent(to_indent, ' ') == ref + + def test_is_uuid(): + assert strutils.is_uuid(uuid.uuid4()) == True + assert strutils.is_uuid(uuid.uuid4(), version=1) == False + assert strutils.is_uuid(str(uuid.uuid4())) == True + assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False + assert strutils.is_uuid(set('garbage')) == False +
Add is_uuid unit-tests, including garbage types.
## Code Before: from boltons import strutils def test_asciify(): ref = u'Beyoncé' b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' def test_indent(): to_indent = '\nabc\ndef\n\nxyz\n' ref = '\n abc\n def\n\n xyz\n' assert strutils.indent(to_indent, ' ') == ref ## Instruction: Add is_uuid unit-tests, including garbage types. ## Code After: import uuid from boltons import strutils def test_asciify(): ref = u'Beyoncé' b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' def test_indent(): to_indent = '\nabc\ndef\n\nxyz\n' ref = '\n abc\n def\n\n xyz\n' assert strutils.indent(to_indent, ' ') == ref def test_is_uuid(): assert strutils.is_uuid(uuid.uuid4()) == True assert strutils.is_uuid(uuid.uuid4(), version=1) == False assert strutils.is_uuid(str(uuid.uuid4())) == True assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False assert strutils.is_uuid(set('garbage')) == False
// ... existing code ... import uuid // ... modified code ... assert strutils.indent(to_indent, ' ') == ref def test_is_uuid(): assert strutils.is_uuid(uuid.uuid4()) == True assert strutils.is_uuid(uuid.uuid4(), version=1) == False assert strutils.is_uuid(str(uuid.uuid4())) == True assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False assert strutils.is_uuid(set('garbage')) == False // ... rest of the code ...
b5bfa67c87c7043f521cde32e7212c0fffdbacd9
Solutions/problem67.py
Solutions/problem67.py
def importTri(): t = [] f = open("problem67.txt") for line in f: t.append(map(int, line.split(" "))) return t def getMax(lm, cur): l = len(cur) - 1 maxL = [lm[0] + cur[0]] i = 1 while True: if i == l: maxL.append(lm[i - 1] + cur[i]) break maxL.append(max((lm[i - 1]), lm[i]) + cur[i]) i += 1 return maxL def getAns(): t = importTri() lmax = t[0] for i in range(1, len(t)): lmax = getMax(lmax, t[i]) print(max(x for x in lmax)) getAns()
def import_triangle(): with open('problem67.txt') as f: # Split each line by spaces and convert to integers return [list(map(int, line.split(' '))) for line in f] # The max of this row is the maximum sum up to its parent items plus the value # in this row. But note that the first and last items in this row only have one # parent each, so it can make the code a little funky to write. def get_max(last_maxes, cur): current_maxes = [cur[0] + last_maxes[0]] for idx, lm in enumerate(last_maxes): # Our left child was the right child of a previous element; get max max_for_left_child = cur[idx] + lm current_maxes[idx] = max(current_maxes[idx], max_for_left_child) # Right child hasn't been seen yet, just append it current_maxes.append(lm + cur[idx + 1]) return current_maxes def solve(): triangle = import_triangle() max_for_last_row = triangle[0] for current_row in triangle[1:]: max_for_last_row = get_max(max_for_last_row, current_row) print('Answer: {}'.format(max(max_for_last_row))) if __name__ == '__main__': solve()
Update problem 67 to be legible
Update problem 67 to be legible
Python
mit
WalrusCow/euler
- def importTri(): + def import_triangle(): + with open('problem67.txt') as f: + # Split each line by spaces and convert to integers + return [list(map(int, line.split(' '))) for line in f] - t = [] - f = open("problem67.txt") - for line in f: - t.append(map(int, line.split(" "))) - return t + # The max of this row is the maximum sum up to its parent items plus the value + # in this row. But note that the first and last items in this row only have one + # parent each, so it can make the code a little funky to write. - def getMax(lm, cur): + def get_max(last_maxes, cur): + current_maxes = [cur[0] + last_maxes[0]] + for idx, lm in enumerate(last_maxes): + # Our left child was the right child of a previous element; get max + max_for_left_child = cur[idx] + lm + current_maxes[idx] = max(current_maxes[idx], max_for_left_child) + # Right child hasn't been seen yet, just append it + current_maxes.append(lm + cur[idx + 1]) + return current_maxes - l = len(cur) - 1 - maxL = [lm[0] + cur[0]] - i = 1 - while True: - if i == l: - maxL.append(lm[i - 1] + cur[i]) - break - maxL.append(max((lm[i - 1]), lm[i]) + cur[i]) - i += 1 - return maxL - def getAns(): - t = importTri() - lmax = t[0] - for i in range(1, len(t)): - lmax = getMax(lmax, t[i]) - print(max(x for x in lmax)) + def solve(): + triangle = import_triangle() + max_for_last_row = triangle[0] + for current_row in triangle[1:]: + max_for_last_row = get_max(max_for_last_row, current_row) + print('Answer: {}'.format(max(max_for_last_row))) - getAns() + if __name__ == '__main__': + solve()
Update problem 67 to be legible
## Code Before: def importTri(): t = [] f = open("problem67.txt") for line in f: t.append(map(int, line.split(" "))) return t def getMax(lm, cur): l = len(cur) - 1 maxL = [lm[0] + cur[0]] i = 1 while True: if i == l: maxL.append(lm[i - 1] + cur[i]) break maxL.append(max((lm[i - 1]), lm[i]) + cur[i]) i += 1 return maxL def getAns(): t = importTri() lmax = t[0] for i in range(1, len(t)): lmax = getMax(lmax, t[i]) print(max(x for x in lmax)) getAns() ## Instruction: Update problem 67 to be legible ## Code After: def import_triangle(): with open('problem67.txt') as f: # Split each line by spaces and convert to integers return [list(map(int, line.split(' '))) for line in f] # The max of this row is the maximum sum up to its parent items plus the value # in this row. But note that the first and last items in this row only have one # parent each, so it can make the code a little funky to write. def get_max(last_maxes, cur): current_maxes = [cur[0] + last_maxes[0]] for idx, lm in enumerate(last_maxes): # Our left child was the right child of a previous element; get max max_for_left_child = cur[idx] + lm current_maxes[idx] = max(current_maxes[idx], max_for_left_child) # Right child hasn't been seen yet, just append it current_maxes.append(lm + cur[idx + 1]) return current_maxes def solve(): triangle = import_triangle() max_for_last_row = triangle[0] for current_row in triangle[1:]: max_for_last_row = get_max(max_for_last_row, current_row) print('Answer: {}'.format(max(max_for_last_row))) if __name__ == '__main__': solve()
// ... existing code ... def import_triangle(): with open('problem67.txt') as f: # Split each line by spaces and convert to integers return [list(map(int, line.split(' '))) for line in f] # The max of this row is the maximum sum up to its parent items plus the value # in this row. But note that the first and last items in this row only have one # parent each, so it can make the code a little funky to write. def get_max(last_maxes, cur): current_maxes = [cur[0] + last_maxes[0]] for idx, lm in enumerate(last_maxes): # Our left child was the right child of a previous element; get max max_for_left_child = cur[idx] + lm current_maxes[idx] = max(current_maxes[idx], max_for_left_child) # Right child hasn't been seen yet, just append it current_maxes.append(lm + cur[idx + 1]) return current_maxes def solve(): triangle = import_triangle() max_for_last_row = triangle[0] for current_row in triangle[1:]: max_for_last_row = get_max(max_for_last_row, current_row) print('Answer: {}'.format(max(max_for_last_row))) if __name__ == '__main__': solve() // ... rest of the code ...
dc47a724525186fe99d79e62447efc3dbc9d95b0
app/groups/utils.py
app/groups/utils.py
from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site def send_group_email(request, to_email, subject, email_text_template, email_html_template): """Sends a email to a group of people using a standard layout""" # Mail the admins to inform them of a new request ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), to_email) msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html') msg.send(fail_silently=True)
from django.conf import settings from django.core.mail import EmailMultiAlternatives, get_connection from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site def send_group_email(request, to_email, subject, email_text_template, email_html_template): """Sends a email to a group of people using a standard layout""" # Mail the admins to inform them of a new request ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) messages = [generate_mail(ctx, email_text_template, email_html_template, to, subject) for to in to_email] connection = get_connection(fail_silently=True) connection.send_messages(messages) def generate_mail(context, email_text_template, email_html_template, to, subject): msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(context), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), [to]) msg.attach_alternative(get_template(email_html_template).render(context), 'text/html') return msg
Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google
Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google
Python
bsd-3-clause
nikdoof/test-auth
from django.conf import settings - from django.core.mail import EmailMultiAlternatives + from django.core.mail import EmailMultiAlternatives, get_connection from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site def send_group_email(request, to_email, subject, email_text_template, email_html_template): """Sends a email to a group of people using a standard layout""" # Mail the admins to inform them of a new request ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) + + messages = [generate_mail(ctx, email_text_template, email_html_template, to, subject) for to in to_email] + connection = get_connection(fail_silently=True) + connection.send_messages(messages) + + def generate_mail(context, email_text_template, email_html_template, to, subject): - msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), to_email) + msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(context), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), [to]) - msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html') + msg.attach_alternative(get_template(email_html_template).render(context), 'text/html') - msg.send(fail_silently=True) + return msg
Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google
## Code Before: from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site def send_group_email(request, to_email, subject, email_text_template, email_html_template): """Sends a email to a group of people using a standard layout""" # Mail the admins to inform them of a new request ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), to_email) msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html') msg.send(fail_silently=True) ## Instruction: Send individual mails, to avoid showing the whole to list, BCC and spamholing from Google ## Code After: from django.conf import settings from django.core.mail import EmailMultiAlternatives, get_connection from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site def send_group_email(request, to_email, subject, email_text_template, email_html_template): """Sends a email to a group of people using a standard layout""" # Mail the admins to inform them of a new request ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) messages = [generate_mail(ctx, email_text_template, email_html_template, to, subject) for to in to_email] connection = get_connection(fail_silently=True) connection.send_messages(messages) def generate_mail(context, email_text_template, email_html_template, to, subject): msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(context), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), [to]) msg.attach_alternative(get_template(email_html_template).render(context), 'text/html') return msg
# ... existing code ... from django.conf import settings from django.core.mail import EmailMultiAlternatives, get_connection from django.template.loader import get_template # ... modified code ... ctx = Context({'request': request, 'domain': Site.objects.get_current().domain}) messages = [generate_mail(ctx, email_text_template, email_html_template, to, subject) for to in to_email] connection = get_connection(fail_silently=True) connection.send_messages(messages) def generate_mail(context, email_text_template, email_html_template, to, subject): msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(context), getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]'), [to]) msg.attach_alternative(get_template(email_html_template).render(context), 'text/html') return msg # ... rest of the code ...
ec8d7b035617f9239a0a52be346d8611cf77cb6f
integration-tests/features/src/utils.py
integration-tests/features/src/utils.py
"""Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')]
"""Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
Add few oc wrappers for future resiliency testing
Add few oc wrappers for future resiliency testing Not used anywhere yet.
Python
apache-2.0
jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common
"""Unsorted utility functions used in integration tests.""" import requests + import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] + + def oc_login(url, username, password, tls_verify=True): + """Wrapper around `oc login`. + + :param url: str, OpenShift URL + :param username: str, username + :param password: str, password + :param tls_verify: bool, verify server's certificate?; default: True + :return: None on success, raises `subprocess.CalledProcessError` on error + """ + command = ['oc', 'login', url, '--username', username, '--password', password] + if not tls_verify: + command.extend(['--insecure-skip-tls-verify=true']) + + try: + subprocess.check_call(command) + except subprocess.CalledProcessError as e: + # replace password with '***' so somebody will not accidentally leak it in CI logs + e.cmd = [x if x != password else '***' for x in e.cmd] + raise e + + + def oc_delete_pods(selector, namespace=None): + """Wrapper around `oc delete`. + + Selector determines which pods will be deleted. + More on selectors: + https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + + Note k8s/OpenShift will immediately restart deleted pods, + to match desired number of replicas for given deployment. + + The expectation is that the user is already logged in + and has permissions to delete pods. + + Example usage: + oc_delete_pods('service=bayesian-pgbouncer' + + :param selector: str, selector identifying pods that will be deleted + :param namespace: str, namespace in which `oc delete` command should be executed, + default: currently selected namespace + :return: None on success, raises `subprocess.CalledProcessError` on error + """ + command = ['oc', 'delete', 'pods', '--selector=', selector] + if namespace: + command.extend(['--namespace', namespace]) + + subprocess.check_call(command) +
Add few oc wrappers for future resiliency testing
## Code Before: """Unsorted utility functions used in integration tests.""" import requests def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] ## Instruction: Add few oc wrappers for future resiliency testing ## Code After: """Unsorted utility functions used in integration tests.""" import requests import subprocess def download_file_from_url(url): """Download file from the given URL and do basic check of response.""" assert url response = requests.get(url) assert response.status_code == 200 assert response.text is not None return response.text def split_comma_separated_list(l): """Split the list into elements separated by commas.""" return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command)
... import requests import subprocess ... return [i.strip() for i in l.split(',')] def oc_login(url, username, password, tls_verify=True): """Wrapper around `oc login`. :param url: str, OpenShift URL :param username: str, username :param password: str, password :param tls_verify: bool, verify server's certificate?; default: True :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'login', url, '--username', username, '--password', password] if not tls_verify: command.extend(['--insecure-skip-tls-verify=true']) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: # replace password with '***' so somebody will not accidentally leak it in CI logs e.cmd = [x if x != password else '***' for x in e.cmd] raise e def oc_delete_pods(selector, namespace=None): """Wrapper around `oc delete`. Selector determines which pods will be deleted. More on selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Note k8s/OpenShift will immediately restart deleted pods, to match desired number of replicas for given deployment. The expectation is that the user is already logged in and has permissions to delete pods. Example usage: oc_delete_pods('service=bayesian-pgbouncer' :param selector: str, selector identifying pods that will be deleted :param namespace: str, namespace in which `oc delete` command should be executed, default: currently selected namespace :return: None on success, raises `subprocess.CalledProcessError` on error """ command = ['oc', 'delete', 'pods', '--selector=', selector] if namespace: command.extend(['--namespace', namespace]) subprocess.check_call(command) ...
94475ea2ed73e57870e8947a5b3ed474a70447e4
src/sentry/signals.py
src/sentry/signals.py
from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>> pass """ def wrapped(func): return super(BetterSignal, self).connect(func, **kwargs) if receiver is None: return wrapped return wraps(receiver)(wrapped(receiver)) regression_signal = BetterSignal(providing_args=["instance"]) buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) event_received = BetterSignal(providing_args=["ip"]) pending_delete = BetterSignal(providing_args=["instance"]) event_processed = BetterSignal(providing_args=['project', 'group', 'event']) # Organization Onboarding Signals project_created = BetterSignal(providing_args=["project", "user"]) first_event_pending = BetterSignal(providing_args=["project", "user"]) first_event_received = BetterSignal(providing_args=["project", "group"]) member_invited = BetterSignal(providing_args=["member", "user"]) member_joined = BetterSignal(providing_args=["member"]) issue_tracker_used = BetterSignal(providing_args=["plugin", "project", "user"]) plugin_enabled = BetterSignal(providing_args=["plugin", "project", "user"])
from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>> pass """ def wrapped(func): return super(BetterSignal, self).connect(func, **kwargs) if receiver is None: return wrapped return wraps(receiver)(wrapped(receiver)) regression_signal = BetterSignal(providing_args=["instance"]) buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) event_received = BetterSignal(providing_args=["ip", "auth", "data"]) pending_delete = BetterSignal(providing_args=["instance"]) event_processed = BetterSignal(providing_args=['project', 'group', 'event']) # Organization Onboarding Signals project_created = BetterSignal(providing_args=["project", "user"]) first_event_pending = BetterSignal(providing_args=["project", "user"]) first_event_received = BetterSignal(providing_args=["project", "group"]) member_invited = BetterSignal(providing_args=["member", "user"]) member_joined = BetterSignal(providing_args=["member"]) issue_tracker_used = BetterSignal(providing_args=["plugin", "project", "user"]) plugin_enabled = BetterSignal(providing_args=["plugin", "project", "user"])
Add missing args to event_received
Add missing args to event_received
Python
bsd-3-clause
jean/sentry,mitsuhiko/sentry,ifduyue/sentry,zenefits/sentry,JamesMura/sentry,mvaled/sentry,beeftornado/sentry,fotinakis/sentry,JamesMura/sentry,jean/sentry,mitsuhiko/sentry,gencer/sentry,jean/sentry,zenefits/sentry,BuildingLink/sentry,JackDanger/sentry,looker/sentry,looker/sentry,zenefits/sentry,beeftornado/sentry,mvaled/sentry,ifduyue/sentry,zenefits/sentry,jean/sentry,looker/sentry,BuildingLink/sentry,gencer/sentry,fotinakis/sentry,BuildingLink/sentry,JamesMura/sentry,JamesMura/sentry,alexm92/sentry,alexm92/sentry,mvaled/sentry,fotinakis/sentry,beeftornado/sentry,gencer/sentry,gencer/sentry,JackDanger/sentry,mvaled/sentry,ifduyue/sentry,fotinakis/sentry,JackDanger/sentry,BuildingLink/sentry,jean/sentry,BuildingLink/sentry,JamesMura/sentry,mvaled/sentry,ifduyue/sentry,mvaled/sentry,ifduyue/sentry,looker/sentry,alexm92/sentry,looker/sentry,zenefits/sentry,gencer/sentry
from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>> pass """ def wrapped(func): return super(BetterSignal, self).connect(func, **kwargs) if receiver is None: return wrapped return wraps(receiver)(wrapped(receiver)) regression_signal = BetterSignal(providing_args=["instance"]) buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) - event_received = BetterSignal(providing_args=["ip"]) + event_received = BetterSignal(providing_args=["ip", "auth", "data"]) pending_delete = BetterSignal(providing_args=["instance"]) event_processed = BetterSignal(providing_args=['project', 'group', 'event']) # Organization Onboarding Signals project_created = BetterSignal(providing_args=["project", "user"]) first_event_pending = BetterSignal(providing_args=["project", "user"]) first_event_received = BetterSignal(providing_args=["project", "group"]) member_invited = BetterSignal(providing_args=["member", "user"]) member_joined = BetterSignal(providing_args=["member"]) issue_tracker_used = BetterSignal(providing_args=["plugin", "project", "user"]) plugin_enabled = BetterSignal(providing_args=["plugin", "project", "user"])
Add missing args to event_received
## Code Before: from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>> pass """ def wrapped(func): return super(BetterSignal, self).connect(func, **kwargs) if receiver is None: return wrapped return wraps(receiver)(wrapped(receiver)) regression_signal = BetterSignal(providing_args=["instance"]) buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) event_received = BetterSignal(providing_args=["ip"]) pending_delete = BetterSignal(providing_args=["instance"]) event_processed = BetterSignal(providing_args=['project', 'group', 'event']) # Organization Onboarding Signals project_created = BetterSignal(providing_args=["project", "user"]) first_event_pending = BetterSignal(providing_args=["project", "user"]) first_event_received = BetterSignal(providing_args=["project", "group"]) member_invited = BetterSignal(providing_args=["member", "user"]) member_joined = BetterSignal(providing_args=["member"]) issue_tracker_used = BetterSignal(providing_args=["plugin", "project", "user"]) plugin_enabled = BetterSignal(providing_args=["plugin", "project", "user"]) ## Instruction: Add missing args to event_received ## Code After: from __future__ import absolute_import from functools import wraps from django.dispatch import Signal class BetterSignal(Signal): def connect(self, receiver=None, **kwargs): """ Support decorator syntax: >>> @signal.connect(sender=type) >>> def my_receiver(**kwargs): >>> pass """ def wrapped(func): return super(BetterSignal, self).connect(func, **kwargs) if receiver is None: return wrapped return wraps(receiver)(wrapped(receiver)) regression_signal = BetterSignal(providing_args=["instance"]) buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) event_received = BetterSignal(providing_args=["ip", "auth", "data"]) pending_delete = BetterSignal(providing_args=["instance"]) event_processed = BetterSignal(providing_args=['project', 'group', 'event']) # Organization Onboarding Signals project_created = BetterSignal(providing_args=["project", "user"]) first_event_pending = BetterSignal(providing_args=["project", "user"]) first_event_received = BetterSignal(providing_args=["project", "group"]) member_invited = BetterSignal(providing_args=["member", "user"]) member_joined = BetterSignal(providing_args=["member"]) issue_tracker_used = BetterSignal(providing_args=["plugin", "project", "user"]) plugin_enabled = BetterSignal(providing_args=["plugin", "project", "user"])
# ... existing code ... buffer_incr_complete = BetterSignal(providing_args=["model", "columns", "extra", "result"]) event_received = BetterSignal(providing_args=["ip", "auth", "data"]) pending_delete = BetterSignal(providing_args=["instance"]) # ... rest of the code ...
6eeecb5e36e5551ba3a3c35a9c7f52393d2f9d14
src/puzzle/problems/problem.py
src/puzzle/problems/problem.py
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
Add simple helper properties to Problem.
Add simple helper properties to Problem.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] + + @property + def kind(self): + return str(type(self)).strip("'<>").split('.').pop() + + @property + def solution(self): + return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
Add simple helper properties to Problem.
## Code Before: from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError() ## Instruction: Add simple helper properties to Problem. ## Code After: from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
... self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() ...
bd70ef56d95958b8f105bdff31b675d66c40bca8
serfnode/handler/supervisor.py
serfnode/handler/supervisor.py
import os import subprocess import docker_utils import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs')) def supervisor_install(block, **kwargs): """Update supervisor with `block` config. - `block` is the name to a .conf template file (in directory `/programs`) - `kwargs` are the key/values to use in the template """ conf_filename = '{}.conf'.format(kwargs['target']) template = env.get_template(block) kwargs.update({ 'DOCKER': docker_utils.DOCKER, 'DOCKER_SOCKET': docker_utils.DOCKER_SOCKET, 'DOCKER_RUN': docker_utils.DOCKER_RUN}) conf = template.render(kwargs) with open(os.path.join( '/etc/supervisor/conf.d', conf_filename), 'w') as f: f.write(conf) def supervisor_exec(*args): return subprocess.check_output( ['supervisorctl'] + list(args)) def supervisor_update(): supervisor_exec('reread') supervisor_exec('update') def start(block, **kwargs): supervisor_install(block, **kwargs) supervisor_update() supervisor_exec('start', '{}:*'.format(kwargs['target'])) def stop(block): supervisor_exec('stop', '{}:*'.format(block))
import os import subprocess import docker_utils import docker import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs')) def supervisor_install(block, **kwargs): """Update supervisor with `block` config. - `block` is the name to a .conf template file (in directory `/programs`) - `kwargs` are the key/values to use in the template """ conf_filename = '{}.conf'.format(kwargs['target']) template = env.get_template(block) kwargs.update({ 'DOCKER': docker_utils.DOCKER, 'DOCKER_SOCKET': docker_utils.DOCKER_SOCKET, 'DOCKER_RUN': docker_utils.DOCKER_RUN}) conf = template.render(kwargs) with open(os.path.join( '/etc/supervisor/conf.d', conf_filename), 'w') as f: f.write(conf) def supervisor_exec(*args): return subprocess.check_output( ['supervisorctl'] + list(args)) def supervisor_update(): supervisor_exec('reread') supervisor_exec('update') def start(block, **kwargs): supervisor_install(block, **kwargs) supervisor_update() supervisor_exec('start', '{}:*'.format(kwargs['target'])) def start_docker(target, name, cmdline): start('app.conf', target=target, ARGS='--cidfile=/app --name={} {}'.format(name, cmdline), NAME=name) def stop(block): supervisor_exec('stop', '{}:*'.format(block))
Add convenience function to start docker
Add convenience function to start docker Mainly to be used from supervisor.
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
import os import subprocess import docker_utils + import docker import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs')) def supervisor_install(block, **kwargs): """Update supervisor with `block` config. - `block` is the name to a .conf template file (in directory `/programs`) - `kwargs` are the key/values to use in the template """ conf_filename = '{}.conf'.format(kwargs['target']) template = env.get_template(block) kwargs.update({ 'DOCKER': docker_utils.DOCKER, 'DOCKER_SOCKET': docker_utils.DOCKER_SOCKET, 'DOCKER_RUN': docker_utils.DOCKER_RUN}) conf = template.render(kwargs) with open(os.path.join( '/etc/supervisor/conf.d', conf_filename), 'w') as f: f.write(conf) def supervisor_exec(*args): return subprocess.check_output( ['supervisorctl'] + list(args)) def supervisor_update(): supervisor_exec('reread') supervisor_exec('update') def start(block, **kwargs): supervisor_install(block, **kwargs) supervisor_update() supervisor_exec('start', '{}:*'.format(kwargs['target'])) + def start_docker(target, name, cmdline): + start('app.conf', target=target, + ARGS='--cidfile=/app --name={} {}'.format(name, cmdline), + NAME=name) + + def stop(block): supervisor_exec('stop', '{}:*'.format(block)) +
Add convenience function to start docker
## Code Before: import os import subprocess import docker_utils import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs')) def supervisor_install(block, **kwargs): """Update supervisor with `block` config. - `block` is the name to a .conf template file (in directory `/programs`) - `kwargs` are the key/values to use in the template """ conf_filename = '{}.conf'.format(kwargs['target']) template = env.get_template(block) kwargs.update({ 'DOCKER': docker_utils.DOCKER, 'DOCKER_SOCKET': docker_utils.DOCKER_SOCKET, 'DOCKER_RUN': docker_utils.DOCKER_RUN}) conf = template.render(kwargs) with open(os.path.join( '/etc/supervisor/conf.d', conf_filename), 'w') as f: f.write(conf) def supervisor_exec(*args): return subprocess.check_output( ['supervisorctl'] + list(args)) def supervisor_update(): supervisor_exec('reread') supervisor_exec('update') def start(block, **kwargs): supervisor_install(block, **kwargs) supervisor_update() supervisor_exec('start', '{}:*'.format(kwargs['target'])) def stop(block): supervisor_exec('stop', '{}:*'.format(block)) ## Instruction: Add convenience function to start docker ## Code After: import os import subprocess import docker_utils import docker import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('/programs')) def supervisor_install(block, **kwargs): """Update supervisor with `block` config. - `block` is the name to a .conf template file (in directory `/programs`) - `kwargs` are the key/values to use in the template """ conf_filename = '{}.conf'.format(kwargs['target']) template = env.get_template(block) kwargs.update({ 'DOCKER': docker_utils.DOCKER, 'DOCKER_SOCKET': docker_utils.DOCKER_SOCKET, 'DOCKER_RUN': docker_utils.DOCKER_RUN}) conf = template.render(kwargs) with open(os.path.join( '/etc/supervisor/conf.d', conf_filename), 'w') as f: f.write(conf) def supervisor_exec(*args): return subprocess.check_output( ['supervisorctl'] + list(args)) def supervisor_update(): supervisor_exec('reread') supervisor_exec('update') def start(block, **kwargs): supervisor_install(block, **kwargs) supervisor_update() supervisor_exec('start', '{}:*'.format(kwargs['target'])) def start_docker(target, name, cmdline): start('app.conf', target=target, ARGS='--cidfile=/app --name={} {}'.format(name, cmdline), NAME=name) def stop(block): supervisor_exec('stop', '{}:*'.format(block))
... import docker_utils import docker import jinja2 ... def start_docker(target, name, cmdline): start('app.conf', target=target, ARGS='--cidfile=/app --name={} {}'.format(name, cmdline), NAME=name) def stop(block): ... supervisor_exec('stop', '{}:*'.format(block)) ...
2c2deea36a7e040244152a345eb672e62c519c76
pulse_actions/publisher.py
pulse_actions/publisher.py
import os import sys from pulse_actions.authentication import (get_user_and_password, AuthenticationError) from mozillapulse.publishers import GenericPublisher from mozillapulse.config import PulseConfiguration from mozillapulse.messages.base import GenericMessage class ExperimentalPublisher(GenericPublisher): def __init__(self, **kwargs): super(ExperimentalPublisher, self).__init__( PulseConfiguration(**kwargs), 'exchange/adusca/experiment', **kwargs) class MessageHandler: def __init__(self): """Create Publisher.""" try: user, password = get_user_and_password() except AuthenticationError as e: print(e.message) sys.exit(1) self.publisher = ExperimentalPublisher(user=user, password=password) def publish_message(self, data, routing_key): """Publish a message to exchange/adusca/experiment.""" msg = GenericMessage() msg.routing_parts = routing_key.split('.') for key, value in data.iteritems(): msg.set_data(key, value) self.publisher.publish(msg)
import os import sys from pulse_actions.authentication import ( get_user_and_password, AuthenticationError ) from mozillapulse.publishers import GenericPublisher from mozillapulse.config import PulseConfiguration from mozillapulse.messages.base import GenericMessage class ExperimentalPublisher(GenericPublisher): def __init__(self, **kwargs): super(ExperimentalPublisher, self).__init__( PulseConfiguration(**kwargs), 'exchange/adusca/experiment', **kwargs) class MessageHandler: def __init__(self): """Create Publisher.""" try: user, password = get_user_and_password() except AuthenticationError as e: print(e.message) sys.exit(1) self.publisher = ExperimentalPublisher(user=user, password=password) def publish_message(self, data, routing_key): """Publish a message to exchange/adusca/experiment.""" msg = GenericMessage() msg.routing_parts = routing_key.split('.') for key, value in data.iteritems(): msg.set_data(key, value) try: self.publisher.publish(msg) except Exception as e: print('ERROR: We failed to post a pulse message with what we did') print(e.message)
Handle failing to publish to pulse
Handle failing to publish to pulse
Python
mpl-2.0
armenzg/pulse_actions,mozilla/pulse_actions,adusca/pulse_actions
import os import sys - from pulse_actions.authentication import (get_user_and_password, + from pulse_actions.authentication import ( + get_user_and_password, - AuthenticationError) + AuthenticationError + ) from mozillapulse.publishers import GenericPublisher from mozillapulse.config import PulseConfiguration from mozillapulse.messages.base import GenericMessage class ExperimentalPublisher(GenericPublisher): def __init__(self, **kwargs): super(ExperimentalPublisher, self).__init__( PulseConfiguration(**kwargs), 'exchange/adusca/experiment', **kwargs) class MessageHandler: def __init__(self): """Create Publisher.""" try: user, password = get_user_and_password() except AuthenticationError as e: print(e.message) sys.exit(1) + self.publisher = ExperimentalPublisher(user=user, password=password) def publish_message(self, data, routing_key): """Publish a message to exchange/adusca/experiment.""" msg = GenericMessage() msg.routing_parts = routing_key.split('.') for key, value in data.iteritems(): msg.set_data(key, value) + try: - self.publisher.publish(msg) + self.publisher.publish(msg) + except Exception as e: + print('ERROR: We failed to post a pulse message with what we did') + print(e.message)
Handle failing to publish to pulse
## Code Before: import os import sys from pulse_actions.authentication import (get_user_and_password, AuthenticationError) from mozillapulse.publishers import GenericPublisher from mozillapulse.config import PulseConfiguration from mozillapulse.messages.base import GenericMessage class ExperimentalPublisher(GenericPublisher): def __init__(self, **kwargs): super(ExperimentalPublisher, self).__init__( PulseConfiguration(**kwargs), 'exchange/adusca/experiment', **kwargs) class MessageHandler: def __init__(self): """Create Publisher.""" try: user, password = get_user_and_password() except AuthenticationError as e: print(e.message) sys.exit(1) self.publisher = ExperimentalPublisher(user=user, password=password) def publish_message(self, data, routing_key): """Publish a message to exchange/adusca/experiment.""" msg = GenericMessage() msg.routing_parts = routing_key.split('.') for key, value in data.iteritems(): msg.set_data(key, value) self.publisher.publish(msg) ## Instruction: Handle failing to publish to pulse ## Code After: import os import sys from pulse_actions.authentication import ( get_user_and_password, AuthenticationError ) from mozillapulse.publishers import GenericPublisher from mozillapulse.config import PulseConfiguration from mozillapulse.messages.base import GenericMessage class ExperimentalPublisher(GenericPublisher): def __init__(self, **kwargs): super(ExperimentalPublisher, self).__init__( PulseConfiguration(**kwargs), 'exchange/adusca/experiment', **kwargs) class MessageHandler: def __init__(self): """Create Publisher.""" try: user, password = get_user_and_password() except AuthenticationError as e: print(e.message) sys.exit(1) self.publisher = ExperimentalPublisher(user=user, password=password) def publish_message(self, data, routing_key): """Publish a message to exchange/adusca/experiment.""" msg = GenericMessage() msg.routing_parts = routing_key.split('.') for key, value in data.iteritems(): msg.set_data(key, value) try: self.publisher.publish(msg) except Exception as e: print('ERROR: We failed to post a pulse message with what we did') print(e.message)
... from pulse_actions.authentication import ( get_user_and_password, AuthenticationError ) ... sys.exit(1) self.publisher = ExperimentalPublisher(user=user, password=password) ... msg.set_data(key, value) try: self.publisher.publish(msg) except Exception as e: print('ERROR: We failed to post a pulse message with what we did') print(e.message) ...
56f7c35722b4d90e04bf2da3d7d72ef0bfd52602
tests/test_decorators.py
tests/test_decorators.py
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 @pytest.mark.xfail def test_chain_arg_access(): @decorator def decor(call): return call.x + call() @decor @decor def func(x): return x assert func(2) == 6
Add a test on failed arg introspection in chained decorators
Add a test on failed arg introspection in chained decorators This is a consequence of not preserving function signature. So this could be fixed by preserving signature or by some workaround.
Python
bsd-3-clause
musicpax/funcy,ma-ric/funcy,Suor/funcy
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 + + @pytest.mark.xfail + def test_chain_arg_access(): + @decorator + def decor(call): + return call.x + call() + + @decor + @decor + def func(x): + return x + + assert func(2) == 6 +
Add a test on failed arg introspection in chained decorators
## Code Before: import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 ## Instruction: Add a test on failed arg introspection in chained decorators ## Code After: import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 @pytest.mark.xfail def test_chain_arg_access(): @decorator def decor(call): return call.x + call() @decor @decor def func(x): return x assert func(2) == 6
... assert inc(A.ten_static)() == 11 @pytest.mark.xfail def test_chain_arg_access(): @decorator def decor(call): return call.x + call() @decor @decor def func(x): return x assert func(2) == 6 ...
6c3c379d414a0c9bfde81ff8daa0e1d40aa7a658
setup.py
setup.py
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'traits', ] )
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'argparse', 'traits', ] )
Add argparse to install_requires for Python 2.6
Add argparse to install_requires for Python 2.6
Python
bsd-3-clause
tkf/traitscli,tkf/traitscli
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ + 'argparse', 'traits', ] )
Add argparse to install_requires for Python 2.6
## Code Before: from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'traits', ] ) ## Instruction: Add argparse to install_requires for Python 2.6 ## Code After: from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='[email protected]', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitscli - CLI generator based on class traits', long_description=traitscli.__doc__, keywords='CLI, traits', classifiers=[ "Development Status :: 3 - Alpha", # see: http://pypi.python.org/pypi?%3Aaction=list_classifiers ], install_requires=[ 'argparse', 'traits', ] )
// ... existing code ... install_requires=[ 'argparse', 'traits', // ... rest of the code ...
214b74d4cf3902456ed274f756f4827f18c0c988
logster/server.py
logster/server.py
import os from tornado.ioloop import IOLoop from tornado.web import Application from tornado.httpserver import HTTPServer from . import handlers class LogsterApplication(Application): handlers = [ (r'/', handlers.IndexHandler), ] settings = { 'template_path': os.path.join( os.path.dirname(__file__), '../templates') } def __init__(self): super(LogsterApplication, self).__init__( handlers=self.handlers, **self.settings ) def run_server(): app = LogsterApplication() server = HTTPServer(app) server.listen(8888) IOLoop.current().start()
import os from tornado.ioloop import IOLoop from tornado.web import Application from tornado.httpserver import HTTPServer from . import handlers from .conf import config class LogsterApplication(Application): handlers = [ (r'/', handlers.IndexHandler), ] settings = { 'template_path': os.path.join( os.path.dirname(__file__), '../templates') } def __init__(self): super(LogsterApplication, self).__init__( handlers=self.handlers, **self.settings ) def run_server(): app = LogsterApplication() server = HTTPServer(app) server.listen(config['app']['port']) IOLoop.current().start()
Use post value from config
Use post value from config
Python
mit
irvind/logster,irvind/logster,irvind/logster
import os from tornado.ioloop import IOLoop from tornado.web import Application from tornado.httpserver import HTTPServer from . import handlers + from .conf import config class LogsterApplication(Application): handlers = [ (r'/', handlers.IndexHandler), ] settings = { 'template_path': os.path.join( os.path.dirname(__file__), '../templates') } def __init__(self): super(LogsterApplication, self).__init__( handlers=self.handlers, **self.settings ) def run_server(): app = LogsterApplication() server = HTTPServer(app) - server.listen(8888) + server.listen(config['app']['port']) IOLoop.current().start()
Use post value from config
## Code Before: import os from tornado.ioloop import IOLoop from tornado.web import Application from tornado.httpserver import HTTPServer from . import handlers class LogsterApplication(Application): handlers = [ (r'/', handlers.IndexHandler), ] settings = { 'template_path': os.path.join( os.path.dirname(__file__), '../templates') } def __init__(self): super(LogsterApplication, self).__init__( handlers=self.handlers, **self.settings ) def run_server(): app = LogsterApplication() server = HTTPServer(app) server.listen(8888) IOLoop.current().start() ## Instruction: Use post value from config ## Code After: import os from tornado.ioloop import IOLoop from tornado.web import Application from tornado.httpserver import HTTPServer from . import handlers from .conf import config class LogsterApplication(Application): handlers = [ (r'/', handlers.IndexHandler), ] settings = { 'template_path': os.path.join( os.path.dirname(__file__), '../templates') } def __init__(self): super(LogsterApplication, self).__init__( handlers=self.handlers, **self.settings ) def run_server(): app = LogsterApplication() server = HTTPServer(app) server.listen(config['app']['port']) IOLoop.current().start()
# ... existing code ... from . import handlers from .conf import config # ... modified code ... server = HTTPServer(app) server.listen(config['app']['port']) # ... rest of the code ...
92c01be43b80247ce2233851dd74b041bb9d44b0
csunplugged/resources/views/BarcodeChecksumPosterResourceGenerator.py
csunplugged/resources/views/BarcodeChecksumPosterResourceGenerator.py
"""Class for Barcode Checksum Poster resource generator.""" from PIL import Image from utils.BaseResourceGenerator import BaseResourceGenerator class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length": ["12", "13"] } def data(self): """Create data for a copy of the Grid resource. Returns: A dictionary of the one page for the resource. """ image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image_path = image_path.format(self.requested_options["barcode_length"]) image = Image.open(image_path) return {"type": "image", "data": image} @property def subtitle(self): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Returns: text for subtitle (str). """ barcode_length = self.requested_options["barcode_length"] return "{} digits - {}".format(barcode_length, super().subtitle)
"""Class for Barcode Checksum Poster resource generator.""" from PIL import Image, ImageDraw from utils.BaseResourceGenerator import BaseResourceGenerator from utils.TextBoxDrawer import TextBoxDrawer from django.utils.translation import ugettext as _ class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length": ["12", "13"] } def data(self): """Create data for a copy of the Grid resource. Returns: A dictionary of the one page for the resource. """ path = "static/img/resources/barcode-checksum-poster/{}-digits" path = path.format(self.requested_options["barcode_length"]) image_path = "{}.png".format(path) svg_path = "{}.svg".format(path) image = Image.open(image_path) draw = ImageDraw.Draw(image) textbox_drawer = TextBoxDrawer(image, draw, svg_path) textbox_drawer.write_text_box( "title", _("13 Digit Barcode"), horiz_just="center", vert_just="center", ) headings = { "heading1": _("Separate!"), "heading2": _("Operate!"), "heading3": _("Calculate!") } for heading_id, heading in headings.items(): textbox_drawer.write_text_box( heading_id, heading, ) textbox_drawer.write_text_box( "paragraph", _("Remember that this algorithm uses modulo 10, so we are only " "interested in the number in the one's column."), ) return {"type": "image", "data": image} @property def subtitle(self): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Returns: text for subtitle (str). """ barcode_length = self.requested_options["barcode_length"] return "{} digits - {}".format(barcode_length, super().subtitle)
Modify Barcode Checksum Poster resource to dynamically overlay text
Modify Barcode Checksum Poster resource to dynamically overlay text
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
"""Class for Barcode Checksum Poster resource generator.""" - from PIL import Image + from PIL import Image, ImageDraw from utils.BaseResourceGenerator import BaseResourceGenerator + from utils.TextBoxDrawer import TextBoxDrawer + from django.utils.translation import ugettext as _ class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length": ["12", "13"] } def data(self): """Create data for a copy of the Grid resource. Returns: A dictionary of the one page for the resource. """ - image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" + path = "static/img/resources/barcode-checksum-poster/{}-digits" - image_path = image_path.format(self.requested_options["barcode_length"]) + path = path.format(self.requested_options["barcode_length"]) + image_path = "{}.png".format(path) + svg_path = "{}.svg".format(path) image = Image.open(image_path) + + draw = ImageDraw.Draw(image) + textbox_drawer = TextBoxDrawer(image, draw, svg_path) + + textbox_drawer.write_text_box( + "title", + _("13 Digit Barcode"), + horiz_just="center", + vert_just="center", + ) + + headings = { + "heading1": _("Separate!"), + "heading2": _("Operate!"), + "heading3": _("Calculate!") + } + + for heading_id, heading in headings.items(): + textbox_drawer.write_text_box( + heading_id, + heading, + ) + + textbox_drawer.write_text_box( + "paragraph", + _("Remember that this algorithm uses modulo 10, so we are only " + "interested in the number in the one's column."), + ) + return {"type": "image", "data": image} @property def subtitle(self): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Returns: text for subtitle (str). """ barcode_length = self.requested_options["barcode_length"] return "{} digits - {}".format(barcode_length, super().subtitle)
Modify Barcode Checksum Poster resource to dynamically overlay text
## Code Before: """Class for Barcode Checksum Poster resource generator.""" from PIL import Image from utils.BaseResourceGenerator import BaseResourceGenerator class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length": ["12", "13"] } def data(self): """Create data for a copy of the Grid resource. Returns: A dictionary of the one page for the resource. """ image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image_path = image_path.format(self.requested_options["barcode_length"]) image = Image.open(image_path) return {"type": "image", "data": image} @property def subtitle(self): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Returns: text for subtitle (str). """ barcode_length = self.requested_options["barcode_length"] return "{} digits - {}".format(barcode_length, super().subtitle) ## Instruction: Modify Barcode Checksum Poster resource to dynamically overlay text ## Code After: """Class for Barcode Checksum Poster resource generator.""" from PIL import Image, ImageDraw from utils.BaseResourceGenerator import BaseResourceGenerator from utils.TextBoxDrawer import TextBoxDrawer from django.utils.translation import ugettext as _ class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length": ["12", "13"] } def data(self): """Create data for a copy of the Grid resource. Returns: A dictionary of the one page for the resource. """ path = "static/img/resources/barcode-checksum-poster/{}-digits" path = path.format(self.requested_options["barcode_length"]) image_path = "{}.png".format(path) svg_path = "{}.svg".format(path) image = Image.open(image_path) draw = ImageDraw.Draw(image) textbox_drawer = TextBoxDrawer(image, draw, svg_path) textbox_drawer.write_text_box( "title", _("13 Digit Barcode"), horiz_just="center", vert_just="center", ) headings = { "heading1": _("Separate!"), "heading2": _("Operate!"), "heading3": _("Calculate!") } for heading_id, heading in headings.items(): textbox_drawer.write_text_box( heading_id, heading, ) textbox_drawer.write_text_box( "paragraph", _("Remember that this algorithm uses modulo 10, so we are only " "interested in the number in the one's column."), ) return {"type": "image", "data": image} @property def subtitle(self): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Returns: text for subtitle (str). """ barcode_length = self.requested_options["barcode_length"] return "{} digits - {}".format(barcode_length, super().subtitle)
// ... existing code ... from PIL import Image, ImageDraw from utils.BaseResourceGenerator import BaseResourceGenerator from utils.TextBoxDrawer import TextBoxDrawer from django.utils.translation import ugettext as _ // ... modified code ... """ path = "static/img/resources/barcode-checksum-poster/{}-digits" path = path.format(self.requested_options["barcode_length"]) image_path = "{}.png".format(path) svg_path = "{}.svg".format(path) image = Image.open(image_path) draw = ImageDraw.Draw(image) textbox_drawer = TextBoxDrawer(image, draw, svg_path) textbox_drawer.write_text_box( "title", _("13 Digit Barcode"), horiz_just="center", vert_just="center", ) headings = { "heading1": _("Separate!"), "heading2": _("Operate!"), "heading3": _("Calculate!") } for heading_id, heading in headings.items(): textbox_drawer.write_text_box( heading_id, heading, ) textbox_drawer.write_text_box( "paragraph", _("Remember that this algorithm uses modulo 10, so we are only " "interested in the number in the one's column."), ) return {"type": "image", "data": image} // ... rest of the code ...
d814c9c131f2c2957173302f7c4c1cbf2b719b45
check_rfc_header.py
check_rfc_header.py
import os from travistooling import ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' print(f, name) print(header)
import datetime as dt import os from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) if __name__ == '__main__': print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] update_timestamp = git('log', '-1', '--format=%ct', f) last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') assert header[2] == expected_date_str, (header[2], expected_date_str)
Check update dates in the RFC headers
Check update dates in the RFC headers
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
+ import datetime as dt import os - from travistooling import ROOT + from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) + if __name__ == '__main__': - print('*** Checking RFC headers') + print('*** Checking RFC headers') - for f in get_rfc_readmes(ROOT): + for f in get_rfc_readmes(ROOT): - print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) + print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) - filename = os.path.basename(os.path.dirname(f)) + filename = os.path.basename(os.path.dirname(f)) - number, name = filename.split('-', 1) + number, name = filename.split('-', 1) - contents = open(f).read() + contents = open(f).read() - header = contents.splitlines()[:3] + header = contents.splitlines()[:3] - assert header[0].startswith('# RFC %03d: ' % int(number)) - assert header[1] == '' + update_timestamp = git('log', '-1', '--format=%ct', f) + last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) - print(f, name) - print(header) + assert header[0].startswith('# RFC %03d: ' % int(number)) + assert header[1] == '' + expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') + assert header[2] == expected_date_str, (header[2], expected_date_str)
Check update dates in the RFC headers
## Code Before: import os from travistooling import ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' print(f, name) print(header) ## Instruction: Check update dates in the RFC headers ## Code After: import datetime as dt import os from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) if __name__ == '__main__': print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] update_timestamp = git('log', '-1', '--format=%ct', f) last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') assert header[2] == expected_date_str, (header[2], expected_date_str)
# ... existing code ... import datetime as dt import os # ... modified code ... from travistooling import git, ROOT ... if __name__ == '__main__': print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] update_timestamp = git('log', '-1', '--format=%ct', f) last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') assert header[2] == expected_date_str, (header[2], expected_date_str) # ... rest of the code ...
bca6f6041e9f49d1d25d7a9c4cb88080d88c45b1
dumper/invalidation.py
dumper/invalidation.py
import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): ''' Each path can actually have multiple cached entries, varying based on different HTTP methods. So a GET request will have a different cached response from a HEAD request. In order to invalidate a path, we must first know all the different cache keys that the path might have been cached at. This returns those keys ''' return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
Comment concerning differences in keys per path
Comment concerning differences in keys per path
Python
mit
saulshanabrook/django-dumper
import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): + ''' + Each path can actually have multiple cached entries, varying based on different HTTP + methods. So a GET request will have a different cached response from a HEAD request. + + In order to invalidate a path, we must first know all the different cache keys that the + path might have been cached at. This returns those keys + ''' return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
Comment concerning differences in keys per path
## Code Before: import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS] ## Instruction: Comment concerning differences in keys per path ## Code After: import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): ''' Each path can actually have multiple cached entries, varying based on different HTTP methods. So a GET request will have a different cached response from a HEAD request. In order to invalidate a path, we must first know all the different cache keys that the path might have been cached at. This returns those keys ''' return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
// ... existing code ... def all_cache_keys_from_path(path): ''' Each path can actually have multiple cached entries, varying based on different HTTP methods. So a GET request will have a different cached response from a HEAD request. In order to invalidate a path, we must first know all the different cache keys that the path might have been cached at. This returns those keys ''' return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS] // ... rest of the code ...
83080df101aca13b9b044996a013794c94ab82ed
pronto/parsers/obo.py
pronto/parsers/obo.py
import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle, ordered=True) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
Make sure to parse OBO documents in order
Make sure to parse OBO documents in order
Python
mit
althonos/pronto
import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo - doc = fastobo.iter(handle) + doc = fastobo.iter(handle, ordered=True) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
Make sure to parse OBO documents in order
## Code Before: import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None ## Instruction: Make sure to parse OBO documents in order ## Code After: import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle, ordered=True) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
# ... existing code ... # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle, ordered=True) # ... rest of the code ...
03ebfe0518a7ac39f9414b3e8d8638c9dcba917c
tests/auth/test_models.py
tests/auth/test_models.py
from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import unittest from bakery.auth.models import BakeryUser class TestBakeryUserModel(TestCase): @unittest.skip('Not yet implemented') def test_get_absolute_url(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_absolute_url(), reverse('user-detail-view')) def test_get_full_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_full_name(), 'John Doe') def test_get_short_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_short_name(), 'John Doe')
from django.test import TestCase from bakery.auth.models import BakeryUser class TestBakeryUserModel(TestCase): def test_get_absolute_url(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_absolute_url(), '/profile/user/') def test_get_full_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_full_name(), 'John Doe') def test_get_short_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_short_name(), 'John Doe')
Adjust test (refers prev commit)
Adjust test (refers prev commit)
Python
bsd-3-clause
muffins-on-dope/bakery,muffins-on-dope/bakery,muffins-on-dope/bakery
- from django.core.urlresolvers import reverse from django.test import TestCase - from django.utils import unittest from bakery.auth.models import BakeryUser class TestBakeryUserModel(TestCase): - @unittest.skip('Not yet implemented') def test_get_absolute_url(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' - self.assertEqual(user.get_absolute_url(), reverse('user-detail-view')) + self.assertEqual(user.get_absolute_url(), '/profile/user/') def test_get_full_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_full_name(), 'John Doe') def test_get_short_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_short_name(), 'John Doe')
Adjust test (refers prev commit)
## Code Before: from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import unittest from bakery.auth.models import BakeryUser class TestBakeryUserModel(TestCase): @unittest.skip('Not yet implemented') def test_get_absolute_url(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_absolute_url(), reverse('user-detail-view')) def test_get_full_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_full_name(), 'John Doe') def test_get_short_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_short_name(), 'John Doe') ## Instruction: Adjust test (refers prev commit) ## Code After: from django.test import TestCase from bakery.auth.models import BakeryUser class TestBakeryUserModel(TestCase): def test_get_absolute_url(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_absolute_url(), '/profile/user/') def test_get_full_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_full_name(), 'John Doe') def test_get_short_name(self): user = BakeryUser.objects.create_user('user', 'password') user.name = 'John Doe' self.assertEqual(user.get_short_name(), 'John Doe')
// ... existing code ... from django.test import TestCase // ... modified code ... def test_get_absolute_url(self): ... user.name = 'John Doe' self.assertEqual(user.get_absolute_url(), '/profile/user/') // ... rest of the code ...
0c803c41fc7a54ddf0b8d1c580c39e7e2c325b8b
container/getPureElkIndex.py
container/getPureElkIndex.py
__author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.indices.exists(index='pureelk-global-arrays'): sys.exit(0) else: sys.exit(1)
__author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.exists(index='.kibana', doc_type='index-pattern',id='pureelk-global-arrays'): sys.exit(0) else: sys.exit(1)
Change the test for pureelk in elasticsearch
Change the test for pureelk in elasticsearch It makes more sense to test for a specific index pattern rather than pureelk-global-arrays index. The reason is if someone never adds an array startup code will try to re-add .kibana data
Python
apache-2.0
pureelk/pureelk,pureelk/pureelk,pureelk/pureelk,pureelk/pureelk
__author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) - if client.indices.exists(index='pureelk-global-arrays'): + if client.exists(index='.kibana', doc_type='index-pattern',id='pureelk-global-arrays'): sys.exit(0) else: sys.exit(1)
Change the test for pureelk in elasticsearch
## Code Before: __author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.indices.exists(index='pureelk-global-arrays'): sys.exit(0) else: sys.exit(1) ## Instruction: Change the test for pureelk in elasticsearch ## Code After: __author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.exists(index='.kibana', doc_type='index-pattern',id='pureelk-global-arrays'): sys.exit(0) else: sys.exit(1)
// ... existing code ... if client.exists(index='.kibana', doc_type='index-pattern',id='pureelk-global-arrays'): sys.exit(0) // ... rest of the code ...
3cee41ff8a7af405fe3a6bfda214e4fe1a6d3c0f
oneflow/settings/snippets/db_production.py
oneflow/settings/snippets/db_production.py
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
Add the test REDIS database.
Add the test REDIS database.
Python
agpl-3.0
1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 + REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
Add the test REDIS database.
## Code Before: DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2 ## Instruction: Add the test REDIS database. ## Code After: DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
... REDIS_DB = 0 REDIS_TEST_DB = 9 ...
4aab1eb2d2d3a0c9b9c4ab6df23b043e6822ff84
examples/delta/delta.py
examples/delta/delta.py
import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') X = np.loadtxt('model_input.txt') Y = np.loadtxt('model_output.txt') # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = delta.analyze(problem, X, Y, num_resamples=10, conf_level=0.95, print_to_console=False) # Returns a dictionary with keys 'delta', 'delta_conf', 'S1', 'S1_conf' print(str(Si['delta']))
import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') X = np.loadtxt('../data/model_input.txt') Y = np.loadtxt('../data/model_output.txt') # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = delta.analyze(problem, X, Y, num_resamples=10, conf_level=0.95, print_to_console=False) # Returns a dictionary with keys 'delta', 'delta_conf', 'S1', 'S1_conf' print(str(Si['delta']))
Fix up example with corrected path
Fix up example with corrected path
Python
mit
jdherman/SALib,SALib/SALib,jdherman/SALib
import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') - X = np.loadtxt('model_input.txt') + X = np.loadtxt('../data/model_input.txt') - Y = np.loadtxt('model_output.txt') + Y = np.loadtxt('../data/model_output.txt') # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = delta.analyze(problem, X, Y, num_resamples=10, conf_level=0.95, print_to_console=False) # Returns a dictionary with keys 'delta', 'delta_conf', 'S1', 'S1_conf' print(str(Si['delta']))
Fix up example with corrected path
## Code Before: import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') X = np.loadtxt('model_input.txt') Y = np.loadtxt('model_output.txt') # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = delta.analyze(problem, X, Y, num_resamples=10, conf_level=0.95, print_to_console=False) # Returns a dictionary with keys 'delta', 'delta_conf', 'S1', 'S1_conf' print(str(Si['delta'])) ## Instruction: Fix up example with corrected path ## Code After: import sys from SALib.analyze import delta from SALib.util import read_param_file import numpy as np sys.path.append('../..') # Read the parameter range file and generate samples # Since this is "given data", the bounds in the parameter file will not be used # but the columns are still expected problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') X = np.loadtxt('../data/model_input.txt') Y = np.loadtxt('../data/model_output.txt') # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = delta.analyze(problem, X, Y, num_resamples=10, conf_level=0.95, print_to_console=False) # Returns a dictionary with keys 'delta', 'delta_conf', 'S1', 'S1_conf' print(str(Si['delta']))
# ... existing code ... problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') X = np.loadtxt('../data/model_input.txt') Y = np.loadtxt('../data/model_output.txt') # ... rest of the code ...
9825d76b6bff7e04d1e277539ece6bda928b648b
wtl/wtlib/forms.py
wtl/wtlib/forms.py
from django import forms from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): worker = GithubWorker() self.repository, self.project = worker.analyze_repo(self.cleaned_data['git_url']) return self.repository, self.project
from django import forms from django.forms.util import ErrorList from django.utils.translation import ugettext_lazy as _ from github import UnknownObjectException from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): if 'git_url' not in self._errors: self._errors['git_url'] = ErrorList() worker = GithubWorker() try: self.repository, self.project = worker.analyze_repo( self.cleaned_data['git_url']) return self.repository, self.project except UnknownObjectException: self._errors['git_url'].append(_('Repository not found.'))
Validate repo exists in `AnalyzeForm`
Validate repo exists in `AnalyzeForm`
Python
mit
elegion/djangodash2013,elegion/djangodash2013
from django import forms + from django.forms.util import ErrorList + from django.utils.translation import ugettext_lazy as _ + from github import UnknownObjectException from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): + if 'git_url' not in self._errors: + self._errors['git_url'] = ErrorList() worker = GithubWorker() + try: - self.repository, self.project = worker.analyze_repo(self.cleaned_data['git_url']) + self.repository, self.project = worker.analyze_repo( + self.cleaned_data['git_url']) - return self.repository, self.project + return self.repository, self.project + except UnknownObjectException: + self._errors['git_url'].append(_('Repository not found.'))
Validate repo exists in `AnalyzeForm`
## Code Before: from django import forms from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): worker = GithubWorker() self.repository, self.project = worker.analyze_repo(self.cleaned_data['git_url']) return self.repository, self.project ## Instruction: Validate repo exists in `AnalyzeForm` ## Code After: from django import forms from django.forms.util import ErrorList from django.utils.translation import ugettext_lazy as _ from github import UnknownObjectException from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): if 'git_url' not in self._errors: self._errors['git_url'] = ErrorList() worker = GithubWorker() try: self.repository, self.project = worker.analyze_repo( self.cleaned_data['git_url']) return self.repository, self.project except UnknownObjectException: self._errors['git_url'].append(_('Repository not found.'))
// ... existing code ... from django import forms from django.forms.util import ErrorList from django.utils.translation import ugettext_lazy as _ from github import UnknownObjectException // ... modified code ... def analyze(self): if 'git_url' not in self._errors: self._errors['git_url'] = ErrorList() worker = GithubWorker() try: self.repository, self.project = worker.analyze_repo( self.cleaned_data['git_url']) return self.repository, self.project except UnknownObjectException: self._errors['git_url'].append(_('Repository not found.')) // ... rest of the code ...
4d547ffa4112412e340abd6231cd406d14b8ff35
l10n_lu_ecdf/__openerp__.py
l10n_lu_ecdf/__openerp__.py
{ "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
{ "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
Python
agpl-3.0
acsone/l10n-luxemburg
{ "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", - "depends": ["l10n_lu_mis_reports", + "depends": ["l10n_lu_ext", + "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
## Code Before: { "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, } ## Instruction: Add dependency on l10n_lu_ext, for the field l10n_lu_matricule ## Code After: { "name": "eCDF annual reports", "version": "8.0.1.0.0", "author": "ACSONE SA/NV", "license": "AGPL-3", "category": "Accounting & Finance", "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], "module": "", "summary": "Generates XML eCDF annual financial reports", "data": [ "views/res_company.xml", "wizard/ecdf_report_view.xml", ], "installable": True, }
// ... existing code ... "website": "http://acsone.eu", "depends": ["l10n_lu_ext", "l10n_lu_mis_reports", "mis_builder"], // ... rest of the code ...
0197553740ff6b542515cb53ce816d629e7b5648
tspapi/__init__.py
tspapi/__init__.py
from __future__ import absolute_import from tspapi.api_call import _ApiCall from tspapi.api import API from tspapi.measurement import Measurement from tspapi.api_exception import ConnectionError from tspapi.api_exception import HTTPResponseError from tspapi.source import Source from tspapi.event import RawEvent from tspapi.event import Event from tspapi.metric import Metric
from __future__ import absolute_import from tspapi.api_exception import ConnectionError from tspapi.api_exception import HTTPResponseError from tspapi.measurement import Measurement from tspapi.source import Source from tspapi.event import RawEvent from tspapi.event import Event from tspapi.metric import Metric from tspapi.api_call import _ApiCall from tspapi.api import API
Rearrange imports for proper dependencies
Rearrange imports for proper dependencies
Python
apache-2.0
jdgwartney/pulse-api-python
from __future__ import absolute_import - from tspapi.api_call import _ApiCall - from tspapi.api import API - from tspapi.measurement import Measurement from tspapi.api_exception import ConnectionError from tspapi.api_exception import HTTPResponseError + from tspapi.measurement import Measurement from tspapi.source import Source from tspapi.event import RawEvent from tspapi.event import Event from tspapi.metric import Metric + from tspapi.api_call import _ApiCall + from tspapi.api import API
Rearrange imports for proper dependencies
## Code Before: from __future__ import absolute_import from tspapi.api_call import _ApiCall from tspapi.api import API from tspapi.measurement import Measurement from tspapi.api_exception import ConnectionError from tspapi.api_exception import HTTPResponseError from tspapi.source import Source from tspapi.event import RawEvent from tspapi.event import Event from tspapi.metric import Metric ## Instruction: Rearrange imports for proper dependencies ## Code After: from __future__ import absolute_import from tspapi.api_exception import ConnectionError from tspapi.api_exception import HTTPResponseError from tspapi.measurement import Measurement from tspapi.source import Source from tspapi.event import RawEvent from tspapi.event import Event from tspapi.metric import Metric from tspapi.api_call import _ApiCall from tspapi.api import API
// ... existing code ... from __future__ import absolute_import from tspapi.api_exception import ConnectionError // ... modified code ... from tspapi.api_exception import HTTPResponseError from tspapi.measurement import Measurement from tspapi.source import Source ... from tspapi.metric import Metric from tspapi.api_call import _ApiCall from tspapi.api import API // ... rest of the code ...
9a879fb583f7f4190a4601a9a488ba61414395e0
kivymd/card.py
kivymd/card.py
from kivy.lang import Builder from kivy.properties import BoundedNumericProperty, ReferenceListProperty from kivy.uix.boxlayout import BoxLayout from kivymd.elevationbehavior import ElevationBehavior from kivymd.theming import ThemableBehavior from kivy.metrics import dp Builder.load_string(''' <MDCard> canvas: Color: rgba: self.background_color RoundedRectangle: size: self.size pos: self.pos radius: [self.border_radius] background_color: self.theme_cls.bg_light ''') class MDCard(ThemableBehavior, ElevationBehavior, BoxLayout): r = BoundedNumericProperty(1., min=0., max=1.) g = BoundedNumericProperty(1., min=0., max=1.) b = BoundedNumericProperty(1., min=0., max=1.) a = BoundedNumericProperty(0., min=0., max=1.) border_radius = BoundedNumericProperty(dp(3),min=0) background_color = ReferenceListProperty(r, g, b, a)
from kivy.lang import Builder from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty from kivy.uix.boxlayout import BoxLayout from kivymd.elevationbehavior import ElevationBehavior from kivymd.theming import ThemableBehavior from kivy.metrics import dp Builder.load_string(''' <MDCard> canvas: Color: rgba: self.background_color RoundedRectangle: size: self.size pos: self.pos radius: [self.border_radius] Color: rgba: self.theme_cls.divider_color a: self.border_color_a Line: rounded_rectangle: (self.pos[0],self.pos[1],self.size[0],self.size[1],self.border_radius) background_color: self.theme_cls.bg_light ''') class MDCard(ThemableBehavior, ElevationBehavior, BoxLayout): r = BoundedNumericProperty(1., min=0., max=1.) g = BoundedNumericProperty(1., min=0., max=1.) b = BoundedNumericProperty(1., min=0., max=1.) a = BoundedNumericProperty(0., min=0., max=1.) border_radius = BoundedNumericProperty(dp(3),min=0) border_color_a = BoundedNumericProperty(0, min=0., max=1.) background_color = ReferenceListProperty(r, g, b, a)
Add border as option (set via alpha)
Add border as option (set via alpha)
Python
mit
cruor99/KivyMD
from kivy.lang import Builder - from kivy.properties import BoundedNumericProperty, ReferenceListProperty + from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty from kivy.uix.boxlayout import BoxLayout from kivymd.elevationbehavior import ElevationBehavior from kivymd.theming import ThemableBehavior from kivy.metrics import dp Builder.load_string(''' <MDCard> canvas: Color: rgba: self.background_color RoundedRectangle: size: self.size pos: self.pos radius: [self.border_radius] + Color: + rgba: self.theme_cls.divider_color + a: self.border_color_a + Line: + rounded_rectangle: (self.pos[0],self.pos[1],self.size[0],self.size[1],self.border_radius) background_color: self.theme_cls.bg_light ''') class MDCard(ThemableBehavior, ElevationBehavior, BoxLayout): r = BoundedNumericProperty(1., min=0., max=1.) g = BoundedNumericProperty(1., min=0., max=1.) b = BoundedNumericProperty(1., min=0., max=1.) a = BoundedNumericProperty(0., min=0., max=1.) border_radius = BoundedNumericProperty(dp(3),min=0) + border_color_a = BoundedNumericProperty(0, min=0., max=1.) background_color = ReferenceListProperty(r, g, b, a)
Add border as option (set via alpha)
## Code Before: from kivy.lang import Builder from kivy.properties import BoundedNumericProperty, ReferenceListProperty from kivy.uix.boxlayout import BoxLayout from kivymd.elevationbehavior import ElevationBehavior from kivymd.theming import ThemableBehavior from kivy.metrics import dp Builder.load_string(''' <MDCard> canvas: Color: rgba: self.background_color RoundedRectangle: size: self.size pos: self.pos radius: [self.border_radius] background_color: self.theme_cls.bg_light ''') class MDCard(ThemableBehavior, ElevationBehavior, BoxLayout): r = BoundedNumericProperty(1., min=0., max=1.) g = BoundedNumericProperty(1., min=0., max=1.) b = BoundedNumericProperty(1., min=0., max=1.) a = BoundedNumericProperty(0., min=0., max=1.) border_radius = BoundedNumericProperty(dp(3),min=0) background_color = ReferenceListProperty(r, g, b, a) ## Instruction: Add border as option (set via alpha) ## Code After: from kivy.lang import Builder from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty from kivy.uix.boxlayout import BoxLayout from kivymd.elevationbehavior import ElevationBehavior from kivymd.theming import ThemableBehavior from kivy.metrics import dp Builder.load_string(''' <MDCard> canvas: Color: rgba: self.background_color RoundedRectangle: size: self.size pos: self.pos radius: [self.border_radius] Color: rgba: self.theme_cls.divider_color a: self.border_color_a Line: rounded_rectangle: (self.pos[0],self.pos[1],self.size[0],self.size[1],self.border_radius) background_color: self.theme_cls.bg_light ''') class MDCard(ThemableBehavior, ElevationBehavior, BoxLayout): r = BoundedNumericProperty(1., min=0., max=1.) g = BoundedNumericProperty(1., min=0., max=1.) b = BoundedNumericProperty(1., min=0., max=1.) a = BoundedNumericProperty(0., min=0., max=1.) border_radius = BoundedNumericProperty(dp(3),min=0) border_color_a = BoundedNumericProperty(0, min=0., max=1.) background_color = ReferenceListProperty(r, g, b, a)
# ... existing code ... from kivy.lang import Builder from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty from kivy.uix.boxlayout import BoxLayout # ... modified code ... radius: [self.border_radius] Color: rgba: self.theme_cls.divider_color a: self.border_color_a Line: rounded_rectangle: (self.pos[0],self.pos[1],self.size[0],self.size[1],self.border_radius) background_color: self.theme_cls.bg_light ... border_radius = BoundedNumericProperty(dp(3),min=0) border_color_a = BoundedNumericProperty(0, min=0., max=1.) background_color = ReferenceListProperty(r, g, b, a) # ... rest of the code ...
9ad0a652e83659cc442b99d6082d4b07204eca4e
apps/mc/settings.py
apps/mc/settings.py
PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.AbstractObservation 'apps.processing.ala.models.Observation': { # currently empty, will be used later for optional filter }, }, # mandatory, number of seconds 'value_frequency': 3600, # mandatory, name_id of common.Process 'process': 'avg_hour', }, 'ground_air_temperature': { 'observation_providers': { 'apps.processing.ala.models.Observation': {}, }, 'value_frequency': 3600, 'process': 'avg_hour', }, }
PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.AbstractObservation 'apps.processing.ala.models.Observation': { # mandatory, name_id of common.Process 'process': 'avg_hour', }, }, # mandatory, number of seconds 'value_frequency': 3600, # mandatory, name_id of common.Process 'process': 'avg_hour', }, 'ground_air_temperature': { 'observation_providers': { 'apps.processing.ala.models.Observation': { 'process': 'avg_hour', }, }, 'value_frequency': 3600, 'process': 'avg_hour', }, }
Move process filter to observation_provider
Move process filter to observation_provider See https://github.com/gis4dis/poster/wiki/Server-configuration/d9e22000c5e923adcb8ec7cee72b62d082799516
Python
bsd-3-clause
gis4dis/poster,gis4dis/poster,gis4dis/poster
PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.AbstractObservation 'apps.processing.ala.models.Observation': { - # currently empty, will be used later for optional filter + # mandatory, name_id of common.Process + 'process': 'avg_hour', }, }, # mandatory, number of seconds 'value_frequency': 3600, # mandatory, name_id of common.Process 'process': 'avg_hour', }, 'ground_air_temperature': { 'observation_providers': { - 'apps.processing.ala.models.Observation': {}, + 'apps.processing.ala.models.Observation': { + 'process': 'avg_hour', + }, }, 'value_frequency': 3600, 'process': 'avg_hour', }, } +
Move process filter to observation_provider
## Code Before: PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.AbstractObservation 'apps.processing.ala.models.Observation': { # currently empty, will be used later for optional filter }, }, # mandatory, number of seconds 'value_frequency': 3600, # mandatory, name_id of common.Process 'process': 'avg_hour', }, 'ground_air_temperature': { 'observation_providers': { 'apps.processing.ala.models.Observation': {}, }, 'value_frequency': 3600, 'process': 'avg_hour', }, } ## Instruction: Move process filter to observation_provider ## Code After: PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.AbstractObservation 'apps.processing.ala.models.Observation': { # mandatory, name_id of common.Process 'process': 'avg_hour', }, }, # mandatory, number of seconds 'value_frequency': 3600, # mandatory, name_id of common.Process 'process': 'avg_hour', }, 'ground_air_temperature': { 'observation_providers': { 'apps.processing.ala.models.Observation': { 'process': 'avg_hour', }, }, 'value_frequency': 3600, 'process': 'avg_hour', }, }
... # mandatory, name_id of common.Process 'process': 'avg_hour', }, ... 'observation_providers': { 'apps.processing.ala.models.Observation': { 'process': 'avg_hour', }, }, ...
a003a7b0d52365c5f5976c7382bc1daf2f5960ac
glitter_news/search_indexes.py
glitter_news/search_indexes.py
from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.select_related().filter( published=True ).exclude( current_version=None )
from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now())
Fix the queryset for news indexing
Fix the queryset for news indexing
Python
bsd-2-clause
blancltd/glitter-news
+ from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): - return self.get_model().objects.select_related().filter( + return self.get_model().objects.published().select_related().filter( + date__lte=timezone.now()) - published=True - ).exclude( - current_version=None - )
Fix the queryset for news indexing
## Code Before: from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.select_related().filter( published=True ).exclude( current_version=None ) ## Instruction: Fix the queryset for news indexing ## Code After: from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now())
# ... existing code ... from django.utils import timezone from haystack import indexes # ... modified code ... def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now()) # ... rest of the code ...
a17b3f1b84d9c87ef3e469a140896dc4dabf9a2b
examples/vhosts.py
examples/vhosts.py
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="example.com") async def hello(request): return response.text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.register_blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
Use of register_blueprint will be deprecated, why not upgrade?
Use of register_blueprint will be deprecated, why not upgrade?
Python
mit
channelcat/sanic,channelcat/sanic,Tim-Erwin/sanic,ashleysommer/sanic,yunstanford/sanic,ashleysommer/sanic,lixxu/sanic,Tim-Erwin/sanic,lixxu/sanic,r0fls/sanic,lixxu/sanic,channelcat/sanic,ashleysommer/sanic,jrocketfingers/sanic,r0fls/sanic,jrocketfingers/sanic,yunstanford/sanic,lixxu/sanic,channelcat/sanic,yunstanford/sanic,yunstanford/sanic
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") - @app.route('/', host="example.com") - async def hello(request): - return response.text("Answer") - @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") - app.register_blueprint(bp) + app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
Use of register_blueprint will be deprecated, why not upgrade?
## Code Before: from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="example.com") async def hello(request): return response.text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.register_blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000) ## Instruction: Use of register_blueprint will be deprecated, why not upgrade? ## Code After: from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
# ... existing code ... @app.route('/', host="sub.example.com") # ... modified code ... app.blueprint(bp) # ... rest of the code ...
d957301018fa47ce61fcb004880ecd5acd18f2a9
features/events/utils.py
features/events/utils.py
from django.utils import timezone def get_requested_time(request): query = request.GET month, year = query.get('month', None), query.get('year', None) if month and year: return timezone.datetime(year=int(year), month=int(month), day=1) else: return None
from django.utils import timezone def get_requested_time(request): query = request.GET month, year = query.get('month', None), query.get('year', None) if month and year: try: return timezone.datetime(year=int(year), month=int(month), day=1) except ValueError: pass return None
Fix handling of invalid parameters
Fix handling of invalid parameters
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
from django.utils import timezone def get_requested_time(request): query = request.GET month, year = query.get('month', None), query.get('year', None) if month and year: + try: - return timezone.datetime(year=int(year), month=int(month), day=1) + return timezone.datetime(year=int(year), month=int(month), day=1) - else: + except ValueError: + pass - return None + return None
Fix handling of invalid parameters
## Code Before: from django.utils import timezone def get_requested_time(request): query = request.GET month, year = query.get('month', None), query.get('year', None) if month and year: return timezone.datetime(year=int(year), month=int(month), day=1) else: return None ## Instruction: Fix handling of invalid parameters ## Code After: from django.utils import timezone def get_requested_time(request): query = request.GET month, year = query.get('month', None), query.get('year', None) if month and year: try: return timezone.datetime(year=int(year), month=int(month), day=1) except ValueError: pass return None
# ... existing code ... if month and year: try: return timezone.datetime(year=int(year), month=int(month), day=1) except ValueError: pass return None # ... rest of the code ...
5d705221e6e6e1d32c90bd8a6e7ee940008d91e9
examples/chatserver/views.py
examples/chatserver/views.py
from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def __init__(self): self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION) def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://localhost:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' def __init__(self): super(BroadcastChatView, self).__init__() self._connection.set('_broadcast_:foobar', 'Hello, Websockets') class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def __init__(self): self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION) def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' def __init__(self): super(BroadcastChatView, self).__init__() self._connection.set('_broadcast_:foobar', 'Hello, Websockets') class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
Use META.SERVER_NAME in template view. …
Use META.SERVER_NAME in template view. …
Python
mit
yacneyac/django-websocket-redis,0nkery/django-websocket-redis3,yacneyac/django-websocket-redis,jgroszko/django-websocket-redis,0nkery/django-websocket-redis3,jgroszko/django-websocket-redis,malefice/django-websocket-redis,Frky/django-websocket-redis,Frky/django-websocket-redis,jrief/django-websocket-redis,malefice/django-websocket-redis,ojarva/django-websocket-redis,ojarva/django-websocket-redis,jrief/django-websocket-redis,Frky/django-websocket-redis
from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def __init__(self): self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION) def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) - context.update(ws_url='ws://localhost:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) + context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' def __init__(self): super(BroadcastChatView, self).__init__() self._connection.set('_broadcast_:foobar', 'Hello, Websockets') class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
Use META.SERVER_NAME in template view. …
## Code Before: from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def __init__(self): self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION) def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://localhost:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' def __init__(self): super(BroadcastChatView, self).__init__() self._connection.set('_broadcast_:foobar', 'Hello, Websockets') class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK') ## Instruction: Use META.SERVER_NAME in template view. … ## Code After: from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def __init__(self): self._connection = redis.StrictRedis(**redis_settings.WS4REDIS_CONNECTION) def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' def __init__(self): super(BroadcastChatView, self).__init__() self._connection.set('_broadcast_:foobar', 'Hello, Websockets') class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
# ... existing code ... context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context # ... rest of the code ...
b8e479e799539be2e413de8052bf0af084e63c8e
osgtest/tests/test_25_voms_admin.py
osgtest/tests/test_25_voms_admin.py
import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 60.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 120.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host.
Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host. git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@18485 4e558342-562e-0410-864c-e07659590f8c
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') - line, gap = core.monitor_file(core.config['voms.webapp-log'], + line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], - core.state['voms.webapp-log-stat'], - 'VOMS-Admin started succesfully', 60.0) + 'VOMS-Admin started succesfully', 120.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') + command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', - command = ('voms-admin', '--nousercert', - '--vo', core.config['voms.vo'], - 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', - 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') + '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host.
## Code Before: import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 60.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry') ## Instruction: Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host. ## Code After: import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 120.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
... line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 120.0) self.assert_(line is not None, 'VOMS Admin webapp started') ... command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry') ...
2917e089734ace4fd212ef9a16e8adf71d671312
test/partial_double_test.py
test/partial_double_test.py
from doubles import allow, teardown class User(object): def __init__(self, name): self.name = name def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice'
from doubles import allow, teardown class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25
Test that only stubbed methods are altered on partial doubles.
Test that only stubbed methods are altered on partial doubles.
Python
mit
uber/doubles
from doubles import allow, teardown class User(object): - def __init__(self, name): + def __init__(self, name, age): self.name = name + self._age = age + + @property + def age(self): + return self._age def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): - user = User('Alice') + user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): - user = User('Alice') + user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' + def test_only_affects_stubbed_method(self): + user = User('Alice', 25) + + allow(user).to_receive('get_name').and_return('Bob') + + assert user.age == 25 +
Test that only stubbed methods are altered on partial doubles.
## Code Before: from doubles import allow, teardown class User(object): def __init__(self, name): self.name = name def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' ## Instruction: Test that only stubbed methods are altered on partial doubles. ## Code After: from doubles import allow, teardown class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25
# ... existing code ... class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age # ... modified code ... def test_stubs_real_object(self): user = User('Alice', 25) ... def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') ... assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25 # ... rest of the code ...
925270e5dd8ffcc72b95bf431444bce480fa18bb
simphony/engine/__init__.py
simphony/engine/__init__.py
from ..extension import get_engine_manager from ..extension import create_wrapper __all__ = ['get_supported_engines', 'create_wrapper', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
from ..extension import get_engine_manager __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
Remove create_wrapper from the API
Remove create_wrapper from the API
Python
bsd-2-clause
simphony/simphony-common
from ..extension import get_engine_manager - from ..extension import create_wrapper - __all__ = ['get_supported_engines', 'create_wrapper', + __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
Remove create_wrapper from the API
## Code Before: from ..extension import get_engine_manager from ..extension import create_wrapper __all__ = ['get_supported_engines', 'create_wrapper', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions ## Instruction: Remove create_wrapper from the API ## Code After: from ..extension import get_engine_manager __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
... from ..extension import get_engine_manager ... __all__ = ['get_supported_engines', 'get_supported_engine_names'] ...
c4bf617dddd15e77974b000e8fa90750e1761386
siteconfig/__init__.py
siteconfig/__init__.py
from .configobj import Config config = Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().update(config) get = config.get
from .configobj import Config config = Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().update(config) get = config.get get_bool = config.get_bool
Add get_bool to package exports
Add get_bool to package exports
Python
bsd-3-clause
mikeboers/siteconfig,mikeboers/siteconfig
from .configobj import Config config = Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().update(config) + get = config.get + get_bool = config.get_bool
Add get_bool to package exports
## Code Before: from .configobj import Config config = Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().update(config) get = config.get ## Instruction: Add get_bool to package exports ## Code After: from .configobj import Config config = Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().update(config) get = config.get get_bool = config.get_bool
# ... existing code ... globals().update(config) get = config.get get_bool = config.get_bool # ... rest of the code ...
3498ca5117a35d61a5b539067b7ac743497cf8c7
tests/test_helpers.py
tests/test_helpers.py
import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'FOO': 'my foo value', 'PATH': None} assert os.environ == old assert not os.environ.get('FOO'), "Invalid test setup" assert not os.environ.get('BAR'), "Invalid test setup" with EnvironContext(**new): assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'PATH': None, 'FOO': 'my foo value'} assert os.environ == old assert os.environ.get('PATH'), "Invalid test setup" assert not os.environ.get('FOO'), "Invalid test setup" with EnvironContext(**new): assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
Make environ context helper test more accurate
Make environ context helper test more accurate
Python
bsd-3-clause
mdgart/sentrylogs
import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ - new = {'FOO': 'my foo value', 'PATH': None} + new = {'PATH': None, 'FOO': 'my foo value'} assert os.environ == old + assert os.environ.get('PATH'), "Invalid test setup" assert not os.environ.get('FOO'), "Invalid test setup" - assert not os.environ.get('BAR'), "Invalid test setup" with EnvironContext(**new): + assert not os.environ.get('PATH'), \ + "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" - assert not os.environ.get('PATH'), \ - "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
Make environ context helper test more accurate
## Code Before: import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'FOO': 'my foo value', 'PATH': None} assert os.environ == old assert not os.environ.get('FOO'), "Invalid test setup" assert not os.environ.get('BAR'), "Invalid test setup" with EnvironContext(**new): assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset" ## Instruction: Make environ context helper test more accurate ## Code After: import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'PATH': None, 'FOO': 'my foo value'} assert os.environ == old assert os.environ.get('PATH'), "Invalid test setup" assert not os.environ.get('FOO'), "Invalid test setup" with EnvironContext(**new): assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
... old = os.environ new = {'PATH': None, 'FOO': 'my foo value'} ... assert os.environ == old assert os.environ.get('PATH'), "Invalid test setup" assert not os.environ.get('FOO'), "Invalid test setup" ... with EnvironContext(**new): assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ['FOO'] == new['FOO'], \ ... "os.environ[FOO] wasn't set by the contextmanager" ...
5c8780c1f4ba914f20f0dc022cc26becb381f2f1
markymark/fields.py
markymark/fields.py
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
Revert "Allow widget overwriting on form field"
Revert "Allow widget overwriting on form field" This reverts commit 23a9aaae78cc4d9228f8d0705647fbcadcaf7975.
Python
mit
moccu/django-markymark,moccu/django-markymark,moccu/django-markymark
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): - kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) + kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
Revert "Allow widget overwriting on form field"
## Code Before: from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs) ## Instruction: Revert "Allow widget overwriting on form field" ## Code After: from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
// ... existing code ... def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) // ... rest of the code ...
15479b3baea8d0f5cb58bf7d22321646ac4513bc
spacy/lang/nl/lex_attrs.py
spacy/lang/nl/lex_attrs.py
from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
Add comment to like_num re: future work
Add comment to like_num re: future work
Python
mit
spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy
from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): + # This only does the most basic check for whether a token is a digit + # or matches one of the number words. In order to handle numbers like + # "drieëntwintig", more work is required. + # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
Add comment to like_num re: future work
## Code Before: from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num } ## Instruction: Add comment to like_num re: future work ## Code After: from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
// ... existing code ... def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') // ... rest of the code ...
bc36a19d3bb1c07cbe2a44de88f227ef71c50b8c
notebooks/utils.py
notebooks/utils.py
def print_generated_sequence(g, num, *, sep=", "): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ if seed: g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
Allow passing seed directly to helper function
Allow passing seed directly to helper function
Python
mit
maxalbert/tohu
- def print_generated_sequence(g, num, *, sep=", "): + def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ + if seed: + g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
Allow passing seed directly to helper function
## Code Before: def print_generated_sequence(g, num, *, sep=", "): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems))) ## Instruction: Allow passing seed directly to helper function ## Code After: def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ if seed: g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
... def print_generated_sequence(g, num, *, sep=", ", seed=None): """ ... """ if seed: g.reset(seed) ...
3373521f43b0d605bba6cc36b190c064d5a0303e
kytos/core/link.py
kytos/core/link.py
import json from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
import json from uuid import uuid4 from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
Define Link ID as UUID
Define Link ID as UUID
Python
mit
kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos
import json + + from uuid import uuid4 from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b + self._uuid = uuid4() super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ - return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id) + return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
Define Link ID as UUID
## Code Before: import json from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict()) ## Instruction: Define Link ID as UUID ## Code After: import json from uuid import uuid4 from kytos.core.common import GenericEntity class Link(GenericEntity): """Define a link between two Endpoints.""" def __init__(self, endpoint_a, endpoint_b): """Create a Link instance and set its attributes.""" self.endpoint_a = endpoint_a self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() def __eq__(self, other): """Check if two instances of Link are equal.""" return ((self.endpoint_a == other.endpoint_a and self.endpoint_b == other.endpoint_b) or (self.endpoint_a == other.endpoint_b and self.endpoint_b == other.endpoint_a)) @property def id(self): # pylint: disable=invalid-name """Return id from Link intance. Returns: string: link id. """ return "{}".format(self._uuid) def as_dict(self): """Return the Link as a dictionary.""" return {'id': self.id, 'endpoint_a': self.endpoint_a.as_dict(), 'endpoint_b': self.endpoint_b.as_dict(), 'metadata': self.metadata, 'active': self.active, 'enabled': self.enabled} def as_json(self): """Return the Link as a JSON string.""" return json.dumps(self.as_dict())
... import json from uuid import uuid4 ... self.endpoint_b = endpoint_b self._uuid = uuid4() super().__init__() ... """ return "{}".format(self._uuid) ...
5ee3eb2f68e4af8e70ea383b067fe67ffd4800bf
loadsbroker/webapp/__init__.py
loadsbroker/webapp/__init__.py
import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA}) ])
import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA, "default_filename": "index.html"}) ])
Set the `default_filename` for `GrafanaHandler`.
Set the `default_filename` for `GrafanaHandler`.
Python
apache-2.0
loads/loads-broker,loads/loads-broker,loads/loads-broker,loads/loads-broker
import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), - (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA}) + (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA, "default_filename": "index.html"}) ])
Set the `default_filename` for `GrafanaHandler`.
## Code Before: import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA}) ]) ## Instruction: Set the `default_filename` for `GrafanaHandler`. ## Code After: import os import tornado.web from loadsbroker.webapp.api import RootHandler, RunHandler from loadsbroker.webapp.views import GrafanaHandler _GRAFANA = os.path.join(os.path.dirname(__file__), 'grafana') application = tornado.web.Application([ (r"/api", RootHandler), (r"/api/run/(.*)", RunHandler), (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA, "default_filename": "index.html"}) ])
# ... existing code ... (r"/api/run/(.*)", RunHandler), (r"/dashboards/run/(.*)", GrafanaHandler, {"path": _GRAFANA, "default_filename": "index.html"}) ]) # ... rest of the code ...
25c0558b0c75306c8d9c547668df9cef25bae786
symbolset.py
symbolset.py
class SymbolSet(): def __init__(self): self._address_labels = dict() self._label_addresses = dict() self._generic_id = 0 def load(self, config_path): pass def add_label(self, address, label): if address in self._address_labels: raise TargetRelabelException("{:#04X} has already been given the " "label {}".format(address, self._address_labels[address])) if label in self._label_addresses: raise LabelReuseException('The label "{}" is already used ' 'at {:#04X}'.format(label, address)) self._address_labels[address] = label self._label_addresses[label] = address def add_generic_label(self, address): label = "label{:04}".format(self._generic_id) self.add_label(address, label) self._generic_id += 1 def get_label(self, address): return self._address_labels.get(address, None) def get_address(self, label): return self._label_addresses.get(label, None) class TargetRelabelException(Exception): pass class LabelReuseException(Exception): pass
class SymbolSet(): def __init__(self): self._address_labels = dict() self._label_addresses = dict() self._generic_id = 0 def add_label(self, address, label): if address in self._address_labels: raise TargetRelabelException("{:#04X} has already been given the " "label {}".format(address, self._address_labels[address])) if label in self._label_addresses: raise LabelReuseException('The label "{}" is already used ' 'at {:#04X}'.format(label, address)) self._address_labels[address] = label self._label_addresses[label] = address def add_generic_label(self, address): label = "label{:04}".format(self._generic_id) self.add_label(address, label) self._generic_id += 1 def get_label(self, address): return self._address_labels.get(address, None) def get_address(self, label): return self._label_addresses.get(label, None) class TargetRelabelException(Exception): pass class LabelReuseException(Exception): pass
Remove redundant load() method from SymbolSet.
Remove redundant load() method from SymbolSet.
Python
mit
achan1989/diSMB
class SymbolSet(): def __init__(self): self._address_labels = dict() self._label_addresses = dict() self._generic_id = 0 - - def load(self, config_path): - pass def add_label(self, address, label): if address in self._address_labels: raise TargetRelabelException("{:#04X} has already been given the " "label {}".format(address, self._address_labels[address])) if label in self._label_addresses: raise LabelReuseException('The label "{}" is already used ' 'at {:#04X}'.format(label, address)) self._address_labels[address] = label self._label_addresses[label] = address def add_generic_label(self, address): label = "label{:04}".format(self._generic_id) self.add_label(address, label) self._generic_id += 1 def get_label(self, address): return self._address_labels.get(address, None) def get_address(self, label): return self._label_addresses.get(label, None) class TargetRelabelException(Exception): pass class LabelReuseException(Exception): pass
Remove redundant load() method from SymbolSet.
## Code Before: class SymbolSet(): def __init__(self): self._address_labels = dict() self._label_addresses = dict() self._generic_id = 0 def load(self, config_path): pass def add_label(self, address, label): if address in self._address_labels: raise TargetRelabelException("{:#04X} has already been given the " "label {}".format(address, self._address_labels[address])) if label in self._label_addresses: raise LabelReuseException('The label "{}" is already used ' 'at {:#04X}'.format(label, address)) self._address_labels[address] = label self._label_addresses[label] = address def add_generic_label(self, address): label = "label{:04}".format(self._generic_id) self.add_label(address, label) self._generic_id += 1 def get_label(self, address): return self._address_labels.get(address, None) def get_address(self, label): return self._label_addresses.get(label, None) class TargetRelabelException(Exception): pass class LabelReuseException(Exception): pass ## Instruction: Remove redundant load() method from SymbolSet. ## Code After: class SymbolSet(): def __init__(self): self._address_labels = dict() self._label_addresses = dict() self._generic_id = 0 def add_label(self, address, label): if address in self._address_labels: raise TargetRelabelException("{:#04X} has already been given the " "label {}".format(address, self._address_labels[address])) if label in self._label_addresses: raise LabelReuseException('The label "{}" is already used ' 'at {:#04X}'.format(label, address)) self._address_labels[address] = label self._label_addresses[label] = address def add_generic_label(self, address): label = "label{:04}".format(self._generic_id) self.add_label(address, label) self._generic_id += 1 def get_label(self, address): return self._address_labels.get(address, None) def get_address(self, label): return self._label_addresses.get(label, None) class TargetRelabelException(Exception): pass class LabelReuseException(Exception): pass
// ... existing code ... self._generic_id = 0 // ... rest of the code ...
c3f8860c717a139d396b0d902db989ab7b8369ba
stock_inventory_hierarchical/__openerp__.py
stock_inventory_hierarchical/__openerp__.py
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True }
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
Fix image path in manifest
Python
agpl-3.0
kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], - "images": ["inventory_form.png", + "images": ["images/inventory_form.png", - "inventory_form_actions.png", + "images/inventory_form_actions.png", - "wizard.png"], + "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
## Code Before: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True } ## Instruction: Fix image path in manifest ## Code After: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
# ... existing code ... "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', # ... rest of the code ...
a5b57601da6e9b85eca18d61e3784addd1863fa4
i3pystatus/__init__.py
i3pystatus/__init__.py
from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp
from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__)
Make i3pystatus a namespace package
Make i3pystatus a namespace package
Python
mit
Arvedui/i3pystatus,schroeji/i3pystatus,opatut/i3pystatus,MaicoTimmerman/i3pystatus,eBrnd/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,Arvedui/i3pystatus,teto/i3pystatus,fmarchenko/i3pystatus,plumps/i3pystatus,paulollivier/i3pystatus,juliushaertl/i3pystatus,ismaelpuerto/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,asmikhailov/i3pystatus,enkore/i3pystatus,drwahl/i3pystatus,claria/i3pystatus,ismaelpuerto/i3pystatus,richese/i3pystatus,onkelpit/i3pystatus,plumps/i3pystatus,claria/i3pystatus,yang-ling/i3pystatus,opatut/i3pystatus,MaicoTimmerman/i3pystatus,facetoe/i3pystatus,onkelpit/i3pystatus,eBrnd/i3pystatus,facetoe/i3pystatus,asmikhailov/i3pystatus,richese/i3pystatus,juliushaertl/i3pystatus,yang-ling/i3pystatus,fmarchenko/i3pystatus,m45t3r/i3pystatus,paulollivier/i3pystatus,enkore/i3pystatus,Elder-of-Ozone/i3pystatus,Elder-of-Ozone/i3pystatus,ncoop/i3pystatus
+ + from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp + __path__ = extend_path(__path__, __name__) +
Make i3pystatus a namespace package
## Code Before: from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp ## Instruction: Make i3pystatus a namespace package ## Code After: from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__)
... from pkgutil import extend_path ... from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__) ...
2b380d501b80afad8c7c5ec27537bcc682ed2775
commands/handle.py
commands/handle.py
import commands.cmds as cmds def handle(self, chat_raw): self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")") _atmp1 = chat_raw.split(" ") _atmp2 = list(_atmp1[0]) del _atmp2[0] del _atmp1[0] cmdobj = { "base": _atmp2, "args_raw": _atmp1, "scope": self, "chat_raw": chat_raw } commands.cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in commands.cmds.baseList else commands.cmds.baseList[_atmp2].begin(self, cmdobj)
import commands.cmds as cmds def handle(self, chat_raw): self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")") _atmp1 = chat_raw.split(" ") _atmp2 = list(_atmp1[0]) del _atmp2[0] del _atmp1[0] cmdobj = { "base": _atmp2, "args_raw": _atmp1, "scope": self, "chat_raw": chat_raw } cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in cmds.baseList else cmds.baseList[_atmp2].begin(self, cmdobj)
Fix some scope mistakes. This fix was part of the reverted commit.
Fix some scope mistakes. This fix was part of the reverted commit.
Python
mit
TiberiumPY/puremine,Armored-Dragon/pymineserver
import commands.cmds as cmds def handle(self, chat_raw): self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")") _atmp1 = chat_raw.split(" ") _atmp2 = list(_atmp1[0]) del _atmp2[0] del _atmp1[0] cmdobj = { "base": _atmp2, "args_raw": _atmp1, "scope": self, "chat_raw": chat_raw } - commands.cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in commands.cmds.baseList else commands.cmds.baseList[_atmp2].begin(self, cmdobj) + cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in cmds.baseList else cmds.baseList[_atmp2].begin(self, cmdobj)
Fix some scope mistakes. This fix was part of the reverted commit.
## Code Before: import commands.cmds as cmds def handle(self, chat_raw): self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")") _atmp1 = chat_raw.split(" ") _atmp2 = list(_atmp1[0]) del _atmp2[0] del _atmp1[0] cmdobj = { "base": _atmp2, "args_raw": _atmp1, "scope": self, "chat_raw": chat_raw } commands.cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in commands.cmds.baseList else commands.cmds.baseList[_atmp2].begin(self, cmdobj) ## Instruction: Fix some scope mistakes. This fix was part of the reverted commit. ## Code After: import commands.cmds as cmds def handle(self, chat_raw): self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")") _atmp1 = chat_raw.split(" ") _atmp2 = list(_atmp1[0]) del _atmp2[0] del _atmp1[0] cmdobj = { "base": _atmp2, "args_raw": _atmp1, "scope": self, "chat_raw": chat_raw } cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in cmds.baseList else cmds.baseList[_atmp2].begin(self, cmdobj)
// ... existing code ... } cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in cmds.baseList else cmds.baseList[_atmp2].begin(self, cmdobj) // ... rest of the code ...
6018abc4a1c2dfa139bb104ae6db69fef5994ff6
plugins/chrome_extensions.py
plugins/chrome_extensions.py
import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150117" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150125" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: try: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 except: pass # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
Add try/except to catch if no extensions are parsed.
Add try/except to catch if no extensions are parsed.
Python
apache-2.0
obsidianforensics/hindsight,obsidianforensics/hindsight
import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 - version = "20150117" + version = "20150125" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: + try: - for ext in target_browser.installed_extensions['data']: + for ext in target_browser.installed_extensions['data']: - if ext.app_id == m.group(1): + if ext.app_id == m.group(1): - item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) + item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) - parsedItems += 1 + parsedItems += 1 + except: + pass # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
Add try/except to catch if no extensions are parsed.
## Code Before: import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150117" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 # Description of what the plugin did return "%s extension URLs parsed" % parsedItems ## Instruction: Add try/except to catch if no extensions are parsed. ## Code After: import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150125" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: try: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 except: pass # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
... browserVersion = 1 version = "20150125" parsedItems = 0 ... if m: try: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 except: pass ...
8c5aca4b9957e883a9dab8c95933de7285ab335b
login/middleware.py
login/middleware.py
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (ACTIVATE_PATH in request.path or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
Revert trying to fix activation redirection bug
Revert trying to fix activation redirection bug This reverts commit c2d63335062abea4cece32bd01132bcf8dce44f2. It seems like the commit doesn't actually do anything to alleviate the bug. Since it's also more lenient with its checks, I'll rather revert it.
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ - and not (ACTIVATE_PATH in request.path + and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
Revert trying to fix activation redirection bug
## Code Before: from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (ACTIVATE_PATH in request.path or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH) ## Instruction: Revert trying to fix activation redirection bug ## Code After: from django.conf import settings from django.http import HttpResponseRedirect DETACH_PATH = '/user/detach' ACTIVATE_PATH = '/user/activate' class DetachMiddleware(object): def process_request(self, request): if not request.path == '/login/' \ and not request.path.startswith('/api') \ and not request.user.is_anonymous: if not request.user.is_native: if not (request.path == DETACH_PATH or request.path.startswith('/logout')): return HttpResponseRedirect(DETACH_PATH) elif not request.user.is_mail_verified \ and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): return HttpResponseRedirect(ACTIVATE_PATH)
... elif not request.user.is_mail_verified \ and not (request.path.startswith(ACTIVATE_PATH) or request.path.startswith('/logout')): ...
138df31dc628daad0c60f062b05774d6c7d4338d
src/kuas_api/modules/const.py
src/kuas_api/modules/const.py
device_version = { "android": "2.1.2", "android_donate": "2.1.2", "ios": "1.4.3" } # Token duration in seconds token_duration = 3600 # HTTP Status Code ok = 200 no_content = 204
device_version = { "android": "2.1.3", "android_donate": "2.1.2", "ios": "1.6.0" } # Token duration in seconds token_duration = 3600 serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf" # HTTP Status Code ok = 200 no_content = 204
Change android version to 2.1.3
Change android version to 2.1.3
Python
mit
JohnSounder/AP-API,kuastw/AP-API,kuastw/AP-API,JohnSounder/AP-API
- device_version = { - "android": "2.1.2", + "android": "2.1.3", "android_donate": "2.1.2", - "ios": "1.4.3" + "ios": "1.6.0" } # Token duration in seconds token_duration = 3600 + serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf" # HTTP Status Code ok = 200 no_content = 204
Change android version to 2.1.3
## Code Before: device_version = { "android": "2.1.2", "android_donate": "2.1.2", "ios": "1.4.3" } # Token duration in seconds token_duration = 3600 # HTTP Status Code ok = 200 no_content = 204 ## Instruction: Change android version to 2.1.3 ## Code After: device_version = { "android": "2.1.3", "android_donate": "2.1.2", "ios": "1.6.0" } # Token duration in seconds token_duration = 3600 serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf" # HTTP Status Code ok = 200 no_content = 204
# ... existing code ... device_version = { "android": "2.1.3", "android_donate": "2.1.2", "ios": "1.6.0" } # ... modified code ... token_duration = 3600 serect_key = "usapoijupojfa;dsj;lv;ldakjads;lfkjapoiuewqprjf" # ... rest of the code ...
9cca5d4ce1c5097e48e55ad3a48b09a01cc0aa6b
lumberjack/config/__init__.py
lumberjack/config/__init__.py
from six.moves import configparser from six import StringIO import pkg_resources import logging.config def configure(mode, disable_existing_loggers=False): """Configure from predefined useful default modes.""" cfg = configparser.ConfigParser() modefn = "{0}.cfg".format(mode) if not mode.endswith(".cfg") else mode for filename in ["base.cfg", modefn]: cfg.readfp(pkg_resources.resource_stream(__name__, filename)) cfgbuffer = StringIO() cfg.write(cfgbuffer) cfgbuffer.seek(0) return logging.config.fileConfig(cfgbuffer, disable_existing_loggers=disable_existing_loggers)
from six.moves import configparser from six import StringIO import pkg_resources import logging.config def configure(mode, disable_existing_loggers=False): """Configure from predefined useful default modes.""" cfg = configparser.ConfigParser() modefn = "{0}.cfg".format(mode) if not mode.endswith(".cfg") else mode for filename in ["base.cfg", modefn]: cfg.readfp(pkg_resources.resource_stream(__name__, filename)) cfg.read("lumberjack.cfg") cfgbuffer = StringIO() cfg.write(cfgbuffer) cfgbuffer.seek(0) return logging.config.fileConfig(cfgbuffer, disable_existing_loggers=disable_existing_loggers)
Read a custom lumberjack.cfg on startup if necessary.
Read a custom lumberjack.cfg on startup if necessary.
Python
mit
alexrudy/lumberjack
from six.moves import configparser from six import StringIO import pkg_resources import logging.config def configure(mode, disable_existing_loggers=False): """Configure from predefined useful default modes.""" cfg = configparser.ConfigParser() modefn = "{0}.cfg".format(mode) if not mode.endswith(".cfg") else mode for filename in ["base.cfg", modefn]: cfg.readfp(pkg_resources.resource_stream(__name__, filename)) + cfg.read("lumberjack.cfg") cfgbuffer = StringIO() cfg.write(cfgbuffer) cfgbuffer.seek(0) return logging.config.fileConfig(cfgbuffer, disable_existing_loggers=disable_existing_loggers)
Read a custom lumberjack.cfg on startup if necessary.
## Code Before: from six.moves import configparser from six import StringIO import pkg_resources import logging.config def configure(mode, disable_existing_loggers=False): """Configure from predefined useful default modes.""" cfg = configparser.ConfigParser() modefn = "{0}.cfg".format(mode) if not mode.endswith(".cfg") else mode for filename in ["base.cfg", modefn]: cfg.readfp(pkg_resources.resource_stream(__name__, filename)) cfgbuffer = StringIO() cfg.write(cfgbuffer) cfgbuffer.seek(0) return logging.config.fileConfig(cfgbuffer, disable_existing_loggers=disable_existing_loggers) ## Instruction: Read a custom lumberjack.cfg on startup if necessary. ## Code After: from six.moves import configparser from six import StringIO import pkg_resources import logging.config def configure(mode, disable_existing_loggers=False): """Configure from predefined useful default modes.""" cfg = configparser.ConfigParser() modefn = "{0}.cfg".format(mode) if not mode.endswith(".cfg") else mode for filename in ["base.cfg", modefn]: cfg.readfp(pkg_resources.resource_stream(__name__, filename)) cfg.read("lumberjack.cfg") cfgbuffer = StringIO() cfg.write(cfgbuffer) cfgbuffer.seek(0) return logging.config.fileConfig(cfgbuffer, disable_existing_loggers=disable_existing_loggers)
// ... existing code ... cfg.readfp(pkg_resources.resource_stream(__name__, filename)) cfg.read("lumberjack.cfg") cfgbuffer = StringIO() // ... rest of the code ...
b180c7e3907df74252ee3270468a768036dc4467
tests/test_timeseries.py
tests/test_timeseries.py
import unittest from datetime import datetime, timedelta import sys sys.path.append(r"..") from daymetpy import download_Daymet class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013) self.assertTrue(df.year.count() == 365) self.assertTrue("tmax" in df.columns) self.assertTrue("tmin" in df.columns) self.assertTrue("prcp" in df.columns) def test_out_of_bounds(self): london_lat, london_long = 51.5072, 0.1275 with self.assertRaises(NameError): df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013) if __name__ == '__main__': unittest.main()
import unittest from datetime import datetime, timedelta import sys sys.path.append(r"../..") from daymetpy import daymet_timeseries class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012) self.assertTrue(df.year.count() == 365) self.assertTrue("tmax" in df.columns) self.assertTrue("tmin" in df.columns) self.assertTrue("prcp" in df.columns) def test_out_of_bounds(self): london_lat, london_long = 51.5072, 0.1275 with self.assertRaises(NameError): df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012) if __name__ == '__main__': unittest.main()
Update test to new package structure
Update test to new package structure
Python
agpl-3.0
khufkens/daymetpy
import unittest from datetime import datetime, timedelta import sys - sys.path.append(r"..") + sys.path.append(r"../..") - from daymetpy import download_Daymet + from daymetpy import daymet_timeseries class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 - df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013) + df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012) self.assertTrue(df.year.count() == 365) self.assertTrue("tmax" in df.columns) self.assertTrue("tmin" in df.columns) self.assertTrue("prcp" in df.columns) def test_out_of_bounds(self): london_lat, london_long = 51.5072, 0.1275 with self.assertRaises(NameError): - df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013) + df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012) if __name__ == '__main__': unittest.main()
Update test to new package structure
## Code Before: import unittest from datetime import datetime, timedelta import sys sys.path.append(r"..") from daymetpy import download_Daymet class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013) self.assertTrue(df.year.count() == 365) self.assertTrue("tmax" in df.columns) self.assertTrue("tmin" in df.columns) self.assertTrue("prcp" in df.columns) def test_out_of_bounds(self): london_lat, london_long = 51.5072, 0.1275 with self.assertRaises(NameError): df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013) if __name__ == '__main__': unittest.main() ## Instruction: Update test to new package structure ## Code After: import unittest from datetime import datetime, timedelta import sys sys.path.append(r"../..") from daymetpy import daymet_timeseries class TimeseriesTest(unittest.TestCase): def setUp(self): pass def test_ornl_df(self): ornl_lat, ornl_long = 35.9313167, -84.3104124 df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012) self.assertTrue(df.year.count() == 365) self.assertTrue("tmax" in df.columns) self.assertTrue("tmin" in df.columns) self.assertTrue("prcp" in df.columns) def test_out_of_bounds(self): london_lat, london_long = 51.5072, 0.1275 with self.assertRaises(NameError): df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012) if __name__ == '__main__': unittest.main()
// ... existing code ... import sys sys.path.append(r"../..") from daymetpy import daymet_timeseries // ... modified code ... ornl_lat, ornl_long = 35.9313167, -84.3104124 df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012) ... with self.assertRaises(NameError): df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012) // ... rest of the code ...
8930337ef2402a9e5a6dfe3a336fc24b0ffbf87f
reviewboard/accounts/urls.py
reviewboard/accounts/urls.py
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Fix internal server error at url /account/recover
Fix internal server error at url /account/recover Fixed a 500 error at /account/recover when trying to reset password on the login page. Testing Done: Verified that the server no longer returns a 500 error when loading the form. Reviewed at https://reviews.reviewboard.org/r/5431/
Python
mit
beol/reviewboard,davidt/reviewboard,beol/reviewboard,1tush/reviewboard,custode/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,KnowNo/reviewboard,1tush/reviewboard,beol/reviewboard,1tush/reviewboard,beol/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,chipx86/reviewboard,chipx86/reviewboard,1tush/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,chipx86/reviewboard,davidt/reviewboard,KnowNo/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,1tush/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,1tush/reviewboard,1tush/reviewboard,sgallagher/reviewboard
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', - {'template_name': 'accounts/password_reset_done.html'}), + {'template_name': 'accounts/password_reset_done.html'}, + name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Fix internal server error at url /account/recover
## Code Before: from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), ) ## Instruction: Fix internal server error at url /account/recover ## Code After: from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
... 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', ...
40a59efec51661d4325e97f2e307963811336b94
calaccess_processed/__init__.py
calaccess_processed/__init__.py
from __future__ import absolute_import default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig'
import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path
Add get_model_list and archive_directory_path functions
Add get_model_list and archive_directory_path functions
Python
mit
california-civic-data-coalition/django-calaccess-processed-data,california-civic-data-coalition/django-calaccess-processed-data
- from __future__ import absolute_import + import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' + + def get_model_list(): + """ + Returns a model list of + """ + from django.apps import apps + model_list = apps.get_app_config("calaccess_processed").models.values() + return [ + m for m in model_list + if m.__module__.split('.')[-1] != 'tracking' + ] + + def archive_directory_path(instance, filename): + """ + Returns a path to an archived processed data file or zip + """ + from calaccess_processed.models.tracking import ( + ProcessedDataVersion, + ProcessedDataFile, + ) + + if isinstance(instance, ProcessedDataVersion): + release_datetime = instance.raw_version.release_datetime + f_name, f_ext = filename.split('.') + path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( + fn=f_name, + dt=release_datetime, + fx=f_ext, + ) + elif isinstance(instance, ProcessedDataFile): + release_datetime = instance.version.raw_version.release_datetime + path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) + else: + raise TypeError( + "Must be ProcessedDataVersion or ProcessedDataFile instance." + ) + return path +
Add get_model_list and archive_directory_path functions
## Code Before: from __future__ import absolute_import default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' ## Instruction: Add get_model_list and archive_directory_path functions ## Code After: import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path
# ... existing code ... import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path # ... rest of the code ...
a7f7d8ff9f8279ec2c1f3981b1507001f1f94394
test/completion/docstring.py
test/completion/docstring.py
""" Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b
""" Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b def e(a, b): """ asdfasdf @type a: str @param a: blablabla """ #? str() a #? b
Add tests for epydoc formated dosctring
Add tests for epydoc formated dosctring
Python
mit
mfussenegger/jedi,flurischt/jedi,dwillmer/jedi,tjwei/jedi,WoLpH/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,jonashaag/jedi,tjwei/jedi,dwillmer/jedi,WoLpH/jedi
""" Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b + def e(a, b): + """ asdfasdf + @type a: str + @param a: blablabla + """ + #? str() + a + #? + b +
Add tests for epydoc formated dosctring
## Code Before: """ Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b ## Instruction: Add tests for epydoc formated dosctring ## Code After: """ Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b def e(a, b): """ asdfasdf @type a: str @param a: blablabla """ #? str() a #? b
# ... existing code ... b def e(a, b): """ asdfasdf @type a: str @param a: blablabla """ #? str() a #? b # ... rest of the code ...
27a1d78611cef1ab23044db22bd4bf7c61582efe
src/data/Track/UploadHandlers/YoutubeUploadHandler.py
src/data/Track/UploadHandlers/YoutubeUploadHandler.py
import os from data.Track.UploadHandler import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
import os from src.data.Track import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
Fix wrong import from UploadHandler
Fix wrong import from UploadHandler
Python
agpl-3.0
Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus,Pynitus-Universe/Pynitus
import os + from src.data.Track import UploadHandler - from data.Track.UploadHandler import UploadHandler - from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
Fix wrong import from UploadHandler
## Code Before: import os from data.Track.UploadHandler import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track ## Instruction: Fix wrong import from UploadHandler ## Code After: import os from src.data.Track import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
... from src.data.Track import UploadHandler from src.data.Track.Tracks import YoutubeTrack ...
79edc5861e37de0970d2af46ba45e07b47d30837
test/test_retriever.py
test/test_retriever.py
"""Tests for the EcoData Retriever""" from StringIO import StringIO from engine import Engine def test_escape_single_quotes(): """Test escaping of single quotes""" test_engine = Engine() assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'" def test_escape_double_quotes(): """Test escaping of double quotes""" test_engine = Engine() assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3' def test_drop_statement(): "Test the creation of drop statements" test_engine = Engine() assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename"
"""Tests for the EcoData Retriever""" from StringIO import StringIO from engine import Engine from table import Table def test_escape_single_quotes(): """Test escaping of single quotes""" test_engine = Engine() assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'" def test_escape_double_quotes(): """Test escaping of double quotes""" test_engine = Engine() assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3' def test_drop_statement(): "Test the creation of drop statements" test_engine = Engine() assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" def test_auto_get_delimiter_comma(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a,b,c;,d") assert test_engine.table.delimiter == "," def test_auto_get_delimiter_tab(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a\tb\tc\td,") assert test_engine.table.delimiter == "\t" def test_auto_get_delimiter_semicolon(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a;b;c;,d") assert test_engine.table.delimiter == ";"
Add tests of automated identification of the delimiter
Add tests of automated identification of the delimiter
Python
mit
bendmorris/retriever,embaldridge/retriever,davharris/retriever,goelakash/retriever,embaldridge/retriever,henrykironde/deletedret,davharris/retriever,bendmorris/retriever,davharris/retriever,bendmorris/retriever,embaldridge/retriever,goelakash/retriever,henrykironde/deletedret
"""Tests for the EcoData Retriever""" from StringIO import StringIO from engine import Engine + from table import Table def test_escape_single_quotes(): """Test escaping of single quotes""" test_engine = Engine() assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'" def test_escape_double_quotes(): """Test escaping of double quotes""" test_engine = Engine() assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3' def test_drop_statement(): "Test the creation of drop statements" test_engine = Engine() assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" + def test_auto_get_delimiter_comma(): + """Test if commas are properly detected as delimiter""" + test_engine = Engine() + test_engine.table = Table("test") + test_engine.auto_get_delimiter("a,b,c;,d") + assert test_engine.table.delimiter == "," + + def test_auto_get_delimiter_tab(): + """Test if commas are properly detected as delimiter""" + test_engine = Engine() + test_engine.table = Table("test") + test_engine.auto_get_delimiter("a\tb\tc\td,") + assert test_engine.table.delimiter == "\t" + + def test_auto_get_delimiter_semicolon(): + """Test if commas are properly detected as delimiter""" + test_engine = Engine() + test_engine.table = Table("test") + test_engine.auto_get_delimiter("a;b;c;,d") + assert test_engine.table.delimiter == ";" +
Add tests of automated identification of the delimiter
## Code Before: """Tests for the EcoData Retriever""" from StringIO import StringIO from engine import Engine def test_escape_single_quotes(): """Test escaping of single quotes""" test_engine = Engine() assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'" def test_escape_double_quotes(): """Test escaping of double quotes""" test_engine = Engine() assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3' def test_drop_statement(): "Test the creation of drop statements" test_engine = Engine() assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" ## Instruction: Add tests of automated identification of the delimiter ## Code After: """Tests for the EcoData Retriever""" from StringIO import StringIO from engine import Engine from table import Table def test_escape_single_quotes(): """Test escaping of single quotes""" test_engine = Engine() assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'" def test_escape_double_quotes(): """Test escaping of double quotes""" test_engine = Engine() assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3' def test_drop_statement(): "Test the creation of drop statements" test_engine = Engine() assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" def test_auto_get_delimiter_comma(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a,b,c;,d") assert test_engine.table.delimiter == "," def test_auto_get_delimiter_tab(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a\tb\tc\td,") assert test_engine.table.delimiter == "\t" def test_auto_get_delimiter_semicolon(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a;b;c;,d") assert test_engine.table.delimiter == ";"
... from engine import Engine from table import Table ... assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" def test_auto_get_delimiter_comma(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a,b,c;,d") assert test_engine.table.delimiter == "," def test_auto_get_delimiter_tab(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a\tb\tc\td,") assert test_engine.table.delimiter == "\t" def test_auto_get_delimiter_semicolon(): """Test if commas are properly detected as delimiter""" test_engine = Engine() test_engine.table = Table("test") test_engine.auto_get_delimiter("a;b;c;,d") assert test_engine.table.delimiter == ";" ...
499defc47f0647afda47be8a8a25d04095b07e1b
nn/slmc/accuracy.py
nn/slmc/accuracy.py
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.to_float(correct_prediction))
Use to_float instead of cast
Use to_float instead of cast
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) - return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) + return tf.reduce_mean(tf.to_float(correct_prediction))
Use to_float instead of cast
## Code Before: import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) ## Instruction: Use to_float instead of cast ## Code After: import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.to_float(correct_prediction))
... correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.to_float(correct_prediction)) ...
0d3737aa2d9ecc435bc110cb6c0045d815b57cad
pygelf/tls.py
pygelf/tls.py
from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, cert=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) self.cert = cert def makeSocket(self, timeout=1): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) try: if self.cert is None: wrapped_socket = ssl.wrap_socket(s) else: wrapped_socket = ssl.wrap_socket(s, ca_certs=self.cert, cert_reqs=ssl.CERT_REQUIRED) wrapped_socket.connect((self.host, self.port)) return wrapped_socket except Exception as e: print('SSL socket exception:', e, file=sys.stderr)
from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, validate=False, ca_certs=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) if validate and ca_certs is None: raise ValueError('CA bundle file path must be specified') self.ca_certs = ca_certs self.reqs = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE def makeSocket(self, timeout=1): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) try: wrapped_socket = ssl.wrap_socket(s, ca_certs=self.ca_certs, cert_reqs=self.reqs) wrapped_socket.connect((self.host, self.port)) return wrapped_socket except Exception as e: print('SSL socket exception:', e, file=sys.stderr)
Add parameter 'validate' to TLS handler
Add parameter 'validate' to TLS handler
Python
mit
keeprocking/pygelf,keeprocking/pygelf
from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): - def __init__(self, cert=None, **kwargs): + def __init__(self, validate=False, ca_certs=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) - self.cert = cert + + if validate and ca_certs is None: + raise ValueError('CA bundle file path must be specified') + + self.ca_certs = ca_certs + self.reqs = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE def makeSocket(self, timeout=1): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) try: - if self.cert is None: - wrapped_socket = ssl.wrap_socket(s) - else: - wrapped_socket = ssl.wrap_socket(s, ca_certs=self.cert, cert_reqs=ssl.CERT_REQUIRED) + wrapped_socket = ssl.wrap_socket(s, ca_certs=self.ca_certs, cert_reqs=self.reqs) wrapped_socket.connect((self.host, self.port)) return wrapped_socket except Exception as e: print('SSL socket exception:', e, file=sys.stderr)
Add parameter 'validate' to TLS handler
## Code Before: from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, cert=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) self.cert = cert def makeSocket(self, timeout=1): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) try: if self.cert is None: wrapped_socket = ssl.wrap_socket(s) else: wrapped_socket = ssl.wrap_socket(s, ca_certs=self.cert, cert_reqs=ssl.CERT_REQUIRED) wrapped_socket.connect((self.host, self.port)) return wrapped_socket except Exception as e: print('SSL socket exception:', e, file=sys.stderr) ## Instruction: Add parameter 'validate' to TLS handler ## Code After: from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, validate=False, ca_certs=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) if validate and ca_certs is None: raise ValueError('CA bundle file path must be specified') self.ca_certs = ca_certs self.reqs = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE def makeSocket(self, timeout=1): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(timeout) try: wrapped_socket = ssl.wrap_socket(s, ca_certs=self.ca_certs, cert_reqs=self.reqs) wrapped_socket.connect((self.host, self.port)) return wrapped_socket except Exception as e: print('SSL socket exception:', e, file=sys.stderr)
# ... existing code ... def __init__(self, validate=False, ca_certs=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) if validate and ca_certs is None: raise ValueError('CA bundle file path must be specified') self.ca_certs = ca_certs self.reqs = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE # ... modified code ... try: wrapped_socket = ssl.wrap_socket(s, ca_certs=self.ca_certs, cert_reqs=self.reqs) wrapped_socket.connect((self.host, self.port)) # ... rest of the code ...
3f90d0ec25491eb64f164180139d4baf9ff238a9
libravatar/context_processors.py
libravatar/context_processors.py
import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context["site_name"] = settings.SITE_NAME context["libravatar_version"] = settings.LIBRAVATAR_VERSION context["avatar_url"] = settings.AVATAR_URL context["secure_avatar_url"] = settings.SECURE_AVATAR_URL context["media_url"] = settings.MEDIA_URL context["site_url"] = settings.SITE_URL context["disable_signup"] = settings.DISABLE_SIGNUP context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID context['support_email'] = settings.SUPPORT_EMAIL return context
import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID context['avatar_url'] = settings.AVATAR_URL context['disable_signup'] = settings.DISABLE_SIGNUP context['libravatar_version'] = settings.LIBRAVATAR_VERSION context['media_url'] = settings.MEDIA_URL context['secure_avatar_url'] = settings.SECURE_AVATAR_URL context['site_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
Sort the context list in alphabetical order
Sort the context list in alphabetical order
Python
agpl-3.0
libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar
import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} - context["site_name"] = settings.SITE_NAME - context["libravatar_version"] = settings.LIBRAVATAR_VERSION - context["avatar_url"] = settings.AVATAR_URL - context["secure_avatar_url"] = settings.SECURE_AVATAR_URL - context["media_url"] = settings.MEDIA_URL - context["site_url"] = settings.SITE_URL - context["disable_signup"] = settings.DISABLE_SIGNUP - context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID + context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID + context['avatar_url'] = settings.AVATAR_URL + context['disable_signup'] = settings.DISABLE_SIGNUP + context['libravatar_version'] = settings.LIBRAVATAR_VERSION + context['media_url'] = settings.MEDIA_URL + context['secure_avatar_url'] = settings.SECURE_AVATAR_URL + context['site_name'] = settings.SITE_NAME + context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
Sort the context list in alphabetical order
## Code Before: import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context["site_name"] = settings.SITE_NAME context["libravatar_version"] = settings.LIBRAVATAR_VERSION context["avatar_url"] = settings.AVATAR_URL context["secure_avatar_url"] = settings.SECURE_AVATAR_URL context["media_url"] = settings.MEDIA_URL context["site_url"] = settings.SITE_URL context["disable_signup"] = settings.DISABLE_SIGNUP context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID context['support_email'] = settings.SUPPORT_EMAIL return context ## Instruction: Sort the context list in alphabetical order ## Code After: import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID context['avatar_url'] = settings.AVATAR_URL context['disable_signup'] = settings.DISABLE_SIGNUP context['libravatar_version'] = settings.LIBRAVATAR_VERSION context['media_url'] = settings.MEDIA_URL context['secure_avatar_url'] = settings.SECURE_AVATAR_URL context['site_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
// ... existing code ... context = {} context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID context['avatar_url'] = settings.AVATAR_URL context['disable_signup'] = settings.DISABLE_SIGNUP context['libravatar_version'] = settings.LIBRAVATAR_VERSION context['media_url'] = settings.MEDIA_URL context['secure_avatar_url'] = settings.SECURE_AVATAR_URL context['site_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL // ... rest of the code ...
6dfb0c1ea4fb3d12d14a07d0e831eb32f3b2f340
yaml_argparse.py
yaml_argparse.py
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
Implement creating arguments for multiple strings
Implement creating arguments for multiple strings
Python
mit
krasch/yaml_argparse,krasch/quickargs
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) - # to start with, support only a single parameter - key = list(yaml_data.keys())[0] - value = yaml_data[key] parser = argparse.ArgumentParser() + for key, value in yaml_data.items(): - parser.add_argument("-{}".format(key), default=value) + parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
Implement creating arguments for multiple strings
## Code Before: import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args ## Instruction: Implement creating arguments for multiple strings ## Code After: import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
// ... existing code ... parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() // ... rest of the code ...
5a36bfb8bb8eceab57203387072f3bf492b2a418
src/onixcheck/exeptions.py
src/onixcheck/exeptions.py
class OnixError(Exception): pass
import logging class OnixError(Exception): pass class NullHandler(logging.Handler): """Not in python 2.6 so we use our own""" def emit(self, record): pass def get_logger(logger_name='onixcheck', add_null_handler=True): logger = logging.getLogger(logger_name) if add_null_handler: logger.addHandler(NullHandler()) return logger
Add NullHandler to silence errors when logging without configuration
Add NullHandler to silence errors when logging without configuration
Python
bsd-2-clause
titusz/onixcheck
+ import logging class OnixError(Exception): pass + + class NullHandler(logging.Handler): + """Not in python 2.6 so we use our own""" + + def emit(self, record): + pass + + + def get_logger(logger_name='onixcheck', add_null_handler=True): + logger = logging.getLogger(logger_name) + if add_null_handler: + logger.addHandler(NullHandler()) + return logger +
Add NullHandler to silence errors when logging without configuration
## Code Before: class OnixError(Exception): pass ## Instruction: Add NullHandler to silence errors when logging without configuration ## Code After: import logging class OnixError(Exception): pass class NullHandler(logging.Handler): """Not in python 2.6 so we use our own""" def emit(self, record): pass def get_logger(logger_name='onixcheck', add_null_handler=True): logger = logging.getLogger(logger_name) if add_null_handler: logger.addHandler(NullHandler()) return logger
# ... existing code ... import logging # ... modified code ... pass class NullHandler(logging.Handler): """Not in python 2.6 so we use our own""" def emit(self, record): pass def get_logger(logger_name='onixcheck', add_null_handler=True): logger = logging.getLogger(logger_name) if add_null_handler: logger.addHandler(NullHandler()) return logger # ... rest of the code ...
d635fc9129bc4ccfd5384be6958ae1c14e9916ec
scripts/merge_translations.py
scripts/merge_translations.py
import sys import yaml def main(base_file, new_file, overwrite_language): old = yaml.load(file(base_file).read()) new = yaml.load(file(new_file).read()) assert len(overwrite_language) == 2 for o, n in zip(old, new): if overwrite_language in n['text']: o['text'][overwrite_language] = n['text'][overwrite_language] if o['type'] == 'multiple_choice': for oo, on in zip(o['options'], n['options']): if 'details' in oo and overwrite_language in on['details']: oo['details'][overwrite_language] = on['details'][overwrite_language] sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) if __name__ == '__main__': main(sys.argv[1], sys.argv[2], sys.argv[3])
import sys import yaml def persona(old, new, overwrite_language): old_t = old['translations'] new_t = new['translations'] for key in old_t: if key in new_t and overwrite_language in new_t[key]: old_t[key][overwrite_language] = new_t[key][overwrite_language] def questions(old, new, overwrite_language): for o, n in zip(old, new): if overwrite_language in n['text']: o['text'][overwrite_language] = n['text'][overwrite_language] if overwrite_language in n['explanation']: o['explanation'][overwrite_language] = n['explanation'][overwrite_language] if overwrite_language in n['explanationmore']: o['explanationmore'][overwrite_language] = n['explanationmore'][overwrite_language] if o['type'] == 'multiple_choice': for oo, on in zip(o['options'], n['options']): if 'details' in oo and overwrite_language in on['details']: oo['details'][overwrite_language] = on['details'][overwrite_language] def main(mode, base_file, new_file, overwrite_language): old = yaml.load(file(base_file).read()) new = yaml.load(file(new_file).read()) assert len(overwrite_language) == 2 if mode == 'persona': persona(old, new, overwrite_language) elif mode == 'questions': questions(old, new, overwrite_language) sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) if __name__ == '__main__': persona(*sys.argv)
Add persona merging to translation merge script
Add persona merging to translation merge script
Python
mit
okfde/eucopyright,okfde/eucopyright,okfde/eucopyright
import sys import yaml - def main(base_file, new_file, overwrite_language): - old = yaml.load(file(base_file).read()) - new = yaml.load(file(new_file).read()) + def persona(old, new, overwrite_language): + old_t = old['translations'] + new_t = new['translations'] - assert len(overwrite_language) == 2 + for key in old_t: + if key in new_t and overwrite_language in new_t[key]: + old_t[key][overwrite_language] = new_t[key][overwrite_language] + + def questions(old, new, overwrite_language): for o, n in zip(old, new): if overwrite_language in n['text']: o['text'][overwrite_language] = n['text'][overwrite_language] + if overwrite_language in n['explanation']: + o['explanation'][overwrite_language] = n['explanation'][overwrite_language] + if overwrite_language in n['explanationmore']: + o['explanationmore'][overwrite_language] = n['explanationmore'][overwrite_language] if o['type'] == 'multiple_choice': for oo, on in zip(o['options'], n['options']): if 'details' in oo and overwrite_language in on['details']: oo['details'][overwrite_language] = on['details'][overwrite_language] + + def main(mode, base_file, new_file, overwrite_language): + old = yaml.load(file(base_file).read()) + new = yaml.load(file(new_file).read()) + + assert len(overwrite_language) == 2 + if mode == 'persona': + persona(old, new, overwrite_language) + elif mode == 'questions': + questions(old, new, overwrite_language) + sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) if __name__ == '__main__': - main(sys.argv[1], sys.argv[2], sys.argv[3]) + persona(*sys.argv)
Add persona merging to translation merge script
## Code Before: import sys import yaml def main(base_file, new_file, overwrite_language): old = yaml.load(file(base_file).read()) new = yaml.load(file(new_file).read()) assert len(overwrite_language) == 2 for o, n in zip(old, new): if overwrite_language in n['text']: o['text'][overwrite_language] = n['text'][overwrite_language] if o['type'] == 'multiple_choice': for oo, on in zip(o['options'], n['options']): if 'details' in oo and overwrite_language in on['details']: oo['details'][overwrite_language] = on['details'][overwrite_language] sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) if __name__ == '__main__': main(sys.argv[1], sys.argv[2], sys.argv[3]) ## Instruction: Add persona merging to translation merge script ## Code After: import sys import yaml def persona(old, new, overwrite_language): old_t = old['translations'] new_t = new['translations'] for key in old_t: if key in new_t and overwrite_language in new_t[key]: old_t[key][overwrite_language] = new_t[key][overwrite_language] def questions(old, new, overwrite_language): for o, n in zip(old, new): if overwrite_language in n['text']: o['text'][overwrite_language] = n['text'][overwrite_language] if overwrite_language in n['explanation']: o['explanation'][overwrite_language] = n['explanation'][overwrite_language] if overwrite_language in n['explanationmore']: o['explanationmore'][overwrite_language] = n['explanationmore'][overwrite_language] if o['type'] == 'multiple_choice': for oo, on in zip(o['options'], n['options']): if 'details' in oo and overwrite_language in on['details']: oo['details'][overwrite_language] = on['details'][overwrite_language] def main(mode, base_file, new_file, overwrite_language): old = yaml.load(file(base_file).read()) new = yaml.load(file(new_file).read()) assert len(overwrite_language) == 2 if mode == 'persona': persona(old, new, overwrite_language) elif mode == 'questions': questions(old, new, overwrite_language) sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) if __name__ == '__main__': persona(*sys.argv)
// ... existing code ... def persona(old, new, overwrite_language): old_t = old['translations'] new_t = new['translations'] for key in old_t: if key in new_t and overwrite_language in new_t[key]: old_t[key][overwrite_language] = new_t[key][overwrite_language] def questions(old, new, overwrite_language): for o, n in zip(old, new): // ... modified code ... o['text'][overwrite_language] = n['text'][overwrite_language] if overwrite_language in n['explanation']: o['explanation'][overwrite_language] = n['explanation'][overwrite_language] if overwrite_language in n['explanationmore']: o['explanationmore'][overwrite_language] = n['explanationmore'][overwrite_language] if o['type'] == 'multiple_choice': ... def main(mode, base_file, new_file, overwrite_language): old = yaml.load(file(base_file).read()) new = yaml.load(file(new_file).read()) assert len(overwrite_language) == 2 if mode == 'persona': persona(old, new, overwrite_language) elif mode == 'questions': questions(old, new, overwrite_language) sys.stdout.write(yaml.safe_dump(old, allow_unicode=True, default_flow_style=False, encoding='utf-8', width=10000)) ... if __name__ == '__main__': persona(*sys.argv) // ... rest of the code ...
d7087cb309c028bdd56cf4c605d7c60eac3d4c0c
utils/custom_context.py
utils/custom_context.py
import discord from discord.ext import commands class CustomContext(commands.Context): async def error(self, title: str, description: str = None): em = discord.Embed( title=f":no_entry_sign: {title}", color=discord.Color.dark_red(), description=description, ) await self.send(embed=em) async def success(self, title: str, description: str = None): em = discord.Embed( title=f":white_check_mark: {title}", color=discord.Color.dark_green(), description=description, ) await self.send(embed=em)
import discord from discord.ext import commands class CustomContext(commands.Context): async def error(self, title: str, description: str = None): em = discord.Embed( title=f":no_entry_sign: {title}", color=discord.Color.dark_red(), description=description or '', ) await self.send(embed=em) async def success(self, title: str, description: str = None): em = discord.Embed( title=f":white_check_mark: {title}", color=discord.Color.dark_green(), description=description or '', ) await self.send(embed=em)
Remove 'None' in embed description
Remove 'None' in embed description
Python
mit
Naught0/qtbot
import discord from discord.ext import commands class CustomContext(commands.Context): async def error(self, title: str, description: str = None): em = discord.Embed( title=f":no_entry_sign: {title}", color=discord.Color.dark_red(), - description=description, + description=description or '', ) await self.send(embed=em) async def success(self, title: str, description: str = None): em = discord.Embed( title=f":white_check_mark: {title}", color=discord.Color.dark_green(), - description=description, + description=description or '', ) await self.send(embed=em)
Remove 'None' in embed description
## Code Before: import discord from discord.ext import commands class CustomContext(commands.Context): async def error(self, title: str, description: str = None): em = discord.Embed( title=f":no_entry_sign: {title}", color=discord.Color.dark_red(), description=description, ) await self.send(embed=em) async def success(self, title: str, description: str = None): em = discord.Embed( title=f":white_check_mark: {title}", color=discord.Color.dark_green(), description=description, ) await self.send(embed=em) ## Instruction: Remove 'None' in embed description ## Code After: import discord from discord.ext import commands class CustomContext(commands.Context): async def error(self, title: str, description: str = None): em = discord.Embed( title=f":no_entry_sign: {title}", color=discord.Color.dark_red(), description=description or '', ) await self.send(embed=em) async def success(self, title: str, description: str = None): em = discord.Embed( title=f":white_check_mark: {title}", color=discord.Color.dark_green(), description=description or '', ) await self.send(embed=em)
# ... existing code ... color=discord.Color.dark_red(), description=description or '', ) # ... modified code ... color=discord.Color.dark_green(), description=description or '', ) # ... rest of the code ...
f8d3477dc4a496d648ac6bfd8d26eeacd853200f
src/masterfile/formatters.py
src/masterfile/formatters.py
import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase if number == 0: return digits[0] return __rec_int_to_colid(number, digits) def __rec_int_to_colid(number, digits): base = len(digits) if number < 0: return '' return ( __rec_int_to_colid((number // base) - 1, digits) + digits[number % base])
import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase parts = [] number += 1 # The algorithm works on 1-based input while number > 0: number, mod = divmod(number - 1, len(digits)) parts.insert(0, digits[mod]) return ''.join(parts)
Replace index_to_column_id with iterative fx
Replace index_to_column_id with iterative fx The recursive one was neat but a bit too clever.
Python
mit
njvack/masterfile
import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase + parts = [] + number += 1 # The algorithm works on 1-based input - if number == 0: + while number > 0: - return digits[0] - return __rec_int_to_colid(number, digits) + number, mod = divmod(number - 1, len(digits)) + parts.insert(0, digits[mod]) + return ''.join(parts) - - def __rec_int_to_colid(number, digits): - base = len(digits) - if number < 0: - return '' - - return ( - __rec_int_to_colid((number // base) - 1, digits) + - digits[number % base]) -
Replace index_to_column_id with iterative fx
## Code Before: import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase if number == 0: return digits[0] return __rec_int_to_colid(number, digits) def __rec_int_to_colid(number, digits): base = len(digits) if number < 0: return '' return ( __rec_int_to_colid((number // base) - 1, digits) + digits[number % base]) ## Instruction: Replace index_to_column_id with iterative fx ## Code After: import string def index_to_column_id(number): """ Takes a zero-based index and converts it to a column identifier string such as used in Excel. Examples: 0 => A 25 => Z 26 => AA """ if number < 0 or not isinstance(number, int): raise AttributeError("index_to_column_id requires a non-negative int") digits = string.ascii_uppercase parts = [] number += 1 # The algorithm works on 1-based input while number > 0: number, mod = divmod(number - 1, len(digits)) parts.insert(0, digits[mod]) return ''.join(parts)
// ... existing code ... digits = string.ascii_uppercase parts = [] number += 1 # The algorithm works on 1-based input while number > 0: number, mod = divmod(number - 1, len(digits)) parts.insert(0, digits[mod]) return ''.join(parts) // ... rest of the code ...
4921d58775faa65423fac321ef68f065b2499813
experiments/hydrotrend-uq-1/plot_results.py
experiments/hydrotrend-uq-1/plot_results.py
from dakota_utils.read import read_tabular from dakota_utils.plot import plot_samples, plot_irregular_surface tab_file = 'dakota.dat' tab_data = read_tabular(tab_file) plot_samples(tab_data, \ outfile='dakota-hydrotrend-dace-1-lhs-samples.png') plot_irregular_surface(tab_data, response_index=-2, \ title='HydroTrend: Mean Qs(T,P)', \ outfile='dakota-hydrotrend-dace-1-Qs_mean.png') plot_irregular_surface(tab_data, response_index=-1, \ title='HydroTrend: Stdev Qs(T,P)', \ outfile='dakota-hydrotrend-dace-1-Qs_stdev.png')
from dakota_utils.read import read_tabular from dakota_utils.plot import plot_samples, plot_irregular_surface from dakota_utils.convert import has_interface_column, strip_interface_column tab_file = 'dakota.dat' if has_interface_column(tab_file): strip_interface_column(tab_file) tab_data = read_tabular(tab_file) plot_samples(tab_data, \ outfile='dakota-hydrotrend-uq-1-lhs-samples.png') plot_irregular_surface(tab_data, response_index=-2, \ title='HydroTrend: Mean Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_mean.png') plot_irregular_surface(tab_data, response_index=-1, \ title='HydroTrend: Stdev Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_stdev.png')
Update script for Dakota 6.1 tabular output file
Update script for Dakota 6.1 tabular output file
Python
mit
mcflugen/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments
from dakota_utils.read import read_tabular from dakota_utils.plot import plot_samples, plot_irregular_surface + from dakota_utils.convert import has_interface_column, strip_interface_column tab_file = 'dakota.dat' + if has_interface_column(tab_file): + strip_interface_column(tab_file) tab_data = read_tabular(tab_file) plot_samples(tab_data, \ - outfile='dakota-hydrotrend-dace-1-lhs-samples.png') + outfile='dakota-hydrotrend-uq-1-lhs-samples.png') plot_irregular_surface(tab_data, response_index=-2, \ - title='HydroTrend: Mean Qs(T,P)', \ + title='HydroTrend: Mean Q(T,P)', \ - outfile='dakota-hydrotrend-dace-1-Qs_mean.png') + outfile='dakota-hydrotrend-uq-1-Q_mean.png') plot_irregular_surface(tab_data, response_index=-1, \ - title='HydroTrend: Stdev Qs(T,P)', \ + title='HydroTrend: Stdev Q(T,P)', \ - outfile='dakota-hydrotrend-dace-1-Qs_stdev.png') + outfile='dakota-hydrotrend-uq-1-Q_stdev.png')
Update script for Dakota 6.1 tabular output file
## Code Before: from dakota_utils.read import read_tabular from dakota_utils.plot import plot_samples, plot_irregular_surface tab_file = 'dakota.dat' tab_data = read_tabular(tab_file) plot_samples(tab_data, \ outfile='dakota-hydrotrend-dace-1-lhs-samples.png') plot_irregular_surface(tab_data, response_index=-2, \ title='HydroTrend: Mean Qs(T,P)', \ outfile='dakota-hydrotrend-dace-1-Qs_mean.png') plot_irregular_surface(tab_data, response_index=-1, \ title='HydroTrend: Stdev Qs(T,P)', \ outfile='dakota-hydrotrend-dace-1-Qs_stdev.png') ## Instruction: Update script for Dakota 6.1 tabular output file ## Code After: from dakota_utils.read import read_tabular from dakota_utils.plot import plot_samples, plot_irregular_surface from dakota_utils.convert import has_interface_column, strip_interface_column tab_file = 'dakota.dat' if has_interface_column(tab_file): strip_interface_column(tab_file) tab_data = read_tabular(tab_file) plot_samples(tab_data, \ outfile='dakota-hydrotrend-uq-1-lhs-samples.png') plot_irregular_surface(tab_data, response_index=-2, \ title='HydroTrend: Mean Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_mean.png') plot_irregular_surface(tab_data, response_index=-1, \ title='HydroTrend: Stdev Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_stdev.png')
// ... existing code ... from dakota_utils.plot import plot_samples, plot_irregular_surface from dakota_utils.convert import has_interface_column, strip_interface_column // ... modified code ... tab_file = 'dakota.dat' if has_interface_column(tab_file): strip_interface_column(tab_file) tab_data = read_tabular(tab_file) ... plot_samples(tab_data, \ outfile='dakota-hydrotrend-uq-1-lhs-samples.png') ... plot_irregular_surface(tab_data, response_index=-2, \ title='HydroTrend: Mean Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_mean.png') ... plot_irregular_surface(tab_data, response_index=-1, \ title='HydroTrend: Stdev Q(T,P)', \ outfile='dakota-hydrotrend-uq-1-Q_stdev.png') // ... rest of the code ...
08d838e87bd92dacbbbfe31b19c628b9d3b271a8
src/plone.example/plone/example/todo.py
src/plone.example/plone/example/todo.py
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
Set default values for fields
Python
bsd-2-clause
plone/plone.server,plone/plone.server
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", + default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", + default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
## Code Before: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass ## Instruction: Set default values for fields ## Code After: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
// ... existing code ... description=u"It's a title", default=u'' ) // ... modified code ... description=u"Has the task been completed?", default=False ) // ... rest of the code ...
938043259eefdec21994489d68b1cf737618ba34
test/test_conversion.py
test/test_conversion.py
import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" actual_result = main.TileLine('w').line expected_result = ' ' self.assertEqual(actual_result, expected_result)
"""Tests for conversion module""" import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('a5') expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) def test_alg_search_good_input_f7(self): """Input with 'f7'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('f7') expected_result = ('f7', 'kb7', 'kb2') self.assertEqual(actual_result, expected_result) def test_alg_search_nonexistant(self): """Input which does not exist""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.alg_search, 'f99') def test_desc_search_good_white(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn3', 'white') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_good_black(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn6', 'black') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_nonexistant(self): """Input with good value""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
Add tests for NotationConverter methods
Add tests for NotationConverter methods
Python
mit
blairck/chess_notation
+ """Tests for conversion module""" + import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" - actual_result = main.TileLine('w').line - expected_result = ' ' + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('a5') + expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) + + def test_alg_search_good_input_f7(self): + """Input with 'f7'""" + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('f7') + expected_result = ('f7', 'kb7', 'kb2') + self.assertEqual(actual_result, expected_result) + + def test_alg_search_nonexistant(self): + """Input which does not exist""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.alg_search, 'f99') + + def test_desc_search_good_white(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn3', 'white') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_good_black(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn6', 'black') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_nonexistant(self): + """Input with good value""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white') +
Add tests for NotationConverter methods
## Code Before: import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" actual_result = main.TileLine('w').line expected_result = ' ' self.assertEqual(actual_result, expected_result) ## Instruction: Add tests for NotationConverter methods ## Code After: """Tests for conversion module""" import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('a5') expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) def test_alg_search_good_input_f7(self): """Input with 'f7'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('f7') expected_result = ('f7', 'kb7', 'kb2') self.assertEqual(actual_result, expected_result) def test_alg_search_nonexistant(self): """Input which does not exist""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.alg_search, 'f99') def test_desc_search_good_white(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn3', 'white') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_good_black(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn6', 'black') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_nonexistant(self): """Input with good value""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
// ... existing code ... """Tests for conversion module""" import unittest // ... modified code ... """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('a5') expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) def test_alg_search_good_input_f7(self): """Input with 'f7'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('f7') expected_result = ('f7', 'kb7', 'kb2') self.assertEqual(actual_result, expected_result) def test_alg_search_nonexistant(self): """Input which does not exist""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.alg_search, 'f99') def test_desc_search_good_white(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn3', 'white') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_good_black(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn6', 'black') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_nonexistant(self): """Input with good value""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white') // ... rest of the code ...
a95f6806ab4e591cfb404624631306932fd69e85
ninja/__init__.py
ninja/__init__.py
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data if platform.system().lower() == "darwin": DATA = os.path.join(DATA, 'CMake.app', 'Contents') BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
Fix lookup of ninja executable on MacOSX
ninja: Fix lookup of ninja executable on MacOSX
Python
apache-2.0
scikit-build/ninja-python-distributions
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data - if platform.system().lower() == "darwin": - DATA = os.path.join(DATA, 'CMake.app', 'Contents') - BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
Fix lookup of ninja executable on MacOSX
## Code Before: import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data if platform.system().lower() == "darwin": DATA = os.path.join(DATA, 'CMake.app', 'Contents') BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:])) ## Instruction: Fix lookup of ninja executable on MacOSX ## Code After: import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
# ... existing code ... BIN_DIR = os.path.join(DATA, 'bin') # ... rest of the code ...
bf006aa3dc8ee331eccb4abd8244a134949c8cc0
bawebauth/apps/bawebauth/fields.py
bawebauth/apps/bawebauth/fields.py
from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def get_internal_type(self): return "PositiveBigIntegerField" def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
Fix tests by removing obsolete internal field type declaration
Fix tests by removing obsolete internal field type declaration
Python
mit
mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth
from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False - - def get_internal_type(self): - return "PositiveBigIntegerField" def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
Fix tests by removing obsolete internal field type declaration
## Code Before: from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def get_internal_type(self): return "PositiveBigIntegerField" def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass ## Instruction: Fix tests by removing obsolete internal field type declaration ## Code After: from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
// ... existing code ... empty_strings_allowed = False // ... rest of the code ...
4051794670ec252cb972ed0c8cd1a5203e8a8de4
amplpy/amplpython/__init__.py
amplpy/amplpython/__init__.py
import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
Fix 'ImportError: DLL load failed'
Fix 'ImportError: DLL load failed'
Python
bsd-3-clause
ampl/amplpy,ampl/amplpy,ampl/amplpy
import os import sys import ctypes import platform if platform.system() == 'Windows': - lib32 = os.path.join(os.path.dirname(__file__), 'lib32') + lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') - lib64 = os.path.join(os.path.dirname(__file__), 'lib64') + lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
Fix 'ImportError: DLL load failed'
## Code Before: import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE ## Instruction: Fix 'ImportError: DLL load failed' ## Code After: import os import sys import ctypes import platform if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
# ... existing code ... if platform.system() == 'Windows': lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32') lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64') from glob import glob # ... rest of the code ...
022d8b992a88fd4c489c068ba57b4b2fcf6dde98
cloudsizzle/studyplanner/completedstudies/models.py
cloudsizzle/studyplanner/completedstudies/models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class CompletedCourse(models.Model): """ Model for completed studies """ student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) name = models.CharField(max_length=100) cr = models.IntegerField() ocr = models.IntegerField() grade = models.CharField(max_length=5) date = models.DateField() teacher = models.CharField(max_length=60) class Teacher(models.Model): """ should be updated for the teachers to combine them with course information """ name = models.CharField(max_length = 30)
from django.db import models from django.contrib.auth.models import User # Create your models here. class CompletedCourse(models.Model): """ Model for completed studies """ student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) name = models.CharField(max_length=100) cr = models.IntegerField(null=True) ocr = models.IntegerField(null=True) grade = models.CharField(max_length=5) date = models.DateField() teacher = models.CharField(max_length=60) class Teacher(models.Model): """ should be updated for the teachers to combine them with course information """ name = models.CharField(max_length = 30)
Allow null values for ocr and cr fields of CompletedCourse
Allow null values for ocr and cr fields of CompletedCourse
Python
mit
jpvanhal/cloudsizzle,jpvanhal/cloudsizzle
from django.db import models from django.contrib.auth.models import User # Create your models here. class CompletedCourse(models.Model): """ Model for completed studies """ - student = models.ForeignKey(User, related_name='completed_courses') + student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) name = models.CharField(max_length=100) - cr = models.IntegerField() + cr = models.IntegerField(null=True) - ocr = models.IntegerField() + ocr = models.IntegerField(null=True) grade = models.CharField(max_length=5) date = models.DateField() teacher = models.CharField(max_length=60) - + class Teacher(models.Model): """ should be updated for the teachers to combine them with course information """ name = models.CharField(max_length = 30)
Allow null values for ocr and cr fields of CompletedCourse
## Code Before: from django.db import models from django.contrib.auth.models import User # Create your models here. class CompletedCourse(models.Model): """ Model for completed studies """ student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) name = models.CharField(max_length=100) cr = models.IntegerField() ocr = models.IntegerField() grade = models.CharField(max_length=5) date = models.DateField() teacher = models.CharField(max_length=60) class Teacher(models.Model): """ should be updated for the teachers to combine them with course information """ name = models.CharField(max_length = 30) ## Instruction: Allow null values for ocr and cr fields of CompletedCourse ## Code After: from django.db import models from django.contrib.auth.models import User # Create your models here. class CompletedCourse(models.Model): """ Model for completed studies """ student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) name = models.CharField(max_length=100) cr = models.IntegerField(null=True) ocr = models.IntegerField(null=True) grade = models.CharField(max_length=5) date = models.DateField() teacher = models.CharField(max_length=60) class Teacher(models.Model): """ should be updated for the teachers to combine them with course information """ name = models.CharField(max_length = 30)
... """ student = models.ForeignKey(User, related_name='completed_courses') code = models.CharField(max_length=11) ... name = models.CharField(max_length=100) cr = models.IntegerField(null=True) ocr = models.IntegerField(null=True) grade = models.CharField(max_length=5) ... teacher = models.CharField(max_length=60) class Teacher(models.Model): ...
86f6191867141d7a7a165b227255d7b4406eb4f4
accounts/utils.py
accounts/utils.py
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
Fix crash on non-logged in users.
Python
agpl-3.0
osamak/student-portal,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city - except ObjectDoesNotExist: + except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
## Code Before: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender ## Instruction: Fix crash on non-logged in users. ## Code After: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
... city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' ...
a6300723150d7d1ff9a58f4f3f1297e0fe2c6f78
css_updater/git/manager.py
css_updater/git/manager.py
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
Check for errors in config
Python
mit
neoliberal/css-updater
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json + try: - self.config: Dict[str, Any] = json.loads(config.read()) + self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] + except KeyError as invalid_json: + print(invalid_json) + except IOError as io_error: + print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
## Code Before: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup() ## Instruction: Check for errors in config ## Code After: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
// ... existing code ... import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) // ... rest of the code ...
8799197befd1f52278a4344fc41ba94cc45c548a
src/you_get/json_output.py
src/you_get/json_output.py
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams try: if ve.audiolang: out['audiolang'] = ve.audiolang except NameError: pass if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
Print audiolang in json output
Print audiolang in json output
Python
mit
zmwangx/you-get,zmwangx/you-get,xyuanmu/you-get,qzane/you-get,qzane/you-get,xyuanmu/you-get,cnbeining/you-get,cnbeining/you-get
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams + try: + if ve.audiolang: + out['audiolang'] = ve.audiolang + except NameError: + pass if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
Print audiolang in json output
## Code Before: import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve) ## Instruction: Print audiolang in json output ## Code After: import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams try: if ve.audiolang: out['audiolang'] = ve.audiolang except NameError: pass if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
... out['streams'] = ve.streams try: if ve.audiolang: out['audiolang'] = ve.audiolang except NameError: pass if pretty_print: ...