commit
stringlengths
40
40
old_file
stringlengths
4
234
new_file
stringlengths
4
234
old_contents
stringlengths
10
3.01k
new_contents
stringlengths
19
3.38k
subject
stringlengths
16
736
message
stringlengths
17
2.63k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
82.6k
config
stringclasses
4 values
content
stringlengths
134
4.41k
fuzzy_diff
stringlengths
29
3.44k
cbfbc7482a19b5d7ddcdb3980bfdf5d1d8487141
Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py
Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py
import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main()
import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing Raises: AssertionError: on invalid input (claimed number of test cases does not match actual number) """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main()
Add description of assertions raised
Add description of assertions raised
Python
cc0-1.0
mschruf/python
python
## Code Before: import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main() ## Instruction: Add description of assertions raised ## Code After: import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing Raises: AssertionError: on invalid input (claimed number of test cases does not match actual number) """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main()
... Returns: Nothing Raises: AssertionError: on invalid input (claimed number of test cases does not match actual number) """ lines = sys.stdin.read().splitlines() ...
b438e3858910eee4f24a5f33858fb039240750cd
get_data_from_twitter.py
get_data_from_twitter.py
import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'hashtags' : [hashtag['text'] for hashtag in data['entities']['hashtags'] ], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
Add support for pulling hash tags
Add support for pulling hash tags
Python
mpl-2.0
aDataAlchemist/election-tweets
python
## Code Before: import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016']) ## Instruction: Add support for pulling hash tags ## Code After: import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'hashtags' : [hashtag['text'] for hashtag in data['entities']['hashtags'] ], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
// ... existing code ... data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'hashtags' : [hashtag['text'] for hashtag in data['entities']['hashtags'] ], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } if len(newdata['urls']) != 0: print json.dumps(newdata) // ... rest of the code ...
7024d3b36176ec11142ee10884936ff329aece49
tests/test_cookiecutter_invocation.py
tests/test_cookiecutter_invocation.py
import os import pytest import subprocess from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(project_dir): subprocess.check_call([ 'python', '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir)
import os import pytest import subprocess import sys from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(monkeypatch, project_dir): monkeypatch.setenv('PYTHONPATH', '.') subprocess.check_call([ sys.executable, '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir)
Set PYTHONPATH and use sys.executable
Set PYTHONPATH and use sys.executable
Python
bsd-3-clause
agconti/cookiecutter,stevepiercy/cookiecutter,sp1rs/cookiecutter,Vauxoo/cookiecutter,hackebrot/cookiecutter,hackebrot/cookiecutter,ramiroluz/cookiecutter,kkujawinski/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,cguardia/cookiecutter,sp1rs/cookiecutter,venumech/cookiecutter,Vauxoo/cookiecutter,dajose/cookiecutter,takeflight/cookiecutter,moi65/cookiecutter,moi65/cookiecutter,audreyr/cookiecutter,michaeljoseph/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,takeflight/cookiecutter,willingc/cookiecutter,christabor/cookiecutter,terryjbates/cookiecutter,kkujawinski/cookiecutter,benthomasson/cookiecutter,audreyr/cookiecutter,atlassian/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,luzfcb/cookiecutter,benthomasson/cookiecutter,christabor/cookiecutter,agconti/cookiecutter,atlassian/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,Springerle/cookiecutter
python
## Code Before: import os import pytest import subprocess from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(project_dir): subprocess.check_call([ 'python', '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir) ## Instruction: Set PYTHONPATH and use sys.executable ## Code After: import os import pytest import subprocess import sys from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(monkeypatch, project_dir): monkeypatch.setenv('PYTHONPATH', '.') subprocess.check_call([ sys.executable, '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir)
... import os import pytest import subprocess import sys from cookiecutter import utils ... return rendered_dir def test_should_invoke_main(monkeypatch, project_dir): monkeypatch.setenv('PYTHONPATH', '.') subprocess.check_call([ sys.executable, '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir) ...
bcc6d199186953b5ae05f7e93bf61c169ac89c77
opps/archives/admin.py
opps/archives/admin.py
from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File @apply_opps_rules('archives') class FileAdmin(AdminViewPermission): search_fields = ['title', 'slug'] raw_id_fields = ['user'] ordering = ('-date_available',) list_filter = ['date_available', 'published'] prepopulated_fields = {"slug": ["title"]} fieldsets = ( (_(u'Identification'), { 'fields': ('site', 'title', 'slug',)}), (_(u'Content'), { 'fields': ('description', 'archive', 'archive_link', 'tags')}), (_(u'Publication'), { 'classes': ('extrapretty'), 'fields': ('published', 'date_available',)}), ) def save_model(self, request, obj, form, change): if not change: obj.user = get_user_model().objects.get(pk=request.user.pk) obj.date_insert = timezone.now() obj.date_update = timezone.now() obj.save() admin.site.register(File, FileAdmin)
from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File @apply_opps_rules('archives') class FileAdmin(AdminViewPermission): search_fields = ['title', 'slug'] raw_id_fields = ['user'] list_display = ['title', 'slug', 'download_link', 'published'] ordering = ('-date_available',) list_filter = ['date_available', 'published'] prepopulated_fields = {"slug": ["title"]} fieldsets = ( (_(u'Identification'), { 'fields': ('site', 'title', 'slug',)}), (_(u'Content'), { 'fields': ('description', 'archive', 'archive_link', 'tags')}), (_(u'Publication'), { 'classes': ('extrapretty'), 'fields': ('published', 'date_available',)}), ) def download_link(self, obj): html = '<a href="{}">{}</a>'.format(obj.archive.url, unicode(_(u'Download'))) return html download_link.short_description = _(u'download') download_link.allow_tags = True def save_model(self, request, obj, form, change): if not change: obj.user = get_user_model().objects.get(pk=request.user.pk) obj.date_insert = timezone.now() obj.date_update = timezone.now() obj.save() admin.site.register(File, FileAdmin)
Add list_display on FileAdmin and download_link def
Add list_display on FileAdmin and download_link def
Python
mit
YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps
python
## Code Before: from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File @apply_opps_rules('archives') class FileAdmin(AdminViewPermission): search_fields = ['title', 'slug'] raw_id_fields = ['user'] ordering = ('-date_available',) list_filter = ['date_available', 'published'] prepopulated_fields = {"slug": ["title"]} fieldsets = ( (_(u'Identification'), { 'fields': ('site', 'title', 'slug',)}), (_(u'Content'), { 'fields': ('description', 'archive', 'archive_link', 'tags')}), (_(u'Publication'), { 'classes': ('extrapretty'), 'fields': ('published', 'date_available',)}), ) def save_model(self, request, obj, form, change): if not change: obj.user = get_user_model().objects.get(pk=request.user.pk) obj.date_insert = timezone.now() obj.date_update = timezone.now() obj.save() admin.site.register(File, FileAdmin) ## Instruction: Add list_display on FileAdmin and download_link def ## Code After: from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File @apply_opps_rules('archives') class FileAdmin(AdminViewPermission): search_fields = ['title', 'slug'] raw_id_fields = ['user'] list_display = ['title', 'slug', 'download_link', 'published'] ordering = ('-date_available',) list_filter = ['date_available', 'published'] prepopulated_fields = {"slug": ["title"]} fieldsets = ( (_(u'Identification'), { 'fields': ('site', 'title', 'slug',)}), (_(u'Content'), { 'fields': ('description', 'archive', 'archive_link', 'tags')}), (_(u'Publication'), { 'classes': ('extrapretty'), 'fields': ('published', 'date_available',)}), ) def download_link(self, obj): html = '<a href="{}">{}</a>'.format(obj.archive.url, unicode(_(u'Download'))) return html download_link.short_description = _(u'download') download_link.allow_tags = True def save_model(self, request, obj, form, change): if not change: obj.user = get_user_model().objects.get(pk=request.user.pk) obj.date_insert = timezone.now() obj.date_update = timezone.now() obj.save() admin.site.register(File, FileAdmin)
... class FileAdmin(AdminViewPermission): search_fields = ['title', 'slug'] raw_id_fields = ['user'] list_display = ['title', 'slug', 'download_link', 'published'] ordering = ('-date_available',) list_filter = ['date_available', 'published'] prepopulated_fields = {"slug": ["title"]} ... 'fields': ('published', 'date_available',)}), ) def download_link(self, obj): html = '<a href="{}">{}</a>'.format(obj.archive.url, unicode(_(u'Download'))) return html download_link.short_description = _(u'download') download_link.allow_tags = True def save_model(self, request, obj, form, change): if not change: obj.user = get_user_model().objects.get(pk=request.user.pk) ...
17d49959fb67a49a1d7078ee2c35f5abb3032b81
helloworld.java
helloworld.java
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } // public > all languages can access // static > will run without making an instance // void > will not return a value // main > method name /** *system > prefdefined class of methods/variables *out > stdout static variable *println > prints that line out */
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } // public > all languages can access // static > will run without making an instance // void > will not return a value // main > method name /** *system > prefdefined class of methods/variables *out > stdout static variable *println > prints that line out */ //Create all the the primitives with different values. C //oncatenate them into a string and print it to the screen so it will print: H3110 w0r1d 2.0 true public class Main2 { public static void main2(String[] args) { byte zero = 0; short a = 3; int b = 1; char d = ' '; float e = 2.0f; boolean f = true; String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f; System.out.println(output); } }
Create all the the primitives with different values
Create all the the primitives with different values
Java
mit
HeyIamJames/LearningJava
java
## Code Before: public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } // public > all languages can access // static > will run without making an instance // void > will not return a value // main > method name /** *system > prefdefined class of methods/variables *out > stdout static variable *println > prints that line out */ ## Instruction: Create all the the primitives with different values ## Code After: public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } // public > all languages can access // static > will run without making an instance // void > will not return a value // main > method name /** *system > prefdefined class of methods/variables *out > stdout static variable *println > prints that line out */ //Create all the the primitives with different values. C //oncatenate them into a string and print it to the screen so it will print: H3110 w0r1d 2.0 true public class Main2 { public static void main2(String[] args) { byte zero = 0; short a = 3; int b = 1; char d = ' '; float e = 2.0f; boolean f = true; String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f; System.out.println(output); } }
... *println > prints that line out */ //Create all the the primitives with different values. C //oncatenate them into a string and print it to the screen so it will print: H3110 w0r1d 2.0 true public class Main2 { public static void main2(String[] args) { byte zero = 0; short a = 3; int b = 1; char d = ' '; float e = 2.0f; boolean f = true; String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f; System.out.println(output); } } ...
b9b03c1f736b38d122baafdd57bbd96657de17af
valuenetwork/api/types/apps.py
valuenetwork/api/types/apps.py
from django.apps import AppConfig import valuenetwork.api.types as types class ApiTypesAppConfig(AppConfig): name = 'valuenetwork.api.types' verbose_name = "ApiTypes" def ready(self): #import pdb; pdb.set_trace() from valuenetwork.api.types.EconomicResource import EconomicResource, EconomicResourceCategory types.EconomicResource = EconomicResource types.EconomicResourceCategory = EconomicResourceCategory from valuenetwork.api.types.Agent import Agent types.Agent = Agent from valuenetwork.api.types.Process import Process types.Process = Process from valuenetwork.api.types.EconomicEvent import EconomicEvent types.EconomicEvent = EconomicEvent super(ApiTypesAppConfig, self).ready()
from django.apps import AppConfig import valuenetwork.api.types as types class ApiTypesAppConfig(AppConfig): name = 'valuenetwork.api.types' verbose_name = "ApiTypes" def ready(self): """ Source of this hack: https://stackoverflow.com/questions/37862725/django-1-9-how-to-import-in-init-py 'Adding from .models import CommentMixin imports CommentMixin so that you can use it inside the ready() method. It does not magically add it to the comment module so that you can access it as comments.CommentMixin You could assign it to the comments module in the ready() method.' from .models import CommentMixin comments.CommentMixin = CommentsMixin """ from valuenetwork.api.types.EconomicResource import EconomicResource, EconomicResourceCategory types.EconomicResource = EconomicResource types.EconomicResourceCategory = EconomicResourceCategory from valuenetwork.api.types.Agent import Agent types.Agent = Agent from valuenetwork.api.types.Process import Process types.Process = Process from valuenetwork.api.types.EconomicEvent import EconomicEvent types.EconomicEvent = EconomicEvent super(ApiTypesAppConfig, self).ready()
Add a comment about the source of the hack
Add a comment about the source of the hack
Python
agpl-3.0
FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork
python
## Code Before: from django.apps import AppConfig import valuenetwork.api.types as types class ApiTypesAppConfig(AppConfig): name = 'valuenetwork.api.types' verbose_name = "ApiTypes" def ready(self): #import pdb; pdb.set_trace() from valuenetwork.api.types.EconomicResource import EconomicResource, EconomicResourceCategory types.EconomicResource = EconomicResource types.EconomicResourceCategory = EconomicResourceCategory from valuenetwork.api.types.Agent import Agent types.Agent = Agent from valuenetwork.api.types.Process import Process types.Process = Process from valuenetwork.api.types.EconomicEvent import EconomicEvent types.EconomicEvent = EconomicEvent super(ApiTypesAppConfig, self).ready() ## Instruction: Add a comment about the source of the hack ## Code After: from django.apps import AppConfig import valuenetwork.api.types as types class ApiTypesAppConfig(AppConfig): name = 'valuenetwork.api.types' verbose_name = "ApiTypes" def ready(self): """ Source of this hack: https://stackoverflow.com/questions/37862725/django-1-9-how-to-import-in-init-py 'Adding from .models import CommentMixin imports CommentMixin so that you can use it inside the ready() method. It does not magically add it to the comment module so that you can access it as comments.CommentMixin You could assign it to the comments module in the ready() method.' from .models import CommentMixin comments.CommentMixin = CommentsMixin """ from valuenetwork.api.types.EconomicResource import EconomicResource, EconomicResourceCategory types.EconomicResource = EconomicResource types.EconomicResourceCategory = EconomicResourceCategory from valuenetwork.api.types.Agent import Agent types.Agent = Agent from valuenetwork.api.types.Process import Process types.Process = Process from valuenetwork.api.types.EconomicEvent import EconomicEvent types.EconomicEvent = EconomicEvent super(ApiTypesAppConfig, self).ready()
# ... existing code ... verbose_name = "ApiTypes" def ready(self): """ Source of this hack: https://stackoverflow.com/questions/37862725/django-1-9-how-to-import-in-init-py 'Adding from .models import CommentMixin imports CommentMixin so that you can use it inside the ready() method. It does not magically add it to the comment module so that you can access it as comments.CommentMixin You could assign it to the comments module in the ready() method.' from .models import CommentMixin comments.CommentMixin = CommentsMixin """ from valuenetwork.api.types.EconomicResource import EconomicResource, EconomicResourceCategory types.EconomicResource = EconomicResource # ... rest of the code ...
f3cdd316f9e0859f77389c68b073134a6076374b
ppp_datamodel_notation_parser/requesthandler.py
ppp_datamodel_notation_parser/requesthandler.py
"""Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(measures, trace, tree): trace = trace + [TraceItem('DatamodelNotationParser', tree, measures)] return Response('en', tree, measures, trace) class RequestHandler: def __init__(self, request): self.request = request def answer(self): if not isinstance(self.request.tree, Sentence): return [] try: forest = parse_triples(self.request.tree.value) except ParseError: return [] measures = {'accuracy': 1, 'relevance': 0.5} return map(partial(tree_to_response, measures, self.request.trace), forest)
"""Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(tree, measures, trace): trace = trace + [TraceItem('DatamodelNotationParser', tree, measures)] return Response('en', tree, measures, trace) class RequestHandler: def __init__(self, request): self.request = request def answer(self): if not isinstance(self.request.tree, Sentence): return [] try: tree = parse_triples(self.request.tree.value) except ParseError: return [] measures = {'accuracy': 1, 'relevance': 0.5} return [tree_to_response(tree, measures, self.request.trace)]
Fix compatibility with new parser.
Fix compatibility with new parser.
Python
mit
ProjetPP/PPP-DatamodelNotationParser,ProjetPP/PPP-DatamodelNotationParser
python
## Code Before: """Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(measures, trace, tree): trace = trace + [TraceItem('DatamodelNotationParser', tree, measures)] return Response('en', tree, measures, trace) class RequestHandler: def __init__(self, request): self.request = request def answer(self): if not isinstance(self.request.tree, Sentence): return [] try: forest = parse_triples(self.request.tree.value) except ParseError: return [] measures = {'accuracy': 1, 'relevance': 0.5} return map(partial(tree_to_response, measures, self.request.trace), forest) ## Instruction: Fix compatibility with new parser. ## Code After: """Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(tree, measures, trace): trace = trace + [TraceItem('DatamodelNotationParser', tree, measures)] return Response('en', tree, measures, trace) class RequestHandler: def __init__(self, request): self.request = request def answer(self): if not isinstance(self.request.tree, Sentence): return [] try: tree = parse_triples(self.request.tree.value) except ParseError: return [] measures = {'accuracy': 1, 'relevance': 0.5} return [tree_to_response(tree, measures, self.request.trace)]
// ... existing code ... from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(tree, measures, trace): trace = trace + [TraceItem('DatamodelNotationParser', tree, measures)] return Response('en', tree, measures, trace) // ... modified code ... if not isinstance(self.request.tree, Sentence): return [] try: tree = parse_triples(self.request.tree.value) except ParseError: return [] measures = {'accuracy': 1, 'relevance': 0.5} return [tree_to_response(tree, measures, self.request.trace)] // ... rest of the code ...
752e6cef31ea124f00eced5699fb225501258148
reversible.py
reversible.py
def is_odd(num): """ Check if an integer is odd. """ if num % 2 != 0: return True else: return False def is_reversible(num): """ Check if a number is reversible given the above definition. """ num_str = str(num) rev_num = int("".join(reversed(num_str))) total = num + rev_num for digit in str(total): if not is_odd(int(digit)): return False return True if __name__ == "__main__": # check some odd and even numbers assert is_odd(1), "1 should be odd" assert not is_odd(2), "2 should not be odd" assert not is_odd(100), "100 should not be odd" assert is_odd(10001), "10001 should be odd" # check the example reversible numbers assert is_reversible(36), "36 should be reversible" assert is_reversible(63), "63 should be reversible" assert is_reversible(409), "409 should be reversible" assert is_reversible(904), "904 should be reversible" print "all assertions passed"
def is_odd(num): """ Check if an integer is odd. """ if num % 2 != 0: return True else: return False def is_reversible(num): """ Check if a number is reversible given the above definition. """ num_str = str(num) rev_str = "".join(reversed(num_str)) if int(rev_str[0]) == 0: return False total = num + int(rev_str) for digit in str(total): if not is_odd(int(digit)): return False return True if __name__ == "__main__": # check some odd and even numbers assert is_odd(1), "1 should be odd" assert not is_odd(2), "2 should not be odd" assert not is_odd(100), "100 should not be odd" assert is_odd(10001), "10001 should be odd" # check the example reversible numbers assert is_reversible(36), "36 should be reversible" assert is_reversible(63), "63 should be reversible" assert is_reversible(409), "409 should be reversible" assert is_reversible(904), "904 should be reversible" assert not is_reversible(10), "10 should not be reversible. (leading zero.)" print "all assertions passed"
Add check for leading zeroes.
Add check for leading zeroes.
Python
mit
smillet15/project-euler
python
## Code Before: def is_odd(num): """ Check if an integer is odd. """ if num % 2 != 0: return True else: return False def is_reversible(num): """ Check if a number is reversible given the above definition. """ num_str = str(num) rev_num = int("".join(reversed(num_str))) total = num + rev_num for digit in str(total): if not is_odd(int(digit)): return False return True if __name__ == "__main__": # check some odd and even numbers assert is_odd(1), "1 should be odd" assert not is_odd(2), "2 should not be odd" assert not is_odd(100), "100 should not be odd" assert is_odd(10001), "10001 should be odd" # check the example reversible numbers assert is_reversible(36), "36 should be reversible" assert is_reversible(63), "63 should be reversible" assert is_reversible(409), "409 should be reversible" assert is_reversible(904), "904 should be reversible" print "all assertions passed" ## Instruction: Add check for leading zeroes. ## Code After: def is_odd(num): """ Check if an integer is odd. """ if num % 2 != 0: return True else: return False def is_reversible(num): """ Check if a number is reversible given the above definition. """ num_str = str(num) rev_str = "".join(reversed(num_str)) if int(rev_str[0]) == 0: return False total = num + int(rev_str) for digit in str(total): if not is_odd(int(digit)): return False return True if __name__ == "__main__": # check some odd and even numbers assert is_odd(1), "1 should be odd" assert not is_odd(2), "2 should not be odd" assert not is_odd(100), "100 should not be odd" assert is_odd(10001), "10001 should be odd" # check the example reversible numbers assert is_reversible(36), "36 should be reversible" assert is_reversible(63), "63 should be reversible" assert is_reversible(409), "409 should be reversible" assert is_reversible(904), "904 should be reversible" assert not is_reversible(10), "10 should not be reversible. (leading zero.)" print "all assertions passed"
# ... existing code ... def is_reversible(num): """ Check if a number is reversible given the above definition. """ num_str = str(num) rev_str = "".join(reversed(num_str)) if int(rev_str[0]) == 0: return False total = num + int(rev_str) for digit in str(total): if not is_odd(int(digit)): # ... modified code ... assert is_reversible(409), "409 should be reversible" assert is_reversible(904), "904 should be reversible" assert not is_reversible(10), "10 should not be reversible. (leading zero.)" print "all assertions passed" # ... rest of the code ...
d3f6edf4589da29a8694b00e797910e2e3f886f5
tools/checkscp.c
tools/checkscp.c
unsigned char scp_processheader(FILE *scpfile) { return 0; } void scp_processtrack(FILE *scpfile, const unsigned char track) { } int main(int argc, char **argv) { unsigned char numtracks; unsigned char track; FILE *fp; if (argc!=2) { printf("Specify .scp on command line\n"); return 1; } fp=fopen(argv[1], "rb"); if (fp==NULL) { printf("Unable to open file\n"); return 2; } numtracks=scp_processheader(fp); for (track=0; track<numtracks; track++) scp_processtrack(fp, track); fclose(fp); return 0; }
struct scp_header header; unsigned char scp_processheader(FILE *scpfile) { fread(&header, 1, sizeof(header), scpfile); if (strncmp((char *)&header.magic, SCP_MAGIC, strlen(SCP_MAGIC))!=0) { printf("Not an SCP file\n"); return 0; } printf("SCP magic detected\n"); printf("Version: %d.%d\n", header.version>>4, header.version&0x0f); printf("Disk type: %d %d\n", header.disktype>>4, header.disktype&0x0f); printf("Revolutions: %d\n", header.revolutions); printf("Tracks: %d to %d\n", header.starttrack, header.endtrack); printf("Flags: 0x%.2x\n", header.flags); printf("Bitcell encoding: %d bits\n", header.bitcellencoding==0?16:header.bitcellencoding); printf("Heads: %d\n", header.heads); printf("Resolution: %dns\n", (header.resolution+1)*SCP_BASE_NS); printf("Checksum: 0x%.8x\n", header.checksum); printf("Tracks in SCP: %d\n", header.endtrack-header.starttrack); return 0; } void scp_processtrack(FILE *scpfile, const unsigned char track) { } int main(int argc, char **argv) { unsigned char numtracks; unsigned char track; FILE *fp; if (argc!=2) { printf("Specify .scp on command line\n"); return 1; } fp=fopen(argv[1], "rb"); if (fp==NULL) { printf("Unable to open file\n"); return 2; } numtracks=scp_processheader(fp); for (track=0; track<numtracks; track++) scp_processtrack(fp, track); fclose(fp); return 0; }
Check magic and output header fields
Check magic and output header fields
C
mit
picosonic/bbc-fdc,picosonic/bbc-fdc
c
## Code Before: unsigned char scp_processheader(FILE *scpfile) { return 0; } void scp_processtrack(FILE *scpfile, const unsigned char track) { } int main(int argc, char **argv) { unsigned char numtracks; unsigned char track; FILE *fp; if (argc!=2) { printf("Specify .scp on command line\n"); return 1; } fp=fopen(argv[1], "rb"); if (fp==NULL) { printf("Unable to open file\n"); return 2; } numtracks=scp_processheader(fp); for (track=0; track<numtracks; track++) scp_processtrack(fp, track); fclose(fp); return 0; } ## Instruction: Check magic and output header fields ## Code After: struct scp_header header; unsigned char scp_processheader(FILE *scpfile) { fread(&header, 1, sizeof(header), scpfile); if (strncmp((char *)&header.magic, SCP_MAGIC, strlen(SCP_MAGIC))!=0) { printf("Not an SCP file\n"); return 0; } printf("SCP magic detected\n"); printf("Version: %d.%d\n", header.version>>4, header.version&0x0f); printf("Disk type: %d %d\n", header.disktype>>4, header.disktype&0x0f); printf("Revolutions: %d\n", header.revolutions); printf("Tracks: %d to %d\n", header.starttrack, header.endtrack); printf("Flags: 0x%.2x\n", header.flags); printf("Bitcell encoding: %d bits\n", header.bitcellencoding==0?16:header.bitcellencoding); printf("Heads: %d\n", header.heads); printf("Resolution: %dns\n", (header.resolution+1)*SCP_BASE_NS); printf("Checksum: 0x%.8x\n", header.checksum); printf("Tracks in SCP: %d\n", header.endtrack-header.starttrack); return 0; } void scp_processtrack(FILE *scpfile, const unsigned char track) { } int main(int argc, char **argv) { unsigned char numtracks; unsigned char track; FILE *fp; if (argc!=2) { printf("Specify .scp on command line\n"); return 1; } fp=fopen(argv[1], "rb"); if (fp==NULL) { printf("Unable to open file\n"); return 2; } numtracks=scp_processheader(fp); for (track=0; track<numtracks; track++) scp_processtrack(fp, track); fclose(fp); return 0; }
... struct scp_header header; unsigned char scp_processheader(FILE *scpfile) { fread(&header, 1, sizeof(header), scpfile); if (strncmp((char *)&header.magic, SCP_MAGIC, strlen(SCP_MAGIC))!=0) { printf("Not an SCP file\n"); return 0; } printf("SCP magic detected\n"); printf("Version: %d.%d\n", header.version>>4, header.version&0x0f); printf("Disk type: %d %d\n", header.disktype>>4, header.disktype&0x0f); printf("Revolutions: %d\n", header.revolutions); printf("Tracks: %d to %d\n", header.starttrack, header.endtrack); printf("Flags: 0x%.2x\n", header.flags); printf("Bitcell encoding: %d bits\n", header.bitcellencoding==0?16:header.bitcellencoding); printf("Heads: %d\n", header.heads); printf("Resolution: %dns\n", (header.resolution+1)*SCP_BASE_NS); printf("Checksum: 0x%.8x\n", header.checksum); printf("Tracks in SCP: %d\n", header.endtrack-header.starttrack); return 0; } ...
e1b5ba70938decbebdc2c4115f2b27b1b8f45ecf
python/mms/__init__.py
python/mms/__init__.py
try: import sympy except ImportError: print("The 'mms' package requires sympy, it can be installed by running " \ "`pip install sympy --user`.") else: from fparser import FParserPrinter, fparser, print_fparser, build_hit, print_hit from moosefunction import MooseFunctionPrinter, moosefunction, print_moose from evaluate import evaluate from runner import run_spatial, run_temporal try: import matplotlib except ImportError: print("The 'mms' package requires matplotlib, it can be installed by running " \ "`pip install matplotlib --user`.") else: from ConvergencePlot import ConvergencePlot
try: import sympy except ImportError: print("The 'mms' package requires sympy, it can be installed by running " \ "`pip install sympy --user`.") else: from fparser import FParserPrinter, fparser, print_fparser, build_hit, print_hit from moosefunction import MooseFunctionPrinter, moosefunction, print_moose from evaluate import evaluate from runner import run_spatial, run_temporal try: import os import matplotlib if not os.getenv('DISPLAY', False): matplotlib.use('Agg') except ImportError: print("The 'mms' package requires matplotlib, it can be installed by running " \ "`pip install matplotlib --user`.") else: from ConvergencePlot import ConvergencePlot
Support offscreen matplotlib plots in mms module
Support offscreen matplotlib plots in mms module (refs #13181)
Python
lgpl-2.1
lindsayad/moose,lindsayad/moose,andrsd/moose,jessecarterMOOSE/moose,harterj/moose,bwspenc/moose,permcody/moose,sapitts/moose,SudiptaBiswas/moose,dschwen/moose,sapitts/moose,lindsayad/moose,jessecarterMOOSE/moose,permcody/moose,SudiptaBiswas/moose,milljm/moose,lindsayad/moose,idaholab/moose,jessecarterMOOSE/moose,idaholab/moose,laagesen/moose,andrsd/moose,laagesen/moose,bwspenc/moose,permcody/moose,bwspenc/moose,jessecarterMOOSE/moose,laagesen/moose,andrsd/moose,YaqiWang/moose,laagesen/moose,sapitts/moose,permcody/moose,nuclear-wizard/moose,bwspenc/moose,sapitts/moose,milljm/moose,lindsayad/moose,nuclear-wizard/moose,nuclear-wizard/moose,harterj/moose,YaqiWang/moose,andrsd/moose,harterj/moose,dschwen/moose,andrsd/moose,sapitts/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,milljm/moose,dschwen/moose,harterj/moose,jessecarterMOOSE/moose,dschwen/moose,idaholab/moose,milljm/moose,nuclear-wizard/moose,harterj/moose,bwspenc/moose,laagesen/moose,idaholab/moose,idaholab/moose,YaqiWang/moose,milljm/moose,dschwen/moose,SudiptaBiswas/moose,YaqiWang/moose
python
## Code Before: try: import sympy except ImportError: print("The 'mms' package requires sympy, it can be installed by running " \ "`pip install sympy --user`.") else: from fparser import FParserPrinter, fparser, print_fparser, build_hit, print_hit from moosefunction import MooseFunctionPrinter, moosefunction, print_moose from evaluate import evaluate from runner import run_spatial, run_temporal try: import matplotlib except ImportError: print("The 'mms' package requires matplotlib, it can be installed by running " \ "`pip install matplotlib --user`.") else: from ConvergencePlot import ConvergencePlot ## Instruction: Support offscreen matplotlib plots in mms module (refs #13181) ## Code After: try: import sympy except ImportError: print("The 'mms' package requires sympy, it can be installed by running " \ "`pip install sympy --user`.") else: from fparser import FParserPrinter, fparser, print_fparser, build_hit, print_hit from moosefunction import MooseFunctionPrinter, moosefunction, print_moose from evaluate import evaluate from runner import run_spatial, run_temporal try: import os import matplotlib if not os.getenv('DISPLAY', False): matplotlib.use('Agg') except ImportError: print("The 'mms' package requires matplotlib, it can be installed by running " \ "`pip install matplotlib --user`.") else: from ConvergencePlot import ConvergencePlot
... from runner import run_spatial, run_temporal try: import os import matplotlib if not os.getenv('DISPLAY', False): matplotlib.use('Agg') except ImportError: print("The 'mms' package requires matplotlib, it can be installed by running " \ ...
4adb686fc15dc3dfdb872157df27b534f1ca7f98
tests/QtUiTools/bug_392.py
tests/QtUiTools/bug_392.py
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main()
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
Extend QUiLoader test to test ui files with custom widgets.
Extend QUiLoader test to test ui files with custom widgets.
Python
lgpl-2.1
PySide/PySide,RobinD42/pyside,M4rtinK/pyside-android,IronManMark20/pyside2,PySide/PySide,RobinD42/pyside,PySide/PySide,RobinD42/pyside,RobinD42/pyside,PySide/PySide,M4rtinK/pyside-android,BadSingleton/pyside2,BadSingleton/pyside2,RobinD42/pyside,enthought/pyside,pankajp/pyside,gbaty/pyside2,M4rtinK/pyside-android,IronManMark20/pyside2,qtproject/pyside-pyside,gbaty/pyside2,M4rtinK/pyside-bb10,PySide/PySide,gbaty/pyside2,pankajp/pyside,pankajp/pyside,M4rtinK/pyside-android,qtproject/pyside-pyside,enthought/pyside,enthought/pyside,M4rtinK/pyside-bb10,IronManMark20/pyside2,pankajp/pyside,M4rtinK/pyside-bb10,RobinD42/pyside,gbaty/pyside2,qtproject/pyside-pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,gbaty/pyside2,enthought/pyside,pankajp/pyside,IronManMark20/pyside2,M4rtinK/pyside-android,qtproject/pyside-pyside,RobinD42/pyside,qtproject/pyside-pyside,M4rtinK/pyside-bb10,M4rtinK/pyside-android,enthought/pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,IronManMark20/pyside2,enthought/pyside,BadSingleton/pyside2,enthought/pyside
python
## Code Before: import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main() ## Instruction: Extend QUiLoader test to test ui files with custom widgets. ## Code After: import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
# ... existing code ... import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): # ... modified code ... result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main() # ... rest of the code ...
74816d4af07808009b89163060f97014b1a20ceb
tests/test_arguments.py
tests/test_arguments.py
import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__hash__'] @property def interface_methods(self): return [getattr(self.argument, f) for f in self.interface_functions] def test_implements_comparison_methods(self): map(ok_, self.interface_methods) class DelegateToValue(object): def test_delegates_all_interface_function_to_the_value_passed_in(self): value_passed_in = MagicMock() value_passed_in.__cmp__ = Mock() argument = self.klass(value_passed_in) for function in self.interface_functions: values_function = getattr(value_passed_in, function) arguments_function = getattr(argument, function) arguments_function(self.valid_comparison_value) values_function.assert_called_once_with(self.valid_comparison_value) class ValueTest(BaseArgument, DelegateToValue, unittest.TestCase): klass = Value @property def valid_comparison_value(self): return 'marv'
import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__hash__', '__nonzero__'] @property def interface_methods(self): return [getattr(self.argument, f) for f in self.interface_functions] def test_implements_comparison_methods(self): map(ok_, self.interface_methods) class DelegateToValue(object): def test_delegates_all_interface_function_to_the_value_passed_in(self): value_passed_in = MagicMock() value_passed_in.__cmp__ = Mock() argument = self.klass(value_passed_in) for function in self.interface_functions: values_function = getattr(value_passed_in, function) arguments_function = getattr(argument, function) arguments_function(self.valid_comparison_value) values_function.assert_called_once_with(self.valid_comparison_value) class ValueTest(BaseArgument, DelegateToValue, unittest.TestCase): klass = Value @property def valid_comparison_value(self): return 'marv'
Enforce that arguments must implement non-zero methods.
Enforce that arguments must implement non-zero methods.
Python
apache-2.0
disqus/gutter,disqus/gutter,kalail/gutter,kalail/gutter,kalail/gutter
python
## Code Before: import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__hash__'] @property def interface_methods(self): return [getattr(self.argument, f) for f in self.interface_functions] def test_implements_comparison_methods(self): map(ok_, self.interface_methods) class DelegateToValue(object): def test_delegates_all_interface_function_to_the_value_passed_in(self): value_passed_in = MagicMock() value_passed_in.__cmp__ = Mock() argument = self.klass(value_passed_in) for function in self.interface_functions: values_function = getattr(value_passed_in, function) arguments_function = getattr(argument, function) arguments_function(self.valid_comparison_value) values_function.assert_called_once_with(self.valid_comparison_value) class ValueTest(BaseArgument, DelegateToValue, unittest.TestCase): klass = Value @property def valid_comparison_value(self): return 'marv' ## Instruction: Enforce that arguments must implement non-zero methods. ## Code After: import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__hash__', '__nonzero__'] @property def interface_methods(self): return [getattr(self.argument, f) for f in self.interface_functions] def test_implements_comparison_methods(self): map(ok_, self.interface_methods) class DelegateToValue(object): def test_delegates_all_interface_function_to_the_value_passed_in(self): value_passed_in = MagicMock() value_passed_in.__cmp__ = Mock() argument = self.klass(value_passed_in) for function in self.interface_functions: values_function = getattr(value_passed_in, function) arguments_function = getattr(argument, function) arguments_function(self.valid_comparison_value) values_function.assert_called_once_with(self.valid_comparison_value) class ValueTest(BaseArgument, DelegateToValue, unittest.TestCase): klass = Value @property def valid_comparison_value(self): return 'marv'
// ... existing code ... @property def interface_functions(self): return ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__hash__', '__nonzero__'] @property def interface_methods(self): // ... rest of the code ...
7a12a49fe84b8e57fd77a9d6fede11316e258251
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/ErrorCodes.java
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/ErrorCodes.java
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core; /** * Error codes that are used in exceptions. * * @author Igor Vinokur */ public class ErrorCodes { private ErrorCodes() { } public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216; public static final int UNABLE_GET_PRIVATE_SSH_KEY = 32068; public static final int UNAUTHORIZED_GIT_OPERATION = 32080; public static final int MERGE_CONFLICT = 32062; public static final int FAILED_CHECKOUT = 32063; public static final int FAILED_CHECKOUT_WITH_START_POINT = 32064; public static final int INIT_COMMIT_WAS_NOT_PERFORMED = 32082; }
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core; /** * Error codes that are used in exceptions. * Defined error codes MUST BE in range <b>15000-32999</b> inclusive. * * @author Igor Vinokur */ public class ErrorCodes { private ErrorCodes() { } public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216; public static final int UNABLE_GET_PRIVATE_SSH_KEY = 32068; public static final int UNAUTHORIZED_GIT_OPERATION = 32080; public static final int MERGE_CONFLICT = 32062; public static final int FAILED_CHECKOUT = 32063; public static final int FAILED_CHECKOUT_WITH_START_POINT = 32064; public static final int INIT_COMMIT_WAS_NOT_PERFORMED = 32082; }
Add comment which defines error codes range
Add comment which defines error codes range
Java
epl-1.0
TypeFox/che,davidfestal/che,cemalkilic/che,TypeFox/che,jonahkichwacoders/che,Mirage20/che,kaloyan-raev/che,cemalkilic/che,ollie314/che,Patricol/che,kaloyan-raev/che,stour/che,bartlomiej-laczkowski/che,snjeza/che,akervern/che,ollie314/che,akervern/che,cemalkilic/che,akervern/che,cemalkilic/che,cdietrich/che,gazarenkov/che-sketch,sudaraka94/che,cemalkilic/che,cemalkilic/che,slemeur/che,cdietrich/che,jonahkichwacoders/che,cdietrich/che,cdietrich/che,gazarenkov/che-sketch,gazarenkov/che-sketch,davidfestal/che,lehmanju/che,kaloyan-raev/che,sudaraka94/che,davidfestal/che,sleshchenko/che,lehmanju/che,davidfestal/che,akervern/che,stour/che,akervern/che,evidolob/che,Mirage20/che,jonahkichwacoders/che,Mirage20/che,bartlomiej-laczkowski/che,gazarenkov/che-sketch,evidolob/che,TypeFox/che,sudaraka94/che,davidfestal/che,lehmanju/che,lehmanju/che,slemeur/che,lehmanju/che,sunix/che,akervern/che,Patricol/che,sunix/che,alexVengrovsk/che,TypeFox/che,evidolob/che,stour/che,cdietrich/che,codenvy/che,sudaraka94/che,snjeza/che,sleshchenko/che,sleshchenko/che,Mirage20/che,jonahkichwacoders/che,Patricol/che,evidolob/che,TypeFox/che,sleshchenko/che,jonahkichwacoders/che,bartlomiej-laczkowski/che,TypeFox/che,codenvy/che,lehmanju/che,snjeza/che,jonahkichwacoders/che,snjeza/che,alexVengrovsk/che,bartlomiej-laczkowski/che,cemalkilic/che,akervern/che,TypeFox/che,davidfestal/che,davidfestal/che,codenvy/che,sunix/che,jonahkichwacoders/che,TypeFox/che,gazarenkov/che-sketch,lehmanju/che,sleshchenko/che,TypeFox/che,sunix/che,alexVengrovsk/che,ollie314/che,cdietrich/che,cemalkilic/che,cdietrich/che,evidolob/che,akervern/che,codenvy/che,Patricol/che,lehmanju/che,gazarenkov/che-sketch,bartlomiej-laczkowski/che,Patricol/che,Patricol/che,sleshchenko/che,gazarenkov/che-sketch,Patricol/che,kaloyan-raev/che,bartlomiej-laczkowski/che,sleshchenko/che,sudaraka94/che,cdietrich/che,sleshchenko/che,slemeur/che,sunix/che,sunix/che,snjeza/che,snjeza/che,bartlomiej-laczkowski/che,alexVengrovsk/che,akervern/che,bartlomiej-laczkowski/che,cemalkilic/che,snjeza/che,sunix/che,sudaraka94/che,ollie314/che,sudaraka94/che,davidfestal/che,Patricol/che,sudaraka94/che,sleshchenko/che,jonahkichwacoders/che,gazarenkov/che-sketch,Patricol/che,sunix/che,kaloyan-raev/che,Mirage20/che,cdietrich/che,jonahkichwacoders/che,Patricol/che,Mirage20/che,bartlomiej-laczkowski/che,ollie314/che,sleshchenko/che,sudaraka94/che,jonahkichwacoders/che,snjeza/che,sudaraka94/che,TypeFox/che,davidfestal/che,slemeur/che,snjeza/che,davidfestal/che,kaloyan-raev/che,lehmanju/che,sunix/che,slemeur/che,gazarenkov/che-sketch,ollie314/che,stour/che
java
## Code Before: /******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core; /** * Error codes that are used in exceptions. * * @author Igor Vinokur */ public class ErrorCodes { private ErrorCodes() { } public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216; public static final int UNABLE_GET_PRIVATE_SSH_KEY = 32068; public static final int UNAUTHORIZED_GIT_OPERATION = 32080; public static final int MERGE_CONFLICT = 32062; public static final int FAILED_CHECKOUT = 32063; public static final int FAILED_CHECKOUT_WITH_START_POINT = 32064; public static final int INIT_COMMIT_WAS_NOT_PERFORMED = 32082; } ## Instruction: Add comment which defines error codes range ## Code After: /******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core; /** * Error codes that are used in exceptions. * Defined error codes MUST BE in range <b>15000-32999</b> inclusive. * * @author Igor Vinokur */ public class ErrorCodes { private ErrorCodes() { } public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216; public static final int UNABLE_GET_PRIVATE_SSH_KEY = 32068; public static final int UNAUTHORIZED_GIT_OPERATION = 32080; public static final int MERGE_CONFLICT = 32062; public static final int FAILED_CHECKOUT = 32063; public static final int FAILED_CHECKOUT_WITH_START_POINT = 32064; public static final int INIT_COMMIT_WAS_NOT_PERFORMED = 32082; }
# ... existing code ... /** * Error codes that are used in exceptions. * Defined error codes MUST BE in range <b>15000-32999</b> inclusive. * * @author Igor Vinokur */ # ... rest of the code ...
2fe315e1753aca8215228091e3a64af057020bc2
celery/loaders/__init__.py
celery/loaders/__init__.py
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Python
bsd-3-clause
frac/celery,WoLpH/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,cbrepo/celery,ask/celery
python
## Code Before: import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf ## Instruction: Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. ## Code After: import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
# ... existing code ... if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader # ... rest of the code ...
d498a9846567e4986ba2a2541b2b4e4719c2c83f
keras/__init__.py
keras/__init__.py
from __future__ import absolute_import from . import activations from . import applications from . import backend from . import datasets from . import engine from . import layers from . import preprocessing from . import utils from . import wrappers from . import callbacks from . import constraints from . import initializers from . import metrics from . import models from . import losses from . import optimizers from . import regularizers __version__ = '2.0.3'
from __future__ import absolute_import from . import activations from . import applications from . import backend from . import datasets from . import engine from . import layers from . import preprocessing from . import utils from . import wrappers from . import callbacks from . import constraints from . import initializers from . import metrics from . import models from . import losses from . import optimizers from . import regularizers # Importable from root because it's technically not a layer from .layers import Input __version__ = '2.0.3'
Make Input importable from root
Make Input importable from root
Python
apache-2.0
keras-team/keras,keras-team/keras
python
## Code Before: from __future__ import absolute_import from . import activations from . import applications from . import backend from . import datasets from . import engine from . import layers from . import preprocessing from . import utils from . import wrappers from . import callbacks from . import constraints from . import initializers from . import metrics from . import models from . import losses from . import optimizers from . import regularizers __version__ = '2.0.3' ## Instruction: Make Input importable from root ## Code After: from __future__ import absolute_import from . import activations from . import applications from . import backend from . import datasets from . import engine from . import layers from . import preprocessing from . import utils from . import wrappers from . import callbacks from . import constraints from . import initializers from . import metrics from . import models from . import losses from . import optimizers from . import regularizers # Importable from root because it's technically not a layer from .layers import Input __version__ = '2.0.3'
# ... existing code ... from . import losses from . import optimizers from . import regularizers # Importable from root because it's technically not a layer from .layers import Input __version__ = '2.0.3' # ... rest of the code ...
428fda845c79f70c6e3d64302bbc716da5130625
src/django_richenum/forms/fields.py
src/django_richenum/forms/fields.py
from abc import ABCMeta from abc import abstractmethod from django import forms class _BaseEnumField(forms.TypedChoiceField): __metaclass__ = ABCMeta def __init__(self, enum, *args, **kwargs): self.enum = enum kwargs.setdefault('empty_value', None) if 'choices' in kwargs: raise ValueError('Cannot explicitly supply choices to enum fields.') if 'coerce' in kwargs: raise ValueError('Cannot explicitly supply coercion function to enum fields.') kwargs['choices'] = self.get_choices() kwargs['coerce'] = self.coerce_value super(_BaseEnumField, self).__init__(*args, **kwargs) @abstractmethod def get_choices(self): pass @abstractmethod def coerce_value(self, val): pass class CanonicalEnumField(_BaseEnumField): """ Uses the RichEnum/OrderedRichEnum canonical_name as form field values """ def get_choices(self): return self.enum.choices() def coerce_value(self, name): return self.enum.from_canonical(name) class IndexEnumField(_BaseEnumField): """ Uses the OrderedRichEnum index as form field values """ def get_choices(self): return self.enum.choices(value_field='index') def coerce_value(self, index): return self.enum.from_index(int(index))
from abc import ABCMeta from abc import abstractmethod from django import forms class _BaseEnumField(forms.TypedChoiceField): __metaclass__ = ABCMeta def __init__(self, enum, *args, **kwargs): self.enum = enum kwargs.setdefault('empty_value', None) if 'choices' in kwargs: raise ValueError('Cannot explicitly supply choices to enum fields.') if 'coerce' in kwargs: raise ValueError('Cannot explicitly supply coercion function to enum fields.') kwargs['choices'] = self.get_choices() kwargs['coerce'] = self.coerce_value super(_BaseEnumField, self).__init__(*args, **kwargs) @abstractmethod def get_choices(self): pass @abstractmethod def coerce_value(self, val): pass def run_validators(self, value): # These have to be from a set, so it's hard for me to imagine a useful # custom validator. # The run_validators method in the superclass checks the value against # None, [], {}, etc, which causes warnings in the RichEnum.__eq__ # method... arguably we shouldn't warn in those cases, but for now we # do. pass class CanonicalEnumField(_BaseEnumField): """ Uses the RichEnum/OrderedRichEnum canonical_name as form field values """ def get_choices(self): return self.enum.choices() def coerce_value(self, name): return self.enum.from_canonical(name) class IndexEnumField(_BaseEnumField): """ Uses the OrderedRichEnum index as form field values """ def get_choices(self): return self.enum.choices(value_field='index') def coerce_value(self, index): return self.enum.from_index(int(index))
Make run_validators method a no-op
_BaseEnumField: Make run_validators method a no-op See the comment in this commit-- I can't see value in allowing custom validators on EnumFields and the implementation in the superclass causes warnings in RichEnum.__eq__. Arguably those warnings aren't useful (warning against []/falsy compare). In that case, we can revert this when they're silenced. Alternatively, if we need the warnings and need this functionality, we'd have re-implement the method in the superclass without said check, or live with warnings every time a form containing an EnumField is validated, which sucks.
Python
mit
hearsaycorp/django-richenum,adepue/django-richenum,dhui/django-richenum,asherf/django-richenum,hearsaycorp/django-richenum
python
## Code Before: from abc import ABCMeta from abc import abstractmethod from django import forms class _BaseEnumField(forms.TypedChoiceField): __metaclass__ = ABCMeta def __init__(self, enum, *args, **kwargs): self.enum = enum kwargs.setdefault('empty_value', None) if 'choices' in kwargs: raise ValueError('Cannot explicitly supply choices to enum fields.') if 'coerce' in kwargs: raise ValueError('Cannot explicitly supply coercion function to enum fields.') kwargs['choices'] = self.get_choices() kwargs['coerce'] = self.coerce_value super(_BaseEnumField, self).__init__(*args, **kwargs) @abstractmethod def get_choices(self): pass @abstractmethod def coerce_value(self, val): pass class CanonicalEnumField(_BaseEnumField): """ Uses the RichEnum/OrderedRichEnum canonical_name as form field values """ def get_choices(self): return self.enum.choices() def coerce_value(self, name): return self.enum.from_canonical(name) class IndexEnumField(_BaseEnumField): """ Uses the OrderedRichEnum index as form field values """ def get_choices(self): return self.enum.choices(value_field='index') def coerce_value(self, index): return self.enum.from_index(int(index)) ## Instruction: _BaseEnumField: Make run_validators method a no-op See the comment in this commit-- I can't see value in allowing custom validators on EnumFields and the implementation in the superclass causes warnings in RichEnum.__eq__. Arguably those warnings aren't useful (warning against []/falsy compare). In that case, we can revert this when they're silenced. Alternatively, if we need the warnings and need this functionality, we'd have re-implement the method in the superclass without said check, or live with warnings every time a form containing an EnumField is validated, which sucks. ## Code After: from abc import ABCMeta from abc import abstractmethod from django import forms class _BaseEnumField(forms.TypedChoiceField): __metaclass__ = ABCMeta def __init__(self, enum, *args, **kwargs): self.enum = enum kwargs.setdefault('empty_value', None) if 'choices' in kwargs: raise ValueError('Cannot explicitly supply choices to enum fields.') if 'coerce' in kwargs: raise ValueError('Cannot explicitly supply coercion function to enum fields.') kwargs['choices'] = self.get_choices() kwargs['coerce'] = self.coerce_value super(_BaseEnumField, self).__init__(*args, **kwargs) @abstractmethod def get_choices(self): pass @abstractmethod def coerce_value(self, val): pass def run_validators(self, value): # These have to be from a set, so it's hard for me to imagine a useful # custom validator. # The run_validators method in the superclass checks the value against # None, [], {}, etc, which causes warnings in the RichEnum.__eq__ # method... arguably we shouldn't warn in those cases, but for now we # do. pass class CanonicalEnumField(_BaseEnumField): """ Uses the RichEnum/OrderedRichEnum canonical_name as form field values """ def get_choices(self): return self.enum.choices() def coerce_value(self, name): return self.enum.from_canonical(name) class IndexEnumField(_BaseEnumField): """ Uses the OrderedRichEnum index as form field values """ def get_choices(self): return self.enum.choices(value_field='index') def coerce_value(self, index): return self.enum.from_index(int(index))
... def coerce_value(self, val): pass def run_validators(self, value): # These have to be from a set, so it's hard for me to imagine a useful # custom validator. # The run_validators method in the superclass checks the value against # None, [], {}, etc, which causes warnings in the RichEnum.__eq__ # method... arguably we shouldn't warn in those cases, but for now we # do. pass class CanonicalEnumField(_BaseEnumField): """ ...
94db2b46f8108d0f5e6edc0d65ae20eee40414aa
MdePkg/Include/PiPei.h
MdePkg/Include/PiPei.h
/** @file Root include file for Mde Package SEC, PEIM, PEI_CORE type modules. This is the include file for any module of type PEIM. PEIM modules only use types defined via this include file and can be ported easily to any environment. Copyright (c) 2006 - 2007, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __PI_PEI_H__ #define __PI_PEI_H__ #include <Uefi/UefiBaseType.h> #include <Pi/PiPeiCis.h> #include <Uefi/UefiMultiPhase.h> // // BUGBUG: The EFI_PEI_STARTUP_DESCRIPTOR definition does not follows PI specification. // After enabling PI for Nt32Pkg and tools generate correct autogen for PEI_CORE, // the following structure should be removed at once. // typedef struct { UINTN BootFirmwareVolume; UINTN SizeOfCacheAsRam; EFI_PEI_PPI_DESCRIPTOR *DispatchTable; } EFI_PEI_STARTUP_DESCRIPTOR; #endif
/** @file Root include file for Mde Package SEC, PEIM, PEI_CORE type modules. This is the include file for any module of type PEIM. PEIM modules only use types defined via this include file and can be ported easily to any environment. Copyright (c) 2006 - 2007, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __PI_PEI_H__ #define __PI_PEI_H__ #include <Uefi/UefiBaseType.h> #include <Pi/PiPeiCis.h> #include <Uefi/UefiMultiPhase.h> #endif
Move the EFI_PEI_STARTUP_DESCRIPTOR into IntelFrameworkPkg.
Move the EFI_PEI_STARTUP_DESCRIPTOR into IntelFrameworkPkg. git-svn-id: 5648d1bec6962b0a6d1d1b40eba8cf5cdb62da3d@4120 6f19259b-4bc3-4df7-8a09-765794883524
C
bsd-2-clause
MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2
c
## Code Before: /** @file Root include file for Mde Package SEC, PEIM, PEI_CORE type modules. This is the include file for any module of type PEIM. PEIM modules only use types defined via this include file and can be ported easily to any environment. Copyright (c) 2006 - 2007, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __PI_PEI_H__ #define __PI_PEI_H__ #include <Uefi/UefiBaseType.h> #include <Pi/PiPeiCis.h> #include <Uefi/UefiMultiPhase.h> // // BUGBUG: The EFI_PEI_STARTUP_DESCRIPTOR definition does not follows PI specification. // After enabling PI for Nt32Pkg and tools generate correct autogen for PEI_CORE, // the following structure should be removed at once. // typedef struct { UINTN BootFirmwareVolume; UINTN SizeOfCacheAsRam; EFI_PEI_PPI_DESCRIPTOR *DispatchTable; } EFI_PEI_STARTUP_DESCRIPTOR; #endif ## Instruction: Move the EFI_PEI_STARTUP_DESCRIPTOR into IntelFrameworkPkg. git-svn-id: 5648d1bec6962b0a6d1d1b40eba8cf5cdb62da3d@4120 6f19259b-4bc3-4df7-8a09-765794883524 ## Code After: /** @file Root include file for Mde Package SEC, PEIM, PEI_CORE type modules. This is the include file for any module of type PEIM. PEIM modules only use types defined via this include file and can be ported easily to any environment. Copyright (c) 2006 - 2007, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __PI_PEI_H__ #define __PI_PEI_H__ #include <Uefi/UefiBaseType.h> #include <Pi/PiPeiCis.h> #include <Uefi/UefiMultiPhase.h> #endif
// ... existing code ... #include <Pi/PiPeiCis.h> #include <Uefi/UefiMultiPhase.h> #endif // ... rest of the code ...
380748fe9ee6935d71bb9930bbe4d2ec84cb1a5c
app/src/main/java/com/tuenti/tuentitv/ui/activity/LoadingActivity.java
app/src/main/java/com/tuenti/tuentitv/ui/activity/LoadingActivity.java
package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); new Handler().postDelayed(new Runnable() { @Override public void run() { startMainActivity(); } }, LOADING_TIME_IN_MILLIS); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } }
package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; private Runnable startMainActivity; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); handler = new Handler(); startMainActivity = new Runnable() { @Override public void run() { startMainActivity(); } }; handler.postDelayed(startMainActivity, LOADING_TIME_IN_MILLIS); } @Override public void onBackPressed() { super.onBackPressed(); handler.removeCallbacks(startMainActivity); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } }
Remove start main activity task from handler if back button is pressed during loading process.
Remove start main activity task from handler if back button is pressed during loading process.
Java
apache-2.0
pedrovgs/TuentiTV,kzganesan/TuentiTV,tjose0101/Mano-TV,msdgwzhy6/TuentiTV,SyrineTrabelsi/TuentiTV
java
## Code Before: package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); new Handler().postDelayed(new Runnable() { @Override public void run() { startMainActivity(); } }, LOADING_TIME_IN_MILLIS); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } } ## Instruction: Remove start main activity task from handler if back button is pressed during loading process. ## Code After: package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; private Runnable startMainActivity; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); handler = new Handler(); startMainActivity = new Runnable() { @Override public void run() { startMainActivity(); } }; handler.postDelayed(startMainActivity, LOADING_TIME_IN_MILLIS); } @Override public void onBackPressed() { super.onBackPressed(); handler.removeCallbacks(startMainActivity); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } }
# ... existing code ... @InjectView(R.id.pb_loading) ProgressBar pb_loading; private Runnable startMainActivity; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); handler = new Handler(); startMainActivity = new Runnable() { @Override public void run() { startMainActivity(); } }; handler.postDelayed(startMainActivity, LOADING_TIME_IN_MILLIS); } @Override public void onBackPressed() { super.onBackPressed(); handler.removeCallbacks(startMainActivity); } private void startMainActivity() { # ... rest of the code ...
c02900e7fb8657316fa647f92c4f9ddbcedb2b7c
rma/helpers/formating.py
rma/helpers/formating.py
from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits) def pref_encoding(data): """ Return string with unique words in list with percentage of they frequency :param data: :return str: """ encoding_counted = Counter(data) total = sum(encoding_counted.values()) sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True) return ' / '.join( ["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings]) def make_total_row(source, agg): """ Execute agg column based function for source columns. For example if you need `total` in table data: Examples: src = [[1,1],[1,2],[1,3]] print(make_total_row(src, [sum, min])) >>> [3, 1] :param source: :param agg: :return: """ return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits) def pref_encoding(data, encoding_transform=None): """ Return string with unique words in list with percentage of they frequency :param data: :param encoding_transform: :return str: """ encoding_counted = Counter(data) total = sum(encoding_counted.values()) sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True) return ' / '.join( ["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings]) def make_total_row(source, agg): """ Execute agg column based function for source columns. For example if you need `total` in table data: Examples: src = [[1,1],[1,2],[1,3]] print(make_total_row(src, [sum, min])) >>> [3, 1] :param source: :param agg: :return: """ return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
Add transforming function to pref_encodings
Add transforming function to pref_encodings
Python
mit
gamenet/redis-memory-analyzer
python
## Code Before: from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits) def pref_encoding(data): """ Return string with unique words in list with percentage of they frequency :param data: :return str: """ encoding_counted = Counter(data) total = sum(encoding_counted.values()) sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True) return ' / '.join( ["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings]) def make_total_row(source, agg): """ Execute agg column based function for source columns. For example if you need `total` in table data: Examples: src = [[1,1],[1,2],[1,3]] print(make_total_row(src, [sum, min])) >>> [3, 1] :param source: :param agg: :return: """ return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))] ## Instruction: Add transforming function to pref_encodings ## Code After: from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits) def pref_encoding(data, encoding_transform=None): """ Return string with unique words in list with percentage of they frequency :param data: :param encoding_transform: :return str: """ encoding_counted = Counter(data) total = sum(encoding_counted.values()) sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True) return ' / '.join( ["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings]) def make_total_row(source, agg): """ Execute agg column based function for source columns. For example if you need `total` in table data: Examples: src = [[1,1],[1,2],[1,3]] print(make_total_row(src, [sum, min])) >>> [3, 1] :param source: :param agg: :return: """ return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
... return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits) def pref_encoding(data, encoding_transform=None): """ Return string with unique words in list with percentage of they frequency :param data: :param encoding_transform: :return str: """ encoding_counted = Counter(data) ... sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True) return ' / '.join( ["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings]) def make_total_row(source, agg): ...
69d8ef8c1eba424568158611d45f02bc316c737b
setup.py
setup.py
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='Glue', version='0.1', url='http://glue.github.com/', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites.'), py_modules=['glue'], include_package_data=True, platforms='any', install_requires=[ 'PIL>=1.1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw )
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.1.1', url='https://github.com/jorgebastida/glue', dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites.'), py_modules=['glue'], include_package_data=True, platforms='any', install_requires=[ 'PIL>=1.1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw )
Change the project name to glue, add the new public download_url
Change the project name to glue, add the new public download_url
Python
bsd-3-clause
WillsB3/glue,zhiqinyigu/glue,jorgebastida/glue,dext0r/glue,beni55/glue,jorgebastida/glue,zhiqinyigu/glue,dext0r/glue,WillsB3/glue,beni55/glue
python
## Code Before: try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='Glue', version='0.1', url='http://glue.github.com/', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites.'), py_modules=['glue'], include_package_data=True, platforms='any', install_requires=[ 'PIL>=1.1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw ) ## Instruction: Change the project name to glue, add the new public download_url ## Code After: try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.1.1', url='https://github.com/jorgebastida/glue', dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites.'), py_modules=['glue'], include_package_data=True, platforms='any', install_requires=[ 'PIL>=1.1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw )
# ... existing code ... kw = {'scripts': ['glue.py']} setup( name='glue', version='0.1.1', url='https://github.com/jorgebastida/glue', dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master', license='BSD', author='Jorge Bastida', author_email='[email protected]', # ... rest of the code ...
a479b445c18687827e7913e8b51abd5937848fe8
anybox/buildbot/openerp/build_utils/analyze_oerp_tests.py
anybox/buildbot/openerp/build_utils/analyze_oerp_tests.py
import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1)
import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), 'WARNING no field in model': re.compile('No such field(s) in model'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1)
Add regex to know if one field is use in a model where this field is not declared
Add regex to know if one field is use in a model where this field is not declared
Python
agpl-3.0
anybox/anybox.buildbot.odoo
python
## Code Before: import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1) ## Instruction: Add regex to know if one field is use in a model where this field is not declared ## Code After: import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), 'WARNING no field in model': re.compile('No such field(s) in model'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1)
// ... existing code ... 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), 'WARNING no field in model': re.compile('No such field(s) in model'), } test_log = open(sys.argv[1], 'r') // ... rest of the code ...
4316527ce70c487e9d9ef4dcf333d00ff3d961b3
src/main/java/de/tum/in/www1/artemis/web/rest/TimeResource.java
src/main/java/de/tum/in/www1/artemis/web/rest/TimeResource.java
package de.tum.in.www1.artemis.web.rest; import java.time.Instant; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TimeResource { /** * {@code GET /time}: * @return the current server time as Instant */ @GetMapping(value = "/time", produces = MediaType.TEXT_PLAIN_VALUE) public String time() { return Instant.now().toString(); } }
package de.tum.in.www1.artemis.web.rest; import java.time.Instant; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TimeResource { /** * {@code GET /time}: * @return the current server time as Instant */ @GetMapping("/time") public ResponseEntity<Instant> time() { return ResponseEntity.ok(Instant.now()); } }
Fix "/time" not returning JSON string
Fix "/time" not returning JSON string Signed-off-by: Jan Philip Bernius <[email protected]>
Java
mit
ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS
java
## Code Before: package de.tum.in.www1.artemis.web.rest; import java.time.Instant; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TimeResource { /** * {@code GET /time}: * @return the current server time as Instant */ @GetMapping(value = "/time", produces = MediaType.TEXT_PLAIN_VALUE) public String time() { return Instant.now().toString(); } } ## Instruction: Fix "/time" not returning JSON string Signed-off-by: Jan Philip Bernius <[email protected]> ## Code After: package de.tum.in.www1.artemis.web.rest; import java.time.Instant; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TimeResource { /** * {@code GET /time}: * @return the current server time as Instant */ @GetMapping("/time") public ResponseEntity<Instant> time() { return ResponseEntity.ok(Instant.now()); } }
// ... existing code ... import java.time.Instant; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; // ... modified code ... * {@code GET /time}: * @return the current server time as Instant */ @GetMapping("/time") public ResponseEntity<Instant> time() { return ResponseEntity.ok(Instant.now()); } } // ... rest of the code ...
77813adc0001c96511aa932ced1adc8500b3f280
example/ex-multi05.c
example/ex-multi05.c
// Let's create an array of string_t and register it globaly ARRAY_DEF(vector_string, string_t) #define M_OPL_vector_string_t() ARRAY_OPLIST(vector_string, STRING_OPLIST) int main(void) { // Let's define a new string named str M_LET(str, string_t) // Let's define msg as a vector_array_t M_LET( (msg, STRING_CTE("Hello"), STRING_CTE("C"), STRING_CTE("World!"), STRING_CTE("Let's"), STRING_CTE("discover"), STRING_CTE("M*LIB!")), vector_string_t) { // Iterate over all words of the array msg for M_EACH(word, msg, vector_string_t) { // Cat the current word into the target string string_cat(str, *word); // Also add a space character string_push_back(str, ' '); } // Print the result printf("%s\n", string_get_cstr(str) ); } return 0; }
// Let's create an array of string_t and register it globaly ARRAY_DEF(vector_string, string_t) #define M_OPL_vector_string_t() ARRAY_OPLIST(vector_string, STRING_OPLIST) int main(void) { // Let's define a new string named str M_LET(str, string_t) // Let's define msg as a vector_array_t M_LET( (msg, STRING_CTE("Hello"), STRING_CTE("C"), STRING_CTE("World!"), STRING_CTE("Let's"), STRING_CTE("discover"), STRING_CTE("M*LIB!")), vector_string_t) { // Iterate over all words of the array msg for M_EACH(word, msg, vector_string_t) { // Cat the current word into the target string string_cat(str, *word); // Also add a space character string_push_back(str, ' '); } // Let's define another string and set it to a formatted value. M_LET( (count, "\nTo display this it uses \"vector\" of %zu strings!", vector_string_size(msg)), string_t) { string_cat(str, count); } // Print the result printf("%s\n", string_get_cstr(str) ); } return 0; }
Add example of formatted C string for string in M_LET
Add example of formatted C string for string in M_LET
C
bsd-2-clause
P-p-H-d/mlib,P-p-H-d/mlib
c
## Code Before: // Let's create an array of string_t and register it globaly ARRAY_DEF(vector_string, string_t) #define M_OPL_vector_string_t() ARRAY_OPLIST(vector_string, STRING_OPLIST) int main(void) { // Let's define a new string named str M_LET(str, string_t) // Let's define msg as a vector_array_t M_LET( (msg, STRING_CTE("Hello"), STRING_CTE("C"), STRING_CTE("World!"), STRING_CTE("Let's"), STRING_CTE("discover"), STRING_CTE("M*LIB!")), vector_string_t) { // Iterate over all words of the array msg for M_EACH(word, msg, vector_string_t) { // Cat the current word into the target string string_cat(str, *word); // Also add a space character string_push_back(str, ' '); } // Print the result printf("%s\n", string_get_cstr(str) ); } return 0; } ## Instruction: Add example of formatted C string for string in M_LET ## Code After: // Let's create an array of string_t and register it globaly ARRAY_DEF(vector_string, string_t) #define M_OPL_vector_string_t() ARRAY_OPLIST(vector_string, STRING_OPLIST) int main(void) { // Let's define a new string named str M_LET(str, string_t) // Let's define msg as a vector_array_t M_LET( (msg, STRING_CTE("Hello"), STRING_CTE("C"), STRING_CTE("World!"), STRING_CTE("Let's"), STRING_CTE("discover"), STRING_CTE("M*LIB!")), vector_string_t) { // Iterate over all words of the array msg for M_EACH(word, msg, vector_string_t) { // Cat the current word into the target string string_cat(str, *word); // Also add a space character string_push_back(str, ' '); } // Let's define another string and set it to a formatted value. M_LET( (count, "\nTo display this it uses \"vector\" of %zu strings!", vector_string_size(msg)), string_t) { string_cat(str, count); } // Print the result printf("%s\n", string_get_cstr(str) ); } return 0; }
// ... existing code ... // Also add a space character string_push_back(str, ' '); } // Let's define another string and set it to a formatted value. M_LET( (count, "\nTo display this it uses \"vector\" of %zu strings!", vector_string_size(msg)), string_t) { string_cat(str, count); } // Print the result printf("%s\n", string_get_cstr(str) ); } // ... rest of the code ...
11e2535f75fbfc294361b6dba3ae51cae158fd59
migrations/versions/849170064430_.py
migrations/versions/849170064430_.py
# revision identifiers, used by Alembic. revision = '849170064430' down_revision = 'a63df077051a' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) def downgrade(): op.drop_column('smtpserver', 'enqueue_job')
# revision identifiers, used by Alembic. revision = '849170064430' down_revision = 'a63df077051a' from alembic import op import sqlalchemy as sa def upgrade(): try: op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) except Exception as exx: print("Could not add column 'smtpserver.enqueue_job'") print(exx) def downgrade(): op.drop_column('smtpserver', 'enqueue_job')
Add try-except block to queue migration script
Add try-except block to queue migration script
Python
agpl-3.0
privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea
python
## Code Before: # revision identifiers, used by Alembic. revision = '849170064430' down_revision = 'a63df077051a' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) def downgrade(): op.drop_column('smtpserver', 'enqueue_job') ## Instruction: Add try-except block to queue migration script ## Code After: # revision identifiers, used by Alembic. revision = '849170064430' down_revision = 'a63df077051a' from alembic import op import sqlalchemy as sa def upgrade(): try: op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) except Exception as exx: print("Could not add column 'smtpserver.enqueue_job'") print(exx) def downgrade(): op.drop_column('smtpserver', 'enqueue_job')
// ... existing code ... def upgrade(): try: op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) except Exception as exx: print("Could not add column 'smtpserver.enqueue_job'") print(exx) def downgrade(): // ... rest of the code ...
c35887025a2127a527862e664d1ef3bb5c4f528a
Constants.py
Constants.py
IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
Add some needed IRC numerics
Add some needed IRC numerics
Python
mit
Didero/DideRobot
python
## Code Before: IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1) ## Instruction: Add some needed IRC numerics ## Code After: IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
# ... existing code ... IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1) # ... rest of the code ...
350f3bb3431d451f6bf6f2fac2e696b9122d65a6
setup.py
setup.py
import os import sys from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
"""Setuptools setup.""" from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
Add missing 'boltons' package & clean up
Add missing 'boltons' package & clean up
Python
mit
wcooley/python-gryaml
python
## Code Before: import os import sys from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], ) ## Instruction: Add missing 'boltons' package & clean up ## Code After: """Setuptools setup.""" from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
// ... existing code ... """Setuptools setup.""" from setuptools import setup // ... modified code ... package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ], // ... rest of the code ...
5ea25bc6c72e5c934e56a90c44f8019ad176bb27
comet/utility/test/test_spawn.py
comet/utility/test/test_spawn.py
import sys from twisted.trial import unittest from twisted.python import failure from ..spawn import SpawnCommand class DummyEvent(object): text = "" class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): spawn = SpawnCommand(sys.executable) d = spawn(DummyEvent()) d.addCallback(self.assertEqual, True) return d def test_bad_process(self): spawn = SpawnCommand("/not/a/real/executable") d = spawn(DummyEvent()) d.addErrback(self.assertIsInstance, failure.Failure) return d
import sys from twisted.trial import unittest from twisted.python import failure from twisted.python import util from ..spawn import SpawnCommand class DummyEvent(object): def __init__(self, text=None): self.text = text class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): spawn = SpawnCommand(sys.executable) d = spawn(DummyEvent()) d.addCallback(self.assertEqual, True) return d def test_bad_process(self): spawn = SpawnCommand("/not/a/real/executable") d = spawn(DummyEvent()) d.addErrback(self.assertIsInstance, failure.Failure) return d def test_write_data(self): TEXT = "Test spawn process" def read_data(result): f = open("spawnfile.txt") try: self.assertEqual(f.read(), TEXT) finally: f.close() spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh")) d = spawn(DummyEvent(TEXT)) d.addCallback(read_data) return d
Test that spawned process actually writes data
Test that spawned process actually writes data
Python
bsd-2-clause
jdswinbank/Comet,jdswinbank/Comet
python
## Code Before: import sys from twisted.trial import unittest from twisted.python import failure from ..spawn import SpawnCommand class DummyEvent(object): text = "" class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): spawn = SpawnCommand(sys.executable) d = spawn(DummyEvent()) d.addCallback(self.assertEqual, True) return d def test_bad_process(self): spawn = SpawnCommand("/not/a/real/executable") d = spawn(DummyEvent()) d.addErrback(self.assertIsInstance, failure.Failure) return d ## Instruction: Test that spawned process actually writes data ## Code After: import sys from twisted.trial import unittest from twisted.python import failure from twisted.python import util from ..spawn import SpawnCommand class DummyEvent(object): def __init__(self, text=None): self.text = text class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): spawn = SpawnCommand(sys.executable) d = spawn(DummyEvent()) d.addCallback(self.assertEqual, True) return d def test_bad_process(self): spawn = SpawnCommand("/not/a/real/executable") d = spawn(DummyEvent()) d.addErrback(self.assertIsInstance, failure.Failure) return d def test_write_data(self): TEXT = "Test spawn process" def read_data(result): f = open("spawnfile.txt") try: self.assertEqual(f.read(), TEXT) finally: f.close() spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh")) d = spawn(DummyEvent(TEXT)) d.addCallback(read_data) return d
... from twisted.trial import unittest from twisted.python import failure from twisted.python import util from ..spawn import SpawnCommand class DummyEvent(object): def __init__(self, text=None): self.text = text class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): ... d = spawn(DummyEvent()) d.addErrback(self.assertIsInstance, failure.Failure) return d def test_write_data(self): TEXT = "Test spawn process" def read_data(result): f = open("spawnfile.txt") try: self.assertEqual(f.read(), TEXT) finally: f.close() spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh")) d = spawn(DummyEvent(TEXT)) d.addCallback(read_data) return d ...
7e3b0ab5366756018e3bcaa50843e7d28ab7643c
codemood/common/views.py
codemood/common/views.py
from django.views.generic import TemplateView from commits.forms import RepositoryForm from commits.models import Repository, Commit from social.models import Post class Index(TemplateView): def get_template_names(self): if self.request.user.is_authenticated(): return 'index/authorized.html' else: return 'index/not-authorized.html' def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): if self.request.method == 'POST': repository_form = RepositoryForm(self.request) else: repository_form = RepositoryForm() context['repository_form'] = repository_form #add filtering by user context['git_activity_list'] = Commit.objects.all() context['repositories'] = Repository.objects.all() context['fb_activity_list'] = Post.objects.filter(user=self.request.user).order_by('created') return context
from django.views.generic import TemplateView from commits.forms import RepositoryForm from commits.models import Repository, Commit from social.models import Post class Index(TemplateView): """ Return different view to authenticated and not. """ def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated(): return AuthenticatedIndex.as_view()(self.request) else: return NotAuthenticatedIndex.as_view()(self.request) class AuthenticatedIndex(TemplateView): """ View to authenticated user """ template_name = 'index/authorized.html' def get_context_data(self, **kwargs): context = super(AuthenticatedIndex, self).get_context_data(**kwargs) if self.request.method == 'POST': repository_form = RepositoryForm(self.request) else: repository_form = RepositoryForm() context['repository_form'] = repository_form #add filtering by user context['git_activity_list'] = Commit.objects.all() context['repositories'] = Repository.objects.all() context['fb_activity_list'] = Post.objects.filter(user=self.request.user).order_by('created') return context class NotAuthenticatedIndex(TemplateView): """ View to NOT authenticated user """ template_name = 'index/not-authorized.html'
Split Index view to AuthenticatedIndex view and NotAuthenticatedIndex view.
Split Index view to AuthenticatedIndex view and NotAuthenticatedIndex view.
Python
mit
mindinpanic/codingmood,pavlenko-volodymyr/codingmood,mindinpanic/codingmood,pavlenko-volodymyr/codingmood
python
## Code Before: from django.views.generic import TemplateView from commits.forms import RepositoryForm from commits.models import Repository, Commit from social.models import Post class Index(TemplateView): def get_template_names(self): if self.request.user.is_authenticated(): return 'index/authorized.html' else: return 'index/not-authorized.html' def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): if self.request.method == 'POST': repository_form = RepositoryForm(self.request) else: repository_form = RepositoryForm() context['repository_form'] = repository_form #add filtering by user context['git_activity_list'] = Commit.objects.all() context['repositories'] = Repository.objects.all() context['fb_activity_list'] = Post.objects.filter(user=self.request.user).order_by('created') return context ## Instruction: Split Index view to AuthenticatedIndex view and NotAuthenticatedIndex view. ## Code After: from django.views.generic import TemplateView from commits.forms import RepositoryForm from commits.models import Repository, Commit from social.models import Post class Index(TemplateView): """ Return different view to authenticated and not. """ def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated(): return AuthenticatedIndex.as_view()(self.request) else: return NotAuthenticatedIndex.as_view()(self.request) class AuthenticatedIndex(TemplateView): """ View to authenticated user """ template_name = 'index/authorized.html' def get_context_data(self, **kwargs): context = super(AuthenticatedIndex, self).get_context_data(**kwargs) if self.request.method == 'POST': repository_form = RepositoryForm(self.request) else: repository_form = RepositoryForm() context['repository_form'] = repository_form #add filtering by user context['git_activity_list'] = Commit.objects.all() context['repositories'] = Repository.objects.all() context['fb_activity_list'] = Post.objects.filter(user=self.request.user).order_by('created') return context class NotAuthenticatedIndex(TemplateView): """ View to NOT authenticated user """ template_name = 'index/not-authorized.html'
... from social.models import Post class Index(TemplateView): """ Return different view to authenticated and not. """ def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated(): return AuthenticatedIndex.as_view()(self.request) else: return NotAuthenticatedIndex.as_view()(self.request) class AuthenticatedIndex(TemplateView): """ View to authenticated user """ template_name = 'index/authorized.html' def get_context_data(self, **kwargs): context = super(AuthenticatedIndex, self).get_context_data(**kwargs) if self.request.method == 'POST': repository_form = RepositoryForm(self.request) else: repository_form = RepositoryForm() context['repository_form'] = repository_form #add filtering by user context['git_activity_list'] = Commit.objects.all() context['repositories'] = Repository.objects.all() context['fb_activity_list'] = Post.objects.filter(user=self.request.user).order_by('created') return context class NotAuthenticatedIndex(TemplateView): """ View to NOT authenticated user """ template_name = 'index/not-authorized.html' ...
14398ec42c0d31d577278d8748b0617650f91775
porick/controllers/create.py
porick/controllers/create.py
import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log = logging.getLogger(__name__) class CreateController(BaseController): def quote(self): authorize() c.page = 'new quote' if request.environ['REQUEST_METHOD'] == 'GET': return render('/create/form.mako') elif request.environ['REQUEST_METHOD'] == 'POST': quote_body = request.params.get('quote_body', '') if not quote_body: abort(400) notes = request.params.get('notes', '') tags = request.params.get('tags', '').split(' ') result = create_quote(quote_body, notes, tags) if result: return render('/create/success.mako') else: abort(500) else: abort(400)
import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log = logging.getLogger(__name__) class CreateController(BaseController): def quote(self): authorize() c.page = 'new quote' if request.environ['REQUEST_METHOD'] == 'GET': return render('/create/form.mako') elif request.environ['REQUEST_METHOD'] == 'POST': quote_body = request.params.get('quote_body', '') if not quote_body: abort(400) notes = request.params.get('notes', '') tags = filter(None, request.params.get('tags', '').replace(',', ' ').split(' ')) result = create_quote(quote_body, notes, tags) if result: return render('/create/success.mako') else: abort(500) else: abort(400)
Deal with comma-separated tags lists HNGH
Deal with comma-separated tags lists HNGH
Python
apache-2.0
kopf/porick,kopf/porick,kopf/porick
python
## Code Before: import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log = logging.getLogger(__name__) class CreateController(BaseController): def quote(self): authorize() c.page = 'new quote' if request.environ['REQUEST_METHOD'] == 'GET': return render('/create/form.mako') elif request.environ['REQUEST_METHOD'] == 'POST': quote_body = request.params.get('quote_body', '') if not quote_body: abort(400) notes = request.params.get('notes', '') tags = request.params.get('tags', '').split(' ') result = create_quote(quote_body, notes, tags) if result: return render('/create/success.mako') else: abort(500) else: abort(400) ## Instruction: Deal with comma-separated tags lists HNGH ## Code After: import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log = logging.getLogger(__name__) class CreateController(BaseController): def quote(self): authorize() c.page = 'new quote' if request.environ['REQUEST_METHOD'] == 'GET': return render('/create/form.mako') elif request.environ['REQUEST_METHOD'] == 'POST': quote_body = request.params.get('quote_body', '') if not quote_body: abort(400) notes = request.params.get('notes', '') tags = filter(None, request.params.get('tags', '').replace(',', ' ').split(' ')) result = create_quote(quote_body, notes, tags) if result: return render('/create/success.mako') else: abort(500) else: abort(400)
... if not quote_body: abort(400) notes = request.params.get('notes', '') tags = filter(None, request.params.get('tags', '').replace(',', ' ').split(' ')) result = create_quote(quote_body, notes, tags) if result: ...
215622e070860cb24c032186d768c6b341ad27fb
nemubot.py
nemubot.py
import sys import os import imp import traceback servers = dict() print ("Nemubot ready, my PID is %i!" % (os.getpid())) prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
import sys import os import imp import traceback servers = dict() prompt = __import__ ("prompt") if len(sys.argv) >= 2: for arg in sys.argv[1:]: prompt.load_file(arg, servers) print ("Nemubot ready, my PID is %i!" % (os.getpid())) while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
Load files given in arguments
Load files given in arguments
Python
agpl-3.0
nemunaire/nemubot,nbr23/nemubot,Bobobol/nemubot-1
python
## Code Before: import sys import os import imp import traceback servers = dict() print ("Nemubot ready, my PID is %i!" % (os.getpid())) prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0) ## Instruction: Load files given in arguments ## Code After: import sys import os import imp import traceback servers = dict() prompt = __import__ ("prompt") if len(sys.argv) >= 2: for arg in sys.argv[1:]: prompt.load_file(arg, servers) print ("Nemubot ready, my PID is %i!" % (os.getpid())) while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
// ... existing code ... servers = dict() prompt = __import__ ("prompt") if len(sys.argv) >= 2: for arg in sys.argv[1:]: prompt.load_file(arg, servers) print ("Nemubot ready, my PID is %i!" % (os.getpid())) while prompt.launch(servers): try: imp.reload(prompt) // ... rest of the code ...
2c57f2143e21fa3d006d4e4e2737429fb60b4797
tornado/setup_pg.py
tornado/setup_pg.py
from os.path import expanduser from os import kill import subprocess import sys import time python = expanduser('~/FrameworkBenchmarks/installs/py2/bin/python') cwd = expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.Popen( python + " server.py --port=8080 --postgres=%s --logging=error" % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(["ps", "aux"]).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None,2)[1]) kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
import os import subprocess import sys import time bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py2/bin') python = os.path.expanduser(os.path.join(bin_dir, 'python')) pip = os.path.expanduser(os.path.join(bin_dir, 'pip')) cwd = os.path.expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.call(pip + ' install -r requirements.txt', cwd=cwd, shell=True, stderr=errfile, stdout=logfile) subprocess.Popen( python + ' server.py --port=8080 --postgres=%s --logging=error' % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(['ps', 'aux']).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
Call pip install before running server.
Call pip install before running server.
Python
bsd-3-clause
knewmanTE/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,denkab/FrameworkBenchmarks,testn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,methane/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,joshk/FrameworkBenchmarks,khellang/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zapov/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,grob/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,methane/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,herloct/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Verber/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,torhve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,testn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zloster/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sgml/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,testn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,herloct/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,testn/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,grob/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,valyala/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zloster/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,doom369/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sxend/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,actframework/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,methane/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,joshk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,testn/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Verber/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,torhve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,torhve/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,testn/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,denkab/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,methane/FrameworkBenchmarks,actframework/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,methane/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,methane/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,herloct/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,testn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,khellang/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,joshk/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sxend/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zapov/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zapov/FrameworkBenchmarks,torhve/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sxend/FrameworkBenchmarks,testn/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,valyala/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,methane/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,doom369/FrameworkBenchmarks,torhve/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,grob/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zloster/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jamming/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zapov/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,actframework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sgml/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,testn/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sxend/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,actframework/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,zloster/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,denkab/FrameworkBenchmarks,herloct/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,grob/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sgml/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,khellang/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,sgml/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zloster/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,denkab/FrameworkBenchmarks,doom369/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,valyala/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,actframework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,denkab/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jamming/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,denkab/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,grob/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,actframework/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,grob/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,khellang/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,torhve/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jamming/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,doom369/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,doom369/FrameworkBenchmarks,testn/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,khellang/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,testn/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Verber/FrameworkBenchmarks,torhve/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,valyala/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,methane/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,khellang/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,herloct/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sxend/FrameworkBenchmarks,valyala/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,joshk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Verber/FrameworkBenchmarks,testn/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,grob/FrameworkBenchmarks,sxend/FrameworkBenchmarks,methane/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,grob/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sxend/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,valyala/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,sgml/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,herloct/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sgml/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sgml/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,torhve/FrameworkBenchmarks,joshk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,actframework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,doom369/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,joshk/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,joshk/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jamming/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,grob/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,denkab/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,torhve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,joshk/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Verber/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,valyala/FrameworkBenchmarks,khellang/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,grob/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,joshk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sxend/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,doom369/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Verber/FrameworkBenchmarks,grob/FrameworkBenchmarks,herloct/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,joshk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,testn/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,valyala/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,grob/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,grob/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jamming/FrameworkBenchmarks,testn/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,khellang/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,khellang/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Verber/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,valyala/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,joshk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nathana1/FrameworkBenchmarks
python
## Code Before: from os.path import expanduser from os import kill import subprocess import sys import time python = expanduser('~/FrameworkBenchmarks/installs/py2/bin/python') cwd = expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.Popen( python + " server.py --port=8080 --postgres=%s --logging=error" % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(["ps", "aux"]).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None,2)[1]) kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr) ## Instruction: Call pip install before running server. ## Code After: import os import subprocess import sys import time bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py2/bin') python = os.path.expanduser(os.path.join(bin_dir, 'python')) pip = os.path.expanduser(os.path.join(bin_dir, 'pip')) cwd = os.path.expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.call(pip + ' install -r requirements.txt', cwd=cwd, shell=True, stderr=errfile, stdout=logfile) subprocess.Popen( python + ' server.py --port=8080 --postgres=%s --logging=error' % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(['ps', 'aux']).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
# ... existing code ... import os import subprocess import sys import time bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py2/bin') python = os.path.expanduser(os.path.join(bin_dir, 'python')) pip = os.path.expanduser(os.path.join(bin_dir, 'pip')) cwd = os.path.expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.call(pip + ' install -r requirements.txt', cwd=cwd, shell=True, stderr=errfile, stdout=logfile) subprocess.Popen( python + ' server.py --port=8080 --postgres=%s --logging=error' % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(['ps', 'aux']).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 if __name__ == '__main__': # ... rest of the code ...
424f6c8c1c4b65e04196a568cfe56b77265aa063
kobo/apps/external_integrations/models.py
kobo/apps/external_integrations/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ def _set_cors_field_options(name, bases, attrs): cls = type(name, bases, attrs) # The `cors` field is already defined by `AbstractCorsModel`, but let's # help folks out by giving it a more descriptive name and help text, which # will both appear in the admin interface cors_field = cls._meta.get_field('cors') cors_field.verbose_name = _('allowed origin') cors_field.help_text = _('You must include scheme (http:// or https://)') return cls class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match the host with its scheme. e.g. https://example.com """ cors = models.CharField(max_length=255) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
from django.db import models from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( max_length=255, verbose_name=_('allowed origin'), help_text=_( 'Must contain exactly the URI scheme, host, and port, e.g. ' 'https://example.com:1234. Standard ports (80 for http and 443 ' 'for https) may be omitted.' ) ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
Simplify CORS model and improve wording
Simplify CORS model and improve wording
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
python
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ def _set_cors_field_options(name, bases, attrs): cls = type(name, bases, attrs) # The `cors` field is already defined by `AbstractCorsModel`, but let's # help folks out by giving it a more descriptive name and help text, which # will both appear in the admin interface cors_field = cls._meta.get_field('cors') cors_field.verbose_name = _('allowed origin') cors_field.help_text = _('You must include scheme (http:// or https://)') return cls class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match the host with its scheme. e.g. https://example.com """ cors = models.CharField(max_length=255) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin') ## Instruction: Simplify CORS model and improve wording ## Code After: from django.db import models from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( max_length=255, verbose_name=_('allowed origin'), help_text=_( 'Must contain exactly the URI scheme, host, and port, e.g. ' 'https://example.com:1234. Standard ports (80 for http and 443 ' 'for https) may be omitted.' ) ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
// ... existing code ... from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( max_length=255, verbose_name=_('allowed origin'), help_text=_( 'Must contain exactly the URI scheme, host, and port, e.g. ' 'https://example.com:1234. Standard ports (80 for http and 443 ' 'for https) may be omitted.' ) ) def __str__(self): return self.cors // ... rest of the code ...
cfdeb127608ca2501d6e465fd189f6b8a21c1ad1
include/parrot/global_setup.h
include/parrot/global_setup.h
/* global_setup.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Contains declarations of global data and the functions * that initialize that data. * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_GLOBAL_SETUP_H_GUARD) #define PARROT_GLOBAL_SETUP_H_GUARD #include "parrot/config.h" /* Needed because this might get compiled before pmcs have been built */ void Parrot_PerlUndef_class_init(INTVAL); void Parrot_PerlInt_class_init(INTVAL); void Parrot_PerlNum_class_init(INTVAL); void Parrot_PerlString_class_init(INTVAL); void Parrot_PerlArray_class_init(INTVAL); void Parrot_PerlHash_class_init(INTVAL); void Parrot_ParrotPointer_class_init(INTVAL); void Parrot_IntQueue_class_init(INTVAL); void init_world(void); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
/* global_setup.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Contains declarations of global data and the functions * that initialize that data. * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_GLOBAL_SETUP_H_GUARD) #define PARROT_GLOBAL_SETUP_H_GUARD #include "parrot/config.h" /* Needed because this might get compiled before pmcs have been built */ void Parrot_PerlUndef_class_init(INTVAL); void Parrot_PerlInt_class_init(INTVAL); void Parrot_PerlNum_class_init(INTVAL); void Parrot_PerlString_class_init(INTVAL); void Parrot_Array_class_init(INTVAL); void Parrot_PerlArray_class_init(INTVAL); void Parrot_PerlHash_class_init(INTVAL); void Parrot_ParrotPointer_class_init(INTVAL); void Parrot_IntQueue_class_init(INTVAL); void init_world(void); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
Patch from Jonathan Stowe to prototype Parrot_Array_class_init
Patch from Jonathan Stowe to prototype Parrot_Array_class_init git-svn-id: 6e74a02f85675cec270f5d931b0f6998666294a3@980 d31e2699-5ff4-0310-a27c-f18f2fbe73fe
C
artistic-2.0
ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot
c
## Code Before: /* global_setup.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Contains declarations of global data and the functions * that initialize that data. * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_GLOBAL_SETUP_H_GUARD) #define PARROT_GLOBAL_SETUP_H_GUARD #include "parrot/config.h" /* Needed because this might get compiled before pmcs have been built */ void Parrot_PerlUndef_class_init(INTVAL); void Parrot_PerlInt_class_init(INTVAL); void Parrot_PerlNum_class_init(INTVAL); void Parrot_PerlString_class_init(INTVAL); void Parrot_PerlArray_class_init(INTVAL); void Parrot_PerlHash_class_init(INTVAL); void Parrot_ParrotPointer_class_init(INTVAL); void Parrot_IntQueue_class_init(INTVAL); void init_world(void); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */ ## Instruction: Patch from Jonathan Stowe to prototype Parrot_Array_class_init git-svn-id: 6e74a02f85675cec270f5d931b0f6998666294a3@980 d31e2699-5ff4-0310-a27c-f18f2fbe73fe ## Code After: /* global_setup.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Contains declarations of global data and the functions * that initialize that data. * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_GLOBAL_SETUP_H_GUARD) #define PARROT_GLOBAL_SETUP_H_GUARD #include "parrot/config.h" /* Needed because this might get compiled before pmcs have been built */ void Parrot_PerlUndef_class_init(INTVAL); void Parrot_PerlInt_class_init(INTVAL); void Parrot_PerlNum_class_init(INTVAL); void Parrot_PerlString_class_init(INTVAL); void Parrot_Array_class_init(INTVAL); void Parrot_PerlArray_class_init(INTVAL); void Parrot_PerlHash_class_init(INTVAL); void Parrot_ParrotPointer_class_init(INTVAL); void Parrot_IntQueue_class_init(INTVAL); void init_world(void); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
... void Parrot_PerlInt_class_init(INTVAL); void Parrot_PerlNum_class_init(INTVAL); void Parrot_PerlString_class_init(INTVAL); void Parrot_Array_class_init(INTVAL); void Parrot_PerlArray_class_init(INTVAL); void Parrot_PerlHash_class_init(INTVAL); void Parrot_ParrotPointer_class_init(INTVAL); ...
295cfb4b3d935aff416a8cc5b23d5f0233e338d8
src/main/java/com/nequissimus/java8/OptionalStuff.java
src/main/java/com/nequissimus/java8/OptionalStuff.java
package com.nequissimus.java8; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; final class OptionalStuff { /** * "Expensive" call to an API, used for {Optional#orElseGet} */ static class Fallback implements Supplier<Integer> { public Integer get() { try { Thread.sleep(10_000); } catch (InterruptedException e) {} return 0; } } /** * Function that may return a String or null */ static String randomString() { if (System.currentTimeMillis() % 2 == 0) { return null; } else { return "lasjlkasjdlas"; } } public static void main(String[] args) { final Function<String, Optional<Integer>> len = x -> Optional.of(x.length()); final Optional<String> oStr = Optional.ofNullable(randomString()); final Optional<Integer> oLen = oStr.flatMap(len); System.out.println("Length = " + oLen.orElseGet(new Fallback())); } }
package com.nequissimus.java8; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; final class OptionalStuff { static int expensiveCall() { try { Thread.sleep(10_000); } catch (InterruptedException e) {} return 0; } /** * "Expensive" call to an API, used for {Optional#orElseGet} */ static class Fallback implements Supplier<Integer> { public Integer get() { return expensiveCall(); } } /** * Function that may return a String or null */ static String randomString() { if (System.currentTimeMillis() % 2 == 0) { return null; } else { return "lasjlkasjdlas"; } } public static void main(String[] args) { final Optional<String> oStr = Optional.ofNullable(randomString()); final Optional<Integer> oLen = oStr.map(x -> x.length()); System.out.println("Length = " + oLen.orElseGet(new Fallback())); } /** * Pre-Java 8 with try/catch */ public static void oldWayTry() throws Exception { final String r = randomString(); int l; try { l = r.length(); } catch (Exception e) { l = expensiveCall(); } System.out.println("Length = " + l); } /** * Initialize to "null"-value, then replace with proper value */ public static void oldWayInit() { final String r = randomString(); int l = expensiveCall(); if (r != null) { l = r.length(); } System.out.println("Length = " + l); } /** * Pre-Java 8 with a guard */ public static void oldWayGuard() { final String r = randomString(); int l; if (r != null) { l = r.length(); } else { l = expensiveCall(); } System.out.println("Length = " + l); } }
Use map, instead of flatMap and add 'old' ways of handling it
Use map, instead of flatMap and add 'old' ways of handling it
Java
unlicense
NeQuissimus/Java8
java
## Code Before: package com.nequissimus.java8; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; final class OptionalStuff { /** * "Expensive" call to an API, used for {Optional#orElseGet} */ static class Fallback implements Supplier<Integer> { public Integer get() { try { Thread.sleep(10_000); } catch (InterruptedException e) {} return 0; } } /** * Function that may return a String or null */ static String randomString() { if (System.currentTimeMillis() % 2 == 0) { return null; } else { return "lasjlkasjdlas"; } } public static void main(String[] args) { final Function<String, Optional<Integer>> len = x -> Optional.of(x.length()); final Optional<String> oStr = Optional.ofNullable(randomString()); final Optional<Integer> oLen = oStr.flatMap(len); System.out.println("Length = " + oLen.orElseGet(new Fallback())); } } ## Instruction: Use map, instead of flatMap and add 'old' ways of handling it ## Code After: package com.nequissimus.java8; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; final class OptionalStuff { static int expensiveCall() { try { Thread.sleep(10_000); } catch (InterruptedException e) {} return 0; } /** * "Expensive" call to an API, used for {Optional#orElseGet} */ static class Fallback implements Supplier<Integer> { public Integer get() { return expensiveCall(); } } /** * Function that may return a String or null */ static String randomString() { if (System.currentTimeMillis() % 2 == 0) { return null; } else { return "lasjlkasjdlas"; } } public static void main(String[] args) { final Optional<String> oStr = Optional.ofNullable(randomString()); final Optional<Integer> oLen = oStr.map(x -> x.length()); System.out.println("Length = " + oLen.orElseGet(new Fallback())); } /** * Pre-Java 8 with try/catch */ public static void oldWayTry() throws Exception { final String r = randomString(); int l; try { l = r.length(); } catch (Exception e) { l = expensiveCall(); } System.out.println("Length = " + l); } /** * Initialize to "null"-value, then replace with proper value */ public static void oldWayInit() { final String r = randomString(); int l = expensiveCall(); if (r != null) { l = r.length(); } System.out.println("Length = " + l); } /** * Pre-Java 8 with a guard */ public static void oldWayGuard() { final String r = randomString(); int l; if (r != null) { l = r.length(); } else { l = expensiveCall(); } System.out.println("Length = " + l); } }
// ... existing code ... import java.util.function.Supplier; final class OptionalStuff { static int expensiveCall() { try { Thread.sleep(10_000); } catch (InterruptedException e) {} return 0; } /** * "Expensive" call to an API, used for {Optional#orElseGet} */ static class Fallback implements Supplier<Integer> { public Integer get() { return expensiveCall(); } } // ... modified code ... } public static void main(String[] args) { final Optional<String> oStr = Optional.ofNullable(randomString()); final Optional<Integer> oLen = oStr.map(x -> x.length()); System.out.println("Length = " + oLen.orElseGet(new Fallback())); } /** * Pre-Java 8 with try/catch */ public static void oldWayTry() throws Exception { final String r = randomString(); int l; try { l = r.length(); } catch (Exception e) { l = expensiveCall(); } System.out.println("Length = " + l); } /** * Initialize to "null"-value, then replace with proper value */ public static void oldWayInit() { final String r = randomString(); int l = expensiveCall(); if (r != null) { l = r.length(); } System.out.println("Length = " + l); } /** * Pre-Java 8 with a guard */ public static void oldWayGuard() { final String r = randomString(); int l; if (r != null) { l = r.length(); } else { l = expensiveCall(); } System.out.println("Length = " + l); } } // ... rest of the code ...
dc2f69deae316dd40652765b9df0bf526f662f29
cuke4duke/src/main/java/cuke4duke/internal/jvmclass/GuiceFactory.java
cuke4duke/src/main/java/cuke4duke/internal/jvmclass/GuiceFactory.java
package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addInstance(Object instance) { } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } }
package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import cuke4duke.StepMother; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addStepMother(StepMother mother) { // Not supported yet. } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } }
Rename method to inject step mother
Rename method to inject step mother
Java
mit
sghill/cucumber-jvm,brasmusson/cucumber-jvm,nilswloka/cucumber-jvm,torbjornvatn/cuke4duke,bartkeizer/cucumber-jvm,dkowis/cucumber-jvm,sghill/cucumber-jvm,flaviuratiu/cucumber-jvm,nilswloka/cucumber-jvm,demos74dx/cucumber-jvm,joansmith/cucumber-jvm,cucumber/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,chrishowejones/cucumber-jvm,paoloambrosio/cucumber-jvm,PeterDG/cucumberPro,NickCharsley/cucumber-jvm,NickCharsley/cucumber-jvm,sventorben/cucumber-jvm,demos74dx/cucumber-jvm,chrishowejones/cucumber-jvm,NickCharsley/cucumber-jvm,bartkeizer/cucumber-jvm,ushkinaz/cucumber-jvm,guardian/cucumber-jvm,jasonh-n-austin/cucumber-jvm,danielwegener/cucumber-jvm,hcawebdevelopment/cucumber-jvm,PhilipMay/cucumber-jvm,dkowis/cucumber-jvm,andyb-ge/cucumber-jvm,cucumber/cuke4duke,DPUkyle/cucumber-jvm,DPUkyle/cucumber-jvm,guardian/cucumber-jvm,andyb-ge/cucumber-jvm,ppotanin/cucumber-jvm,demos74dx/cucumber-jvm,paoloambrosio/cucumber-jvm,jc-hdez83/cuke4duke,chiranjith/cucumber-jvm,hcawebdevelopment/cucumber-jvm,PhilipMay/cucumber-jvm,danielwegener/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,ppotanin/cucumber-jvm,dkowis/cucumber-jvm,jasonh-n-austin/cucumber-jvm,PhilipMay/cucumber-jvm,guardian/cucumber-jvm,goushijie/cucumber-jvm,PeterDG/cucumberPro,DPUkyle/cucumber-jvm,hcawebdevelopment/cucumber-jvm,goushijie/cucumber-jvm,chrishowejones/cucumber-jvm,danielwegener/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,sventorben/cucumber-jvm,bartkeizer/cucumber-jvm,HendrikSP/cucumber-jvm,andyb-ge/cucumber-jvm,flaviuratiu/cucumber-jvm,NickCharsley/cucumber-jvm,Draeval/cucumber-jvm,hcawebdevelopment/cucumber-jvm,assilzm/cucumber-groovy-seeyon,goushijie/cucumber-jvm,demos74dx/cucumber-jvm,danielwegener/cucumber-jvm,andyb-ge/cucumber-jvm,cucumber/cucumber-jvm,brasmusson/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,ArishArbab/cucumber-jvm,sghill/cucumber-jvm,danielwegener/cucumber-jvm,flaviuratiu/cucumber-jvm,flaviuratiu/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,HendrikSP/cucumber-jvm,chiranjith/cucumber-jvm,dkowis/cucumber-jvm,Draeval/cucumber-jvm,jc-hdez83/cuke4duke,cucumber/cuke4duke,VivaceVivo/cucumber-mod-DI,cucumber/cucumber-jvm,nilswloka/cucumber-jvm,hcawebdevelopment/cucumber-jvm,andyb-ge/cucumber-jvm,guardian/cucumber-jvm,nilswloka/cucumber-jvm,chrishowejones/cucumber-jvm,chiranjith/cucumber-jvm,paoloambrosio/cucumber-jvm,PeterDG/cucumberPro,ArishArbab/cucumber-jvm,ArishArbab/cucumber-jvm,chiranjith/cucumber-jvm,joansmith/cucumber-jvm,ushkinaz/cucumber-jvm,cucumber/cuke4duke,PeterDG/cucumberPro,demos74dx/cucumber-jvm,sghill/cucumber-jvm,sghill/cucumber-jvm,PeterDG/cucumberPro,joansmith/cucumber-jvm,bartkeizer/cucumber-jvm,dkowis/cucumber-jvm,flaviuratiu/cucumber-jvm,Draeval/cucumber-jvm,danielwegener/cucumber-jvm,ushkinaz/cucumber-jvm,ArishArbab/cucumber-jvm,Draeval/cucumber-jvm,VivaceVivo/cucumber-mod-DI,jasonh-n-austin/cucumber-jvm,bartkeizer/cucumber-jvm,joansmith/cucumber-jvm,goushijie/cucumber-jvm,sventorben/cucumber-jvm,ppotanin/cucumber-jvm,chrishowejones/cucumber-jvm,ArishArbab/cucumber-jvm,torbjornvatn/cuke4duke,joansmith/cucumber-jvm,dkowis/cucumber-jvm,jc-hdez83/cuke4duke,sventorben/cucumber-jvm,DPUkyle/cucumber-jvm,HendrikSP/cucumber-jvm,brasmusson/cucumber-jvm,ArishArbab/cucumber-jvm,paoloambrosio/cucumber-jvm,flaviuratiu/cucumber-jvm,brasmusson/cucumber-jvm,ushkinaz/cucumber-jvm,goushijie/cucumber-jvm,ushkinaz/cucumber-jvm,HendrikSP/cucumber-jvm,ppotanin/cucumber-jvm,sventorben/cucumber-jvm,DPUkyle/cucumber-jvm,jasonh-n-austin/cucumber-jvm,VivaceVivo/cucumber-mod-DI,joansmith/cucumber-jvm,chiranjith/cucumber-jvm,nilswloka/cucumber-jvm,torbjornvatn/cuke4duke,andyb-ge/cucumber-jvm,PeterDG/cucumberPro,cucumber/cucumber-jvm,PhilipMay/cucumber-jvm,DPUkyle/cucumber-jvm,sghill/cucumber-jvm,Draeval/cucumber-jvm,goushijie/cucumber-jvm,cucumber/cucumber-jvm,Draeval/cucumber-jvm,hcawebdevelopment/cucumber-jvm,NickCharsley/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,VivaceVivo/cucumber-mod-DI,ushkinaz/cucumber-jvm,VivaceVivo/cucumber-mod-DI,ppotanin/cucumber-jvm,jc-hdez83/cuke4duke,HendrikSP/cucumber-jvm,ppotanin/cucumber-jvm,chrishowejones/cucumber-jvm,bartkeizer/cucumber-jvm,NickCharsley/cucumber-jvm,sventorben/cucumber-jvm,chiranjith/cucumber-jvm,brasmusson/cucumber-jvm,assilzm/cucumber-groovy-seeyon,HendrikSP/cucumber-jvm,demos74dx/cucumber-jvm,guardian/cucumber-jvm
java
## Code Before: package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addInstance(Object instance) { } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } } ## Instruction: Rename method to inject step mother ## Code After: package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import cuke4duke.StepMother; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addStepMother(StepMother mother) { // Not supported yet. } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } }
# ... existing code ... import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import cuke4duke.StepMother; /** * @author Henning Jensen # ... modified code ... classes.add(clazz); } public void addStepMother(StepMother mother) { // Not supported yet. } public void createObjects() { # ... rest of the code ...
5fd855f55777b2ecb0dc9521bee1ee87e27eae17
core/src/main/java/com/zyeeda/framework/cxf/JacksonJsonProvider.java
core/src/main/java/com/zyeeda/framework/cxf/JacksonJsonProvider.java
package com.zyeeda.framework.cxf; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.SerializationConfig.Feature; public class JacksonJsonProvider extends JacksonJaxbJsonProvider { public JacksonJsonProvider() { ObjectMapper m = this._mapperConfig.getConfiguredMapper(); if (m == null) { m = this._mapperConfig.getDefaultMapper(); } m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); m.configure(Feature.FAIL_ON_EMPTY_BEANS, false); } }
package com.zyeeda.framework.cxf; import java.text.SimpleDateFormat; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.SerializationConfig.Feature; public class JacksonJsonProvider extends JacksonJaxbJsonProvider { public JacksonJsonProvider() { ObjectMapper m = this._mapperConfig.getConfiguredMapper(); if (m == null) { m = this._mapperConfig.getDefaultMapper(); } SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")); sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); sc.set(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(sc); /* m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); m.configure(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd"))); */ } }
Make CXF serialize date type in pre-defined format.
Make CXF serialize date type in pre-defined format.
Java
apache-2.0
BGCX262/zyeeda-framework-hg-to-git,BGCX262/zyeeda-framework-hg-to-git
java
## Code Before: package com.zyeeda.framework.cxf; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.SerializationConfig.Feature; public class JacksonJsonProvider extends JacksonJaxbJsonProvider { public JacksonJsonProvider() { ObjectMapper m = this._mapperConfig.getConfiguredMapper(); if (m == null) { m = this._mapperConfig.getDefaultMapper(); } m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); m.configure(Feature.FAIL_ON_EMPTY_BEANS, false); } } ## Instruction: Make CXF serialize date type in pre-defined format. ## Code After: package com.zyeeda.framework.cxf; import java.text.SimpleDateFormat; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.SerializationConfig.Feature; public class JacksonJsonProvider extends JacksonJaxbJsonProvider { public JacksonJsonProvider() { ObjectMapper m = this._mapperConfig.getConfiguredMapper(); if (m == null) { m = this._mapperConfig.getDefaultMapper(); } SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")); sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); sc.set(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(sc); /* m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); m.configure(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd"))); */ } }
// ... existing code ... package com.zyeeda.framework.cxf; import java.text.SimpleDateFormat; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.SerializationConfig.Feature; // ... modified code ... if (m == null) { m = this._mapperConfig.getDefaultMapper(); } SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")); sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); sc.set(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(sc); /* m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); m.configure(Feature.FAIL_ON_EMPTY_BEANS, false); m.setSerializationConfig(m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd"))); */ } } // ... rest of the code ...
76282391f35725ee42ac0671a9a77b68e1f34081
rest_tester/test_info.py
rest_tester/test_info.py
class TestInfo(object): """Read test information from JSON data.""" PATH_API = 'api' PATH_API_URL = 'url' PATH_API_PARAMS = 'params' PATH_API_TIMEOUT = 'timeout' PATH_TESTS = 'tests' DEFAULT_TIME_OUT = 10 @classmethod def read(cls, json_data): """Read test information from JSON data.""" api_data = json_data[cls.PATH_API] url = api_data[cls.PATH_API_URL] params = api_data[cls.PATH_API_PARAMS] if cls.PATH_API_PARAMS in api_data.keys() else {} timeout = api_data[cls.PATH_API_TIMEOUT] if cls.PATH_API_TIMEOUT in api_data.keys() else cls.DEFAULT_TIME_OUT test_cases = json_data[cls.PATH_TESTS] return url, params, timeout, test_cases
class TestInfo(object): """Read test information from JSON data.""" PATH_API = 'api' PATH_API_URL = 'url' PATH_API_PARAMS = 'params' PATH_API_TIMEOUT = 'timeout' PATH_TESTS = 'tests' DEFAULT_TIME_OUT = 10 @classmethod def read(cls, json_data): """Read test information from JSON data.""" """Use get for only 'params' and 'timeout' to raise KeyError if keys do not exist.""" api_data = json_data[cls.PATH_API] url = api_data[cls.PATH_API_URL] params = api_data.get(cls.PATH_API_PARAMS, {}) timeout = api_data.get(cls.PATH_API_TIMEOUT, cls.DEFAULT_TIME_OUT) test_cases = json_data[cls.PATH_TESTS] return url, params, timeout, test_cases
Use get for params and timeout.
Use get for params and timeout.
Python
mit
ridibooks/lightweight-rest-tester,ridibooks/lightweight-rest-tester
python
## Code Before: class TestInfo(object): """Read test information from JSON data.""" PATH_API = 'api' PATH_API_URL = 'url' PATH_API_PARAMS = 'params' PATH_API_TIMEOUT = 'timeout' PATH_TESTS = 'tests' DEFAULT_TIME_OUT = 10 @classmethod def read(cls, json_data): """Read test information from JSON data.""" api_data = json_data[cls.PATH_API] url = api_data[cls.PATH_API_URL] params = api_data[cls.PATH_API_PARAMS] if cls.PATH_API_PARAMS in api_data.keys() else {} timeout = api_data[cls.PATH_API_TIMEOUT] if cls.PATH_API_TIMEOUT in api_data.keys() else cls.DEFAULT_TIME_OUT test_cases = json_data[cls.PATH_TESTS] return url, params, timeout, test_cases ## Instruction: Use get for params and timeout. ## Code After: class TestInfo(object): """Read test information from JSON data.""" PATH_API = 'api' PATH_API_URL = 'url' PATH_API_PARAMS = 'params' PATH_API_TIMEOUT = 'timeout' PATH_TESTS = 'tests' DEFAULT_TIME_OUT = 10 @classmethod def read(cls, json_data): """Read test information from JSON data.""" """Use get for only 'params' and 'timeout' to raise KeyError if keys do not exist.""" api_data = json_data[cls.PATH_API] url = api_data[cls.PATH_API_URL] params = api_data.get(cls.PATH_API_PARAMS, {}) timeout = api_data.get(cls.PATH_API_TIMEOUT, cls.DEFAULT_TIME_OUT) test_cases = json_data[cls.PATH_TESTS] return url, params, timeout, test_cases
# ... existing code ... @classmethod def read(cls, json_data): """Read test information from JSON data.""" """Use get for only 'params' and 'timeout' to raise KeyError if keys do not exist.""" api_data = json_data[cls.PATH_API] url = api_data[cls.PATH_API_URL] params = api_data.get(cls.PATH_API_PARAMS, {}) timeout = api_data.get(cls.PATH_API_TIMEOUT, cls.DEFAULT_TIME_OUT) test_cases = json_data[cls.PATH_TESTS] # ... rest of the code ...
9d2ff18544950e129f5b363af4fa042b067e6830
dashboards/help/guides/urls.py
dashboards/help/guides/urls.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from .views import GuidesView urlpatterns = patterns('', url(r'^$', login_required(GuidesView.as_view()), name='index'))
from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import GuidesView urlpatterns = [ url(r'^$', login_required(GuidesView.as_view()), name='index'), ]
Fix patterns for Django > 1.10
Fix patterns for Django > 1.10 Pike requires Django 1.11 so fix the template pattern import which was not compatible with that version. This fixes: File "/srv/www/openstack-dashboard/openstack_dashboard/dashboards/help/guides/\ urls.py", line 15, in <module> from django.conf.urls import patterns, url ImportError: cannot import name patterns
Python
apache-2.0
SUSE-Cloud/horizon-suse-theme,SUSE-Cloud/horizon-suse-theme
python
## Code Before: from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from .views import GuidesView urlpatterns = patterns('', url(r'^$', login_required(GuidesView.as_view()), name='index')) ## Instruction: Fix patterns for Django > 1.10 Pike requires Django 1.11 so fix the template pattern import which was not compatible with that version. This fixes: File "/srv/www/openstack-dashboard/openstack_dashboard/dashboards/help/guides/\ urls.py", line 15, in <module> from django.conf.urls import patterns, url ImportError: cannot import name patterns ## Code After: from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import GuidesView urlpatterns = [ url(r'^$', login_required(GuidesView.as_view()), name='index'), ]
// ... existing code ... from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import GuidesView urlpatterns = [ url(r'^$', login_required(GuidesView.as_view()), name='index'), ] // ... rest of the code ...
ab49b49f04a3dd9d3a530193798983d540c031d4
touch/inc/touch/touch.h
touch/inc/touch/touch.h
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright 2013 LibreOffice contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_TOUCH_TOUCH_H #define INCLUDED_TOUCH_TOUCH_H #include <config_features.h> #if !HAVE_FEATURE_DESKTOP // Functions to be implemented by the upper/medium layers on // non-desktop touch-based platforms, with the same API on each such // platform. Note that these are just declared here in this header in // the "touch" module, the per-platform implementations are elsewhere. #ifdef __cplusplus extern "C" { #endif void lo_show_keyboard(); void lo_hide_keyboard(); #ifdef __cplusplus } #endif #endif // HAVE_FEATURE_DESKTOP #endif // INCLUDED_TOUCH_TOUCH_H /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright 2013 LibreOffice contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_TOUCH_TOUCH_H #define INCLUDED_TOUCH_TOUCH_H #include <config_features.h> #if !HAVE_FEATURE_DESKTOP // Functions to be implemented by the app-specifc upper or less // app-specific but platform-specific medium layer on touch-based // platforms. The same API is used on each such platform. There are // called from low level LibreOffice code. Note that these are just // declared here in this header in the "touch" module, the // per-platform implementations are elsewhere. #ifdef __cplusplus extern "C" { #endif void lo_show_keyboard(); void lo_hide_keyboard(); // Functions to be implemented in the medium platform-specific layer // to be called from the app-specific UI layer. void lo_keyboard_did_hide(); #ifdef __cplusplus } #endif #endif // HAVE_FEATURE_DESKTOP #endif // INCLUDED_TOUCH_TOUCH_H /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Add lo_keyboard_did_hide() and improve comment
Add lo_keyboard_did_hide() and improve comment Change-Id: I20ae40fa03079d69f7ce9e71fa4ef6264e8d84a4
C
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
c
## Code Before: /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright 2013 LibreOffice contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_TOUCH_TOUCH_H #define INCLUDED_TOUCH_TOUCH_H #include <config_features.h> #if !HAVE_FEATURE_DESKTOP // Functions to be implemented by the upper/medium layers on // non-desktop touch-based platforms, with the same API on each such // platform. Note that these are just declared here in this header in // the "touch" module, the per-platform implementations are elsewhere. #ifdef __cplusplus extern "C" { #endif void lo_show_keyboard(); void lo_hide_keyboard(); #ifdef __cplusplus } #endif #endif // HAVE_FEATURE_DESKTOP #endif // INCLUDED_TOUCH_TOUCH_H /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ ## Instruction: Add lo_keyboard_did_hide() and improve comment Change-Id: I20ae40fa03079d69f7ce9e71fa4ef6264e8d84a4 ## Code After: /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright 2013 LibreOffice contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_TOUCH_TOUCH_H #define INCLUDED_TOUCH_TOUCH_H #include <config_features.h> #if !HAVE_FEATURE_DESKTOP // Functions to be implemented by the app-specifc upper or less // app-specific but platform-specific medium layer on touch-based // platforms. The same API is used on each such platform. There are // called from low level LibreOffice code. Note that these are just // declared here in this header in the "touch" module, the // per-platform implementations are elsewhere. #ifdef __cplusplus extern "C" { #endif void lo_show_keyboard(); void lo_hide_keyboard(); // Functions to be implemented in the medium platform-specific layer // to be called from the app-specific UI layer. void lo_keyboard_did_hide(); #ifdef __cplusplus } #endif #endif // HAVE_FEATURE_DESKTOP #endif // INCLUDED_TOUCH_TOUCH_H /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
... #if !HAVE_FEATURE_DESKTOP // Functions to be implemented by the app-specifc upper or less // app-specific but platform-specific medium layer on touch-based // platforms. The same API is used on each such platform. There are // called from low level LibreOffice code. Note that these are just // declared here in this header in the "touch" module, the // per-platform implementations are elsewhere. #ifdef __cplusplus extern "C" { ... void lo_show_keyboard(); void lo_hide_keyboard(); // Functions to be implemented in the medium platform-specific layer // to be called from the app-specific UI layer. void lo_keyboard_did_hide(); #ifdef __cplusplus } ...
8f14e64701fb26da8e4a614da6129964f29be16d
testapp/testapp/testmain/models.py
testapp/testapp/testmain/models.py
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word)
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word) class School(models.Model): classes = models.ManyToManyField(ClassRoom)
Add new testing model `School`
Add new testing model `School` Issue #43
Python
mit
applegrew/django-select2,dulaccc/django-select2,strongriley/django-select2,Feria/https-github.com-applegrew-django-select2,hobarrera/django-select2,hisie/django-select2,Feria/https-github.com-applegrew-django-select2,hisie/django-select2,bubenkoff/django-select2,pbs/django-select2,dantagg/django-select2,hobarrera/django-select2,applegrew/django-select2,SmithsonianEnterprises/django-select2,bubenkoff/django-select2,dulaccc/django-select2,DMOJ/django-select2,emorozov/django-select2,strongriley/django-select2,pbs/django-select2,DMOJ/django-select2,rizumu/django-select2,emorozov/django-select2,applegrew/django-select2,SmithsonianEnterprises/django-select2,patgmiller/django-select2,hisie/django-select2,anneFly/django-select2,TempoIQ/django-select2,patgmiller/django-select2,bubenkoff/django-select2,patgmiller/django-select2,rizumu/django-select2,DMOJ/django-select2,pbs/django-select2,dantagg/django-select2,Feria/https-github.com-applegrew-django-select2,rizumu/django-select2,anneFly/django-select2,dulaccc/django-select2,TempoIQ/django-select2,SmithsonianEnterprises/django-select2,anneFly/django-select2,TempoIQ/django-select2,hobarrera/django-select2,strongriley/django-select2,dantagg/django-select2,emorozov/django-select2
python
## Code Before: from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word) ## Instruction: Add new testing model `School` Issue #43 ## Code After: from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.Model): name = models.CharField(max_length=10) allotted_rooms = models.ManyToManyField(ClassRoom) allotted_labs = models.ManyToManyField(Lab) def __unicode__(self): return unicode(self.name) class Employee(models.Model): name = models.CharField(max_length=30) salary = models.FloatField() dept = models.ForeignKey(Dept) manager = models.ForeignKey('Employee', null=True, blank=True) def __unicode__(self): return unicode(self.name) class Word(models.Model): word = models.CharField(max_length=15) def __unicode__(self): return unicode(self.word) class School(models.Model): classes = models.ManyToManyField(ClassRoom)
# ... existing code ... def __unicode__(self): return unicode(self.word) class School(models.Model): classes = models.ManyToManyField(ClassRoom) # ... rest of the code ...
af6f4868f4329fec75e43fe0cdcd1a7665c5238a
contentcuration/manage.py
contentcuration/manage.py
import os import sys # Attach Python Cloud Debugger if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import os import sys if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Remove comment on attaching cloud debugger
Remove comment on attaching cloud debugger
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
python
## Code Before: import os import sys # Attach Python Cloud Debugger if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ## Instruction: Remove comment on attaching cloud debugger ## Code After: import os import sys if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
# ... existing code ... import sys if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) # ... rest of the code ...
d8e054df4810ad2c32cd61c41391e0ee1b542a66
ipython_widgets/__init__.py
ipython_widgets/__init__.py
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None: ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
Make it possible to import ipython_widgets without having a kernel or comm manager
Make it possible to import ipython_widgets without having a kernel or comm manager
Python
bsd-3-clause
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets
python
## Code Before: from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None: ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened) ## Instruction: Make it possible to import ipython_widgets without having a kernel or comm manager ## Code After: from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
// ... existing code ... # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened) // ... rest of the code ...
eb15038cd582e087225985947e4b98ffbc86d812
setup.py
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click>=6.0'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, )
try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click', 'pathlib'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, )
Remove version requirement, add pathlib
Remove version requirement, add pathlib
Python
mit
develersrl/git-externals,develersrl/git-externals,develersrl/git-externals
python
## Code Before: try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click>=6.0'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, ) ## Instruction: Remove version requirement, add pathlib ## Code After: try: from setuptools import setup except ImportError: from distutils.core import setup with open('git_externals/__init__.py') as fp: exec(fp.read()) classifiers = [ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ] setup( name='git-externals', version=__version__, description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click', 'pathlib'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', 'gittify-cleanup = git_externals.cleanup_repo:main', 'svn-externals-info = git_externals.process_externals:main', 'gittify = git_externals.gittify:main', 'gittify-gen = git_externals.makefiles:cli', ], }, author=__author__, author_email=__email__, license='MIT', classifiers=classifiers, )
# ... existing code ... description='utility to manage svn externals', long_description='', packages=['git_externals'], install_requires=['click', 'pathlib'], entry_points={ 'console_scripts': [ 'git-externals = git_externals.git_externals:cli', # ... rest of the code ...
c6ab73a718d7f8c948ba79071993cd7a8f484ab5
rm/userprofiles/views.py
rm/userprofiles/views.py
from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from rm.userprofiles.forms import ProfileForm from rm.userprofiles.models import RMUser class RMUserUpdate(UpdateView): model = RMUser form_class = ProfileForm success_url = reverse_lazy('account-edit') def get_object(self, *args, **kwargs): """ Override the default get object to return the currently logged in user. """ return self.request.user
from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from rm.http import LoginRequiredMixin from rm.userprofiles.forms import ProfileForm from rm.userprofiles.models import RMUser class RMUserUpdate(LoginRequiredMixin, UpdateView): model = RMUser form_class = ProfileForm success_url = reverse_lazy('account-edit') def get_object(self, *args, **kwargs): """ Override the default get object to return the currently logged in user. """ return self.request.user
Make our account pages require a logged in user.
Make our account pages require a logged in user. closes #221
Python
agpl-3.0
openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me
python
## Code Before: from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from rm.userprofiles.forms import ProfileForm from rm.userprofiles.models import RMUser class RMUserUpdate(UpdateView): model = RMUser form_class = ProfileForm success_url = reverse_lazy('account-edit') def get_object(self, *args, **kwargs): """ Override the default get object to return the currently logged in user. """ return self.request.user ## Instruction: Make our account pages require a logged in user. closes #221 ## Code After: from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from rm.http import LoginRequiredMixin from rm.userprofiles.forms import ProfileForm from rm.userprofiles.models import RMUser class RMUserUpdate(LoginRequiredMixin, UpdateView): model = RMUser form_class = ProfileForm success_url = reverse_lazy('account-edit') def get_object(self, *args, **kwargs): """ Override the default get object to return the currently logged in user. """ return self.request.user
# ... existing code ... from django.core.urlresolvers import reverse_lazy from django.views.generic.edit import UpdateView from rm.http import LoginRequiredMixin from rm.userprofiles.forms import ProfileForm from rm.userprofiles.models import RMUser class RMUserUpdate(LoginRequiredMixin, UpdateView): model = RMUser form_class = ProfileForm success_url = reverse_lazy('account-edit') # ... rest of the code ...
5fff847531ede017aeabc7e38264f438748b5493
webkit/plugins/ppapi/ppp_pdf.h
webkit/plugins/ppapi/ppp_pdf.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #define WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_point.h" #include "ppapi/c/pp_var.h" #define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" struct PPP_Pdf_1 { // Returns an absolute URL if the position is over a link. PP_Var (*GetLinkAtPosition)(PP_Instance instance, PP_Point point); }; typedef PPP_Pdf_1 PPP_Pdf; #endif // WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #define WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_point.h" #include "ppapi/c/pp_var.h" #define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" #define PPP_PDF_INTERFACE PPP_PDF_INTERFACE_1 struct PPP_Pdf_1 { // Returns an absolute URL if the position is over a link. PP_Var (*GetLinkAtPosition)(PP_Instance instance, PP_Point point); }; typedef PPP_Pdf_1 PPP_Pdf; #endif // WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_
Add missing unversioned interface-name macro for PPP_Pdf.
Add missing unversioned interface-name macro for PPP_Pdf. BUG=107398 Review URL: http://codereview.chromium.org/9114010 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@116504 0039d316-1c4b-4281-b951-d872f2087c98
C
bsd-3-clause
adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium
c
## Code Before: // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #define WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_point.h" #include "ppapi/c/pp_var.h" #define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" struct PPP_Pdf_1 { // Returns an absolute URL if the position is over a link. PP_Var (*GetLinkAtPosition)(PP_Instance instance, PP_Point point); }; typedef PPP_Pdf_1 PPP_Pdf; #endif // WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ ## Instruction: Add missing unversioned interface-name macro for PPP_Pdf. BUG=107398 Review URL: http://codereview.chromium.org/9114010 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@116504 0039d316-1c4b-4281-b951-d872f2087c98 ## Code After: // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #define WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_ #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_point.h" #include "ppapi/c/pp_var.h" #define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" #define PPP_PDF_INTERFACE PPP_PDF_INTERFACE_1 struct PPP_Pdf_1 { // Returns an absolute URL if the position is over a link. PP_Var (*GetLinkAtPosition)(PP_Instance instance, PP_Point point); }; typedef PPP_Pdf_1 PPP_Pdf; #endif // WEBKIT_PLUGINS_PPAPI_PPP_PDF_H_
# ... existing code ... #include "ppapi/c/pp_var.h" #define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" #define PPP_PDF_INTERFACE PPP_PDF_INTERFACE_1 struct PPP_Pdf_1 { // Returns an absolute URL if the position is over a link. # ... rest of the code ...
14537b8260891f03f478fd0c4ff1736d57bffe5e
src/com/markupartist/crimesweeper/PlayerLocationOverlay.java
src/com/markupartist/crimesweeper/PlayerLocationOverlay.java
package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } }
package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); if(listener == null) { return; } for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } }
Allow the listener to be set to null
Allow the listener to be set to null
Java
apache-2.0
joakimk/CrimeSweeper
java
## Code Before: package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } } ## Instruction: Allow the listener to be set to null ## Code After: package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); if(listener == null) { return; } for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } }
// ... existing code ... public void onLocationChanged(Location location) { super.onLocationChanged(location); if(listener == null) { return; } for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); // ... rest of the code ...
235b1753f48c8a22cb79e3115b637f179c3e1e8b
src/initiation/transport/sipauthentication.h
src/initiation/transport/sipauthentication.h
/* This class handles the authentication for this connection * should we receive a challenge */ class SIPAuthentication : public SIPMessageProcessor { Q_OBJECT public: SIPAuthentication(); public slots: // add credentials to request, if we have them virtual void processOutgoingRequest(SIPRequest& request, QVariant& content); // take challenge if they require authentication virtual void processIncomingResponse(SIPResponse& response, QVariant& content); private: DigestResponse generateAuthResponse(DigestChallenge& challenge, QString username, SIP_URI& requestURI, SIPRequestMethod method, QVariant& content); void updateNonceCount(DigestChallenge& challenge, DigestResponse& response); // TODO: Test if these need to be separate QList<DigestChallenge> wwwChallenges_; QList<DigestChallenge> proxyChallenges_; QList<DigestResponse> authorizations_; QList<DigestResponse> proxyAuthorizations_; // key is realm and value current nonce std::map<QString, QString> realmToNonce_; std::map<QString, uint32_t> realmToNonceCount_; QByteArray a1_; };
/* This class handles the authentication for this connection * should we receive a challenge */ class SIPAuthentication : public SIPMessageProcessor { Q_OBJECT public: SIPAuthentication(); public slots: // add credentials to request, if we have them virtual void processOutgoingRequest(SIPRequest& request, QVariant& content); // take challenge if they require authentication virtual void processIncomingResponse(SIPResponse& response, QVariant& content); private: DigestResponse generateAuthResponse(DigestChallenge& challenge, QString username, SIP_URI& requestURI, SIPRequestMethod method, QVariant& content); void updateNonceCount(DigestChallenge& challenge, DigestResponse& response); QList<DigestChallenge> wwwChallenges_; QList<DigestChallenge> proxyChallenges_; QList<DigestResponse> authorizations_; QList<DigestResponse> proxyAuthorizations_; // key is realm and value current nonce std::map<QString, QString> realmToNonce_; std::map<QString, uint32_t> realmToNonceCount_; QByteArray a1_; };
Remove TODO. Tested common credentials, didn't work.
cosmetic(Transport): Remove TODO. Tested common credentials, didn't work.
C
isc
ultravideo/kvazzup,ultravideo/kvazzup
c
## Code Before: /* This class handles the authentication for this connection * should we receive a challenge */ class SIPAuthentication : public SIPMessageProcessor { Q_OBJECT public: SIPAuthentication(); public slots: // add credentials to request, if we have them virtual void processOutgoingRequest(SIPRequest& request, QVariant& content); // take challenge if they require authentication virtual void processIncomingResponse(SIPResponse& response, QVariant& content); private: DigestResponse generateAuthResponse(DigestChallenge& challenge, QString username, SIP_URI& requestURI, SIPRequestMethod method, QVariant& content); void updateNonceCount(DigestChallenge& challenge, DigestResponse& response); // TODO: Test if these need to be separate QList<DigestChallenge> wwwChallenges_; QList<DigestChallenge> proxyChallenges_; QList<DigestResponse> authorizations_; QList<DigestResponse> proxyAuthorizations_; // key is realm and value current nonce std::map<QString, QString> realmToNonce_; std::map<QString, uint32_t> realmToNonceCount_; QByteArray a1_; }; ## Instruction: cosmetic(Transport): Remove TODO. Tested common credentials, didn't work. ## Code After: /* This class handles the authentication for this connection * should we receive a challenge */ class SIPAuthentication : public SIPMessageProcessor { Q_OBJECT public: SIPAuthentication(); public slots: // add credentials to request, if we have them virtual void processOutgoingRequest(SIPRequest& request, QVariant& content); // take challenge if they require authentication virtual void processIncomingResponse(SIPResponse& response, QVariant& content); private: DigestResponse generateAuthResponse(DigestChallenge& challenge, QString username, SIP_URI& requestURI, SIPRequestMethod method, QVariant& content); void updateNonceCount(DigestChallenge& challenge, DigestResponse& response); QList<DigestChallenge> wwwChallenges_; QList<DigestChallenge> proxyChallenges_; QList<DigestResponse> authorizations_; QList<DigestResponse> proxyAuthorizations_; // key is realm and value current nonce std::map<QString, QString> realmToNonce_; std::map<QString, uint32_t> realmToNonceCount_; QByteArray a1_; };
# ... existing code ... void updateNonceCount(DigestChallenge& challenge, DigestResponse& response); QList<DigestChallenge> wwwChallenges_; QList<DigestChallenge> proxyChallenges_; # ... rest of the code ...
35f9c78274876c6eb1e487071c7957c9b8460f68
pecan/compat/__init__.py
pecan/compat/__init__.py
import inspect import six if six.PY3: import urllib.parse as urlparse from urllib.parse import quote, unquote_plus from urllib.request import urlopen, URLError from html import escape izip = zip else: import urlparse # noqa from urllib import quote, unquote_plus # noqa from urllib2 import urlopen, URLError # noqa from cgi import escape # noqa from itertools import izip def is_bound_method(ob): return inspect.ismethod(ob) and six.get_method_self(ob) is not None def getargspec(func): import sys if sys.version_info < (3, 5): return inspect.getargspec(func) sig = inspect._signature_from_callable(func, follow_wrapper_chains=False, skip_bound_arg=False, sigcls=inspect.Signature) args = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] varargs = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_POSITIONAL ] varargs = varargs[0] if varargs else None varkw = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_KEYWORD ] varkw = varkw[0] if varkw else None defaults = [ p.default for p in sig.parameters.values() if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and p.default is not p.empty) ] or None if defaults is not None: defaults = tuple(defaults) from collections import namedtuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') return ArgSpec(args, varargs, varkw, defaults)
import inspect import six if six.PY3: import urllib.parse as urlparse from urllib.parse import quote, unquote_plus from urllib.request import urlopen, URLError from html import escape izip = zip else: import urlparse # noqa from urllib import quote, unquote_plus # noqa from urllib2 import urlopen, URLError # noqa from cgi import escape # noqa from itertools import izip def is_bound_method(ob): return inspect.ismethod(ob) and six.get_method_self(ob) is not None def getargspec(func): import sys if sys.version_info < (3, 5): return inspect.getargspec(func) from collections import namedtuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') args, varargs, keywords, defaults = inspect.getfullargspec(func)[:4] return ArgSpec(args=args, varargs=varargs, keywords=keywords, defaults=defaults)
Simplify our argspec compatability shim.
Simplify our argspec compatability shim.
Python
bsd-3-clause
pecan/pecan,ryanpetrello/pecan,pecan/pecan,ryanpetrello/pecan
python
## Code Before: import inspect import six if six.PY3: import urllib.parse as urlparse from urllib.parse import quote, unquote_plus from urllib.request import urlopen, URLError from html import escape izip = zip else: import urlparse # noqa from urllib import quote, unquote_plus # noqa from urllib2 import urlopen, URLError # noqa from cgi import escape # noqa from itertools import izip def is_bound_method(ob): return inspect.ismethod(ob) and six.get_method_self(ob) is not None def getargspec(func): import sys if sys.version_info < (3, 5): return inspect.getargspec(func) sig = inspect._signature_from_callable(func, follow_wrapper_chains=False, skip_bound_arg=False, sigcls=inspect.Signature) args = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] varargs = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_POSITIONAL ] varargs = varargs[0] if varargs else None varkw = [ p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.VAR_KEYWORD ] varkw = varkw[0] if varkw else None defaults = [ p.default for p in sig.parameters.values() if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and p.default is not p.empty) ] or None if defaults is not None: defaults = tuple(defaults) from collections import namedtuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') return ArgSpec(args, varargs, varkw, defaults) ## Instruction: Simplify our argspec compatability shim. ## Code After: import inspect import six if six.PY3: import urllib.parse as urlparse from urllib.parse import quote, unquote_plus from urllib.request import urlopen, URLError from html import escape izip = zip else: import urlparse # noqa from urllib import quote, unquote_plus # noqa from urllib2 import urlopen, URLError # noqa from cgi import escape # noqa from itertools import izip def is_bound_method(ob): return inspect.ismethod(ob) and six.get_method_self(ob) is not None def getargspec(func): import sys if sys.version_info < (3, 5): return inspect.getargspec(func) from collections import namedtuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') args, varargs, keywords, defaults = inspect.getfullargspec(func)[:4] return ArgSpec(args=args, varargs=varargs, keywords=keywords, defaults=defaults)
# ... existing code ... if sys.version_info < (3, 5): return inspect.getargspec(func) from collections import namedtuple ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') args, varargs, keywords, defaults = inspect.getfullargspec(func)[:4] return ArgSpec(args=args, varargs=varargs, keywords=keywords, defaults=defaults) # ... rest of the code ...
36b10d57a812b393c73fe3b4117cc133d0f9d110
templatemailer/mailer.py
templatemailer/mailer.py
import logging from django.core import mail from .tasks import task_email_user logger = logging.getLogger(__name__) def send_email(user, template, context, attachments=None, delete_attachments_after_send=False, language_code=None): ''' Send email to user :param user: User instance or recipient email addres :param template: Template to use for email :param context: Context for email :param attachments: List of attachments :param delete_attachments_after_send: If true, delete attachments from storage after sending :param language_code: Language code for template :return: ''' ### check if we are using test framework if hasattr(mail, 'outbox'): ### if yes, do not defer sending email send_email_f = task_email_user else: ### otherwise, defer sending email to celery send_email_f = task_email_user.delay ### send email send_email_f( user.pk if user else None, template, context, attachments=attachments, delete_attachments_after_send=delete_attachments_after_send, language_code=language_code )
import logging from django.core import mail from .tasks import task_email_user logger = logging.getLogger(__name__) def send_email(user, template, context, attachments=None, delete_attachments_after_send=False, language_code=None): ''' Send email to user :param user: User instance or recipient email addres :param template: Template to use for email :param context: Context for email :param attachments: List of attachments :param delete_attachments_after_send: If true, delete attachments from storage after sending :param language_code: Language code for template :return: ''' ### check if we are using test framework if hasattr(mail, 'outbox'): ### if yes, do not defer sending email send_email_f = task_email_user else: ### otherwise, defer sending email to celery send_email_f = task_email_user.delay try: user = user.pk except AttributeError: pass ### send email send_email_f( user, template, context, attachments=attachments, delete_attachments_after_send=delete_attachments_after_send, language_code=language_code )
Fix AttributeError when supplying email address as user
Fix AttributeError when supplying email address as user
Python
mit
tuomasjaanu/django-templatemailer
python
## Code Before: import logging from django.core import mail from .tasks import task_email_user logger = logging.getLogger(__name__) def send_email(user, template, context, attachments=None, delete_attachments_after_send=False, language_code=None): ''' Send email to user :param user: User instance or recipient email addres :param template: Template to use for email :param context: Context for email :param attachments: List of attachments :param delete_attachments_after_send: If true, delete attachments from storage after sending :param language_code: Language code for template :return: ''' ### check if we are using test framework if hasattr(mail, 'outbox'): ### if yes, do not defer sending email send_email_f = task_email_user else: ### otherwise, defer sending email to celery send_email_f = task_email_user.delay ### send email send_email_f( user.pk if user else None, template, context, attachments=attachments, delete_attachments_after_send=delete_attachments_after_send, language_code=language_code ) ## Instruction: Fix AttributeError when supplying email address as user ## Code After: import logging from django.core import mail from .tasks import task_email_user logger = logging.getLogger(__name__) def send_email(user, template, context, attachments=None, delete_attachments_after_send=False, language_code=None): ''' Send email to user :param user: User instance or recipient email addres :param template: Template to use for email :param context: Context for email :param attachments: List of attachments :param delete_attachments_after_send: If true, delete attachments from storage after sending :param language_code: Language code for template :return: ''' ### check if we are using test framework if hasattr(mail, 'outbox'): ### if yes, do not defer sending email send_email_f = task_email_user else: ### otherwise, defer sending email to celery send_email_f = task_email_user.delay try: user = user.pk except AttributeError: pass ### send email send_email_f( user, template, context, attachments=attachments, delete_attachments_after_send=delete_attachments_after_send, language_code=language_code )
... ### otherwise, defer sending email to celery send_email_f = task_email_user.delay try: user = user.pk except AttributeError: pass ### send email send_email_f( user, template, context, attachments=attachments, ...
429c93cfa5745a9a37cb453a5fabb3eabf0a99cb
lab1/digenv.c
lab1/digenv.c
int main(int argc, char *argv[]) { /* Command argument vectors. */ char *more_argv[] = { "more", NULL }; char *less_argv[] = { "less", NULL }; char *pager_argv[] = { getenv("PAGER"), NULL }; char *sort_argv[] = { "sort", NULL }; char *printenv_argv[] = { "printenv", NULL }; char **grep_argv = argv; grep_argv[0] = "grep"; /* Construct pipeline. */ /* file argv err next fallback */ command_t more = { "more", more_argv, 0, NULL, NULL}; command_t less = { "less", less_argv, 0, NULL, &more }; command_t pager = { getenv("PAGER"), pager_argv, 0, NULL, &less }; command_t sort = { "sort", sort_argv, 0, &pager, NULL }; command_t grep = { "grep", grep_argv, 0, &sort, NULL }; command_t printenv = { "printenv", printenv_argv, 0, &sort, NULL }; if (argc > 1) { /* Arguments given: Run grep as well. */ printenv.next = &grep; } /* Run pipeline. */ run_pipeline(&printenv, STDIN_FILENO); return 0; }
int main(int argc, char *argv[]) { char *pager_env = getenv("PAGER"); /* Construct pipeline. */ /* file argv err next fallback */ command_t more = {"more", (char *[]){"more", NULL}, 0, NULL, NULL}; command_t less = {"less", (char *[]){"less", NULL}, 0, NULL, &more}; command_t pager = {pager_env, (char *[]){pager_env, NULL}, 0, NULL, &less}; command_t sort = {"sort", (char *[]){"sort", NULL}, 0, &pager, NULL}; command_t grep = {"grep", argv, 0, &sort, NULL}; command_t printenv = {"printenv", (char *[]){"printenv", NULL}, 0, &sort, NULL}; if (argc > 1) { /* Arguments given: Run grep as well. */ printenv.next = &grep; argv[0] = "grep"; } /* Run pipeline. */ run_pipeline(&printenv, STDIN_FILENO); return 0; }
Initialize argv vectors using compound literals.
Initialize argv vectors using compound literals.
C
mit
estan/ID2200,estan/ID2200
c
## Code Before: int main(int argc, char *argv[]) { /* Command argument vectors. */ char *more_argv[] = { "more", NULL }; char *less_argv[] = { "less", NULL }; char *pager_argv[] = { getenv("PAGER"), NULL }; char *sort_argv[] = { "sort", NULL }; char *printenv_argv[] = { "printenv", NULL }; char **grep_argv = argv; grep_argv[0] = "grep"; /* Construct pipeline. */ /* file argv err next fallback */ command_t more = { "more", more_argv, 0, NULL, NULL}; command_t less = { "less", less_argv, 0, NULL, &more }; command_t pager = { getenv("PAGER"), pager_argv, 0, NULL, &less }; command_t sort = { "sort", sort_argv, 0, &pager, NULL }; command_t grep = { "grep", grep_argv, 0, &sort, NULL }; command_t printenv = { "printenv", printenv_argv, 0, &sort, NULL }; if (argc > 1) { /* Arguments given: Run grep as well. */ printenv.next = &grep; } /* Run pipeline. */ run_pipeline(&printenv, STDIN_FILENO); return 0; } ## Instruction: Initialize argv vectors using compound literals. ## Code After: int main(int argc, char *argv[]) { char *pager_env = getenv("PAGER"); /* Construct pipeline. */ /* file argv err next fallback */ command_t more = {"more", (char *[]){"more", NULL}, 0, NULL, NULL}; command_t less = {"less", (char *[]){"less", NULL}, 0, NULL, &more}; command_t pager = {pager_env, (char *[]){pager_env, NULL}, 0, NULL, &less}; command_t sort = {"sort", (char *[]){"sort", NULL}, 0, &pager, NULL}; command_t grep = {"grep", argv, 0, &sort, NULL}; command_t printenv = {"printenv", (char *[]){"printenv", NULL}, 0, &sort, NULL}; if (argc > 1) { /* Arguments given: Run grep as well. */ printenv.next = &grep; argv[0] = "grep"; } /* Run pipeline. */ run_pipeline(&printenv, STDIN_FILENO); return 0; }
// ... existing code ... int main(int argc, char *argv[]) { char *pager_env = getenv("PAGER"); /* Construct pipeline. */ /* file argv err next fallback */ command_t more = {"more", (char *[]){"more", NULL}, 0, NULL, NULL}; command_t less = {"less", (char *[]){"less", NULL}, 0, NULL, &more}; command_t pager = {pager_env, (char *[]){pager_env, NULL}, 0, NULL, &less}; command_t sort = {"sort", (char *[]){"sort", NULL}, 0, &pager, NULL}; command_t grep = {"grep", argv, 0, &sort, NULL}; command_t printenv = {"printenv", (char *[]){"printenv", NULL}, 0, &sort, NULL}; if (argc > 1) { /* Arguments given: Run grep as well. */ printenv.next = &grep; argv[0] = "grep"; } /* Run pipeline. */ // ... modified code ... return 0; } // ... rest of the code ...
04b7e79ce3fed1afac129098badb632ca226fdee
dispatch.py
dispatch.py
import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run()
import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web # wsgi application = render.application.wsgifunc() if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run()
Add wsgi handler by default
Add wsgi handler by default
Python
isc
Lagg/optf2,FlaminSarge/optf2,Lagg/optf2,FlaminSarge/optf2,Lagg/optf2,FlaminSarge/optf2
python
## Code Before: import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run() ## Instruction: Add wsgi handler by default ## Code After: import config import steam steam.set_api_key(config.api_key) from optf2.backend import openid from optf2.frontend import render openid.set_session(render.session) import web # wsgi application = render.application.wsgifunc() if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": render.application.run()
# ... existing code ... openid.set_session(render.session) import web # wsgi application = render.application.wsgifunc() if config.enable_fastcgi: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) # ... rest of the code ...
db44748e593166fdff24cef275e13d0dfb56df3b
src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java
src/net/java/sip/communicator/impl/gui/lookandfeel/SIPCommMenuBarUI.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.lookandfeel; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Yana Stamcheva */ public class SIPCommMenuBarUI extends BasicMenuBarUI { /** * Creates a new SIPCommMenuUI instance. */ public static ComponentUI createUI(JComponent x) { return new SIPCommMenuBarUI(); } protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); LookAndFeel.installBorder(menuBar, null); } }
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.lookandfeel; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Yana Stamcheva */ public class SIPCommMenuBarUI extends BasicMenuBarUI { /** * Creates a new SIPCommMenuUI instance. */ public static ComponentUI createUI(JComponent x) { return new SIPCommMenuBarUI(); } protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); } }
Fix NullPointerException when starting SC.
Fix NullPointerException when starting SC.
Java
apache-2.0
ringdna/jitsi,HelioGuilherme66/jitsi,damencho/jitsi,gpolitis/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,level7systems/jitsi,level7systems/jitsi,gpolitis/jitsi,bhatvv/jitsi,laborautonomo/jitsi,bebo/jitsi,procandi/jitsi,damencho/jitsi,jitsi/jitsi,cobratbq/jitsi,gpolitis/jitsi,laborautonomo/jitsi,Metaswitch/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,bhatvv/jitsi,damencho/jitsi,bhatvv/jitsi,level7systems/jitsi,cobratbq/jitsi,459below/jitsi,jibaro/jitsi,marclaporte/jitsi,mckayclarey/jitsi,459below/jitsi,bebo/jitsi,tuijldert/jitsi,mckayclarey/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,iant-gmbh/jitsi,tuijldert/jitsi,procandi/jitsi,ibauersachs/jitsi,pplatek/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,martin7890/jitsi,dkcreinoso/jitsi,laborautonomo/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,ringdna/jitsi,level7systems/jitsi,tuijldert/jitsi,damencho/jitsi,bhatvv/jitsi,ringdna/jitsi,HelioGuilherme66/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,bebo/jitsi,mckayclarey/jitsi,gpolitis/jitsi,jibaro/jitsi,ringdna/jitsi,Metaswitch/jitsi,pplatek/jitsi,martin7890/jitsi,459below/jitsi,Metaswitch/jitsi,ibauersachs/jitsi,marclaporte/jitsi,procandi/jitsi,bebo/jitsi,mckayclarey/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,gpolitis/jitsi,martin7890/jitsi,procandi/jitsi,jitsi/jitsi,bebo/jitsi,pplatek/jitsi,cobratbq/jitsi,ringdna/jitsi,iant-gmbh/jitsi,jitsi/jitsi,jibaro/jitsi,marclaporte/jitsi,HelioGuilherme66/jitsi,procandi/jitsi,459below/jitsi,cobratbq/jitsi,jitsi/jitsi,jibaro/jitsi,tuijldert/jitsi,pplatek/jitsi,459below/jitsi,damencho/jitsi,level7systems/jitsi,jitsi/jitsi,dkcreinoso/jitsi,laborautonomo/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,mckayclarey/jitsi,jibaro/jitsi,martin7890/jitsi,laborautonomo/jitsi
java
## Code Before: /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.lookandfeel; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Yana Stamcheva */ public class SIPCommMenuBarUI extends BasicMenuBarUI { /** * Creates a new SIPCommMenuUI instance. */ public static ComponentUI createUI(JComponent x) { return new SIPCommMenuBarUI(); } protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); LookAndFeel.installBorder(menuBar, null); } } ## Instruction: Fix NullPointerException when starting SC. ## Code After: /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.lookandfeel; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Yana Stamcheva */ public class SIPCommMenuBarUI extends BasicMenuBarUI { /** * Creates a new SIPCommMenuUI instance. */ public static ComponentUI createUI(JComponent x) { return new SIPCommMenuBarUI(); } protected void installDefaults() { super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); } }
... super.installDefaults(); LookAndFeel.installProperty(menuBar, "opaque", Boolean.FALSE); } } ...
8226571dc97230a486a3b59c8752411e038f04ee
openprescribing/matrixstore/tests/matrixstore_factory.py
openprescribing/matrixstore/tests/matrixstore_factory.py
import mock import sqlite3 from matrixstore.connection import MatrixStore from matrixstore import db from matrixstore.tests.import_test_data_fast import import_test_data_fast def matrixstore_from_data_factory(data_factory, end_date=None, months=None): """ Returns a new in-memory MatrixStore instance using the data from the supplied DataFactory """ connection = sqlite3.connect(":memory:") end_date = max(data_factory.months)[:7] if end_date is None else end_date months = len(data_factory.months) if months is None else months import_test_data_fast(connection, data_factory, end_date, months=months) return MatrixStore(connection) def patch_global_matrixstore(matrixstore): """ Temporarily replace the global MatrixStore instance (as accessed via `matrixstore.db.get_db`) with the supplied matrixstore Returns a function which undoes the monkeypatching """ patcher = mock.patch("matrixstore.connection.MatrixStore.from_file") mocked = patcher.start() mocked.return_value = matrixstore # There are memoized functions so we clear any previously memoized value db.get_db.cache_clear() db.get_row_grouper.cache_clear() def stop_patching(): patcher.stop() db.get_db.cache_clear() db.get_row_grouper.cache_clear() matrixstore.close() return stop_patching
import mock import sqlite3 from matrixstore.connection import MatrixStore from matrixstore import db from matrixstore.tests.import_test_data_fast import import_test_data_fast def matrixstore_from_data_factory(data_factory, end_date=None, months=None): """ Returns a new in-memory MatrixStore instance using the data from the supplied DataFactory """ # We need this connection to be sharable across threads because # LiveServerTestCase runs in a separate thread from the main test code connection = sqlite3.connect(":memory:", check_same_thread=False) end_date = max(data_factory.months)[:7] if end_date is None else end_date months = len(data_factory.months) if months is None else months import_test_data_fast(connection, data_factory, end_date, months=months) return MatrixStore(connection) def patch_global_matrixstore(matrixstore): """ Temporarily replace the global MatrixStore instance (as accessed via `matrixstore.db.get_db`) with the supplied matrixstore Returns a function which undoes the monkeypatching """ patcher = mock.patch("matrixstore.connection.MatrixStore.from_file") mocked = patcher.start() mocked.return_value = matrixstore # There are memoized functions so we clear any previously memoized value db.get_db.cache_clear() db.get_row_grouper.cache_clear() def stop_patching(): patcher.stop() db.get_db.cache_clear() db.get_row_grouper.cache_clear() matrixstore.close() return stop_patching
Fix MatrixStore test patching to work with LiveServerTestCase
Fix MatrixStore test patching to work with LiveServerTestCase
Python
mit
annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing
python
## Code Before: import mock import sqlite3 from matrixstore.connection import MatrixStore from matrixstore import db from matrixstore.tests.import_test_data_fast import import_test_data_fast def matrixstore_from_data_factory(data_factory, end_date=None, months=None): """ Returns a new in-memory MatrixStore instance using the data from the supplied DataFactory """ connection = sqlite3.connect(":memory:") end_date = max(data_factory.months)[:7] if end_date is None else end_date months = len(data_factory.months) if months is None else months import_test_data_fast(connection, data_factory, end_date, months=months) return MatrixStore(connection) def patch_global_matrixstore(matrixstore): """ Temporarily replace the global MatrixStore instance (as accessed via `matrixstore.db.get_db`) with the supplied matrixstore Returns a function which undoes the monkeypatching """ patcher = mock.patch("matrixstore.connection.MatrixStore.from_file") mocked = patcher.start() mocked.return_value = matrixstore # There are memoized functions so we clear any previously memoized value db.get_db.cache_clear() db.get_row_grouper.cache_clear() def stop_patching(): patcher.stop() db.get_db.cache_clear() db.get_row_grouper.cache_clear() matrixstore.close() return stop_patching ## Instruction: Fix MatrixStore test patching to work with LiveServerTestCase ## Code After: import mock import sqlite3 from matrixstore.connection import MatrixStore from matrixstore import db from matrixstore.tests.import_test_data_fast import import_test_data_fast def matrixstore_from_data_factory(data_factory, end_date=None, months=None): """ Returns a new in-memory MatrixStore instance using the data from the supplied DataFactory """ # We need this connection to be sharable across threads because # LiveServerTestCase runs in a separate thread from the main test code connection = sqlite3.connect(":memory:", check_same_thread=False) end_date = max(data_factory.months)[:7] if end_date is None else end_date months = len(data_factory.months) if months is None else months import_test_data_fast(connection, data_factory, end_date, months=months) return MatrixStore(connection) def patch_global_matrixstore(matrixstore): """ Temporarily replace the global MatrixStore instance (as accessed via `matrixstore.db.get_db`) with the supplied matrixstore Returns a function which undoes the monkeypatching """ patcher = mock.patch("matrixstore.connection.MatrixStore.from_file") mocked = patcher.start() mocked.return_value = matrixstore # There are memoized functions so we clear any previously memoized value db.get_db.cache_clear() db.get_row_grouper.cache_clear() def stop_patching(): patcher.stop() db.get_db.cache_clear() db.get_row_grouper.cache_clear() matrixstore.close() return stop_patching
// ... existing code ... Returns a new in-memory MatrixStore instance using the data from the supplied DataFactory """ # We need this connection to be sharable across threads because # LiveServerTestCase runs in a separate thread from the main test code connection = sqlite3.connect(":memory:", check_same_thread=False) end_date = max(data_factory.months)[:7] if end_date is None else end_date months = len(data_factory.months) if months is None else months import_test_data_fast(connection, data_factory, end_date, months=months) // ... rest of the code ...
4b1b5d0b71100fea17f127683a58533ef0e06fe9
bintools/splitter.py
bintools/splitter.py
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: cont = False chunksize = filesize chunk = __read_write_block(fromfile, chunksize) if not chunk: break partnum = partnum + 1 filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() chunksize *= 2 #### Private methods def __read_write_block(f, n): stream = open(f, 'rb') chunk = stream.read(n) stream.close() return chunk
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj
Refactor functions & add params
Refactor functions & add params
Python
apache-2.0
FernandoDoming/offset_finder
python
## Code Before: import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: cont = False chunksize = filesize chunk = __read_write_block(fromfile, chunksize) if not chunk: break partnum = partnum + 1 filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() chunksize *= 2 #### Private methods def __read_write_block(f, n): stream = open(f, 'rb') chunk = stream.read(n) stream.close() return chunk ## Instruction: Refactor functions & add params ## Code After: import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj
... import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts ... partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj ...
27839484173c4d505ddb9f949da3576f180b8266
tests/test_short_url.py
tests/test_short_url.py
from random import randrange from pytest import raises import short_url def test_custom_alphabet(): encoder = short_url.UrlEncoder(alphabet='ab') url = encoder.encode_url(12) assert url == 'bbaaaaaaaaaaaaaaaaaaaa' key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa') assert key == 12 def test_too_short_alphabet(): with raises(AttributeError): short_url.UrlEncoder(alphabet='aa') with raises(AttributeError): short_url.UrlEncoder(alphabet='a')
import os from random import randrange from pytest import raises import short_url TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) TEST_DATA = os.path.join(TEST_DATA, 'tests/data') def generate_test_data(count=10000): result = {} for i in range(1000): value = short_url.encode_url(i) result[i] = value while len(result) < count: random_int = randrange(1000000) value = short_url.encode_url(random_int) result[random_int] = value with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f: for k, v in result.items(): f.write('%s:%s\n' % (k, v)) # generate_test_data() def test_custom_alphabet(): encoder = short_url.UrlEncoder(alphabet='ab') url = encoder.encode_url(12) assert url == 'bbaaaaaaaaaaaaaaaaaaaa' key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa') assert key == 12 def test_too_short_alphabet(): with raises(AttributeError): short_url.UrlEncoder(alphabet='aa') with raises(AttributeError): short_url.UrlEncoder(alphabet='a')
Add function for generating test data
Add function for generating test data
Python
mit
Alir3z4/python-short_url
python
## Code Before: from random import randrange from pytest import raises import short_url def test_custom_alphabet(): encoder = short_url.UrlEncoder(alphabet='ab') url = encoder.encode_url(12) assert url == 'bbaaaaaaaaaaaaaaaaaaaa' key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa') assert key == 12 def test_too_short_alphabet(): with raises(AttributeError): short_url.UrlEncoder(alphabet='aa') with raises(AttributeError): short_url.UrlEncoder(alphabet='a') ## Instruction: Add function for generating test data ## Code After: import os from random import randrange from pytest import raises import short_url TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) TEST_DATA = os.path.join(TEST_DATA, 'tests/data') def generate_test_data(count=10000): result = {} for i in range(1000): value = short_url.encode_url(i) result[i] = value while len(result) < count: random_int = randrange(1000000) value = short_url.encode_url(random_int) result[random_int] = value with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f: for k, v in result.items(): f.write('%s:%s\n' % (k, v)) # generate_test_data() def test_custom_alphabet(): encoder = short_url.UrlEncoder(alphabet='ab') url = encoder.encode_url(12) assert url == 'bbaaaaaaaaaaaaaaaaaaaa' key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa') assert key == 12 def test_too_short_alphabet(): with raises(AttributeError): short_url.UrlEncoder(alphabet='aa') with raises(AttributeError): short_url.UrlEncoder(alphabet='a')
# ... existing code ... import os from random import randrange from pytest import raises # ... modified code ... import short_url TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) TEST_DATA = os.path.join(TEST_DATA, 'tests/data') def generate_test_data(count=10000): result = {} for i in range(1000): value = short_url.encode_url(i) result[i] = value while len(result) < count: random_int = randrange(1000000) value = short_url.encode_url(random_int) result[random_int] = value with open(os.path.join(TEST_DATA, 'key_values.txt'), 'w') as f: for k, v in result.items(): f.write('%s:%s\n' % (k, v)) # generate_test_data() def test_custom_alphabet(): # ... rest of the code ...
5a7a1d9b287813559f13298575dba1de09040900
inc/angle.h
inc/angle.h
namespace angle { template <typename T> T wrap(T angle) { angle = std::fmod(angle, boost::math::constants::two_pi<T>()); if (angle >= boost::math::constants::pi<T>()) { angle -= boost::math::constants::two_pi<T>(); } if (angle < -boost::math::constants::pi<T>()) { angle += boost::math::constants::two_pi<T>(); } return angle; } /* * Get angle from encoder count (enccnt_t is uint32_t) * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative * values for any count over half a revolution. */ template <typename T> T encoder_count(const Encoder& encoder) { auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count()); auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); if (position > rev / 2) { position -= rev; } return static_cast<T>(position) / rev * boost::math::constants::two_pi<T>(); } } // namespace angle
namespace angle { template <typename T> T wrap(T angle) { angle = std::fmod(angle, boost::math::constants::two_pi<T>()); if (angle >= boost::math::constants::pi<T>()) { angle -= boost::math::constants::two_pi<T>(); } if (angle < -boost::math::constants::pi<T>()) { angle += boost::math::constants::two_pi<T>(); } return angle; } /* * Get angle from encoder count (enccnt_t is uint32_t) * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative * values for any count over half a revolution. */ template <typename T> T encoder_count(const Encoder& encoder) { auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count()); auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); if (position > rev / 2) { position -= rev; } return static_cast<T>(position) / rev * boost::math::constants::two_pi<T>(); } template <typename T, size_t N> T encoder_rate(const EncoderFoaw<T, N>& encoder) { auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); return static_cast<T>(encoder.velocity()) / rev * boost::math::constants::two_pi<T>(); } } // namespace angle
Add function to obtain encoder angular rate
Add function to obtain encoder angular rate Add function to angle namespace to obtain encoder angular rate in rad/s. This requires that the encoder object has a velocity() member function which means only EncoderFoaw for now.
C
bsd-2-clause
oliverlee/phobos,oliverlee/phobos,oliverlee/phobos,oliverlee/phobos
c
## Code Before: namespace angle { template <typename T> T wrap(T angle) { angle = std::fmod(angle, boost::math::constants::two_pi<T>()); if (angle >= boost::math::constants::pi<T>()) { angle -= boost::math::constants::two_pi<T>(); } if (angle < -boost::math::constants::pi<T>()) { angle += boost::math::constants::two_pi<T>(); } return angle; } /* * Get angle from encoder count (enccnt_t is uint32_t) * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative * values for any count over half a revolution. */ template <typename T> T encoder_count(const Encoder& encoder) { auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count()); auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); if (position > rev / 2) { position -= rev; } return static_cast<T>(position) / rev * boost::math::constants::two_pi<T>(); } } // namespace angle ## Instruction: Add function to obtain encoder angular rate Add function to angle namespace to obtain encoder angular rate in rad/s. This requires that the encoder object has a velocity() member function which means only EncoderFoaw for now. ## Code After: namespace angle { template <typename T> T wrap(T angle) { angle = std::fmod(angle, boost::math::constants::two_pi<T>()); if (angle >= boost::math::constants::pi<T>()) { angle -= boost::math::constants::two_pi<T>(); } if (angle < -boost::math::constants::pi<T>()) { angle += boost::math::constants::two_pi<T>(); } return angle; } /* * Get angle from encoder count (enccnt_t is uint32_t) * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative * values for any count over half a revolution. */ template <typename T> T encoder_count(const Encoder& encoder) { auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count()); auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); if (position > rev / 2) { position -= rev; } return static_cast<T>(position) / rev * boost::math::constants::two_pi<T>(); } template <typename T, size_t N> T encoder_rate(const EncoderFoaw<T, N>& encoder) { auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); return static_cast<T>(encoder.velocity()) / rev * boost::math::constants::two_pi<T>(); } } // namespace angle
# ... existing code ... } return static_cast<T>(position) / rev * boost::math::constants::two_pi<T>(); } template <typename T, size_t N> T encoder_rate(const EncoderFoaw<T, N>& encoder) { auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev); return static_cast<T>(encoder.velocity()) / rev * boost::math::constants::two_pi<T>(); } } // namespace angle # ... rest of the code ...
ba4654cf8250921bc2f9c5a1d01dd443a8d2958d
src/test/java/com/adaptionsoft/games/uglytrivia/GameCorrectAnswerTest.java
src/test/java/com/adaptionsoft/games/uglytrivia/GameCorrectAnswerTest.java
package com.adaptionsoft.games.uglytrivia; import org.junit.Ignore; import org.junit.Test; import static org.mockito.Mockito.*; public class GameCorrectAnswerTest { @Test public void correctAnswerShouldGetACoin() { Player player = mock(Player.class); Game game = createGameWithSinglePlayer(player); game.correctAnswer(); verify(player, times(1)).answeredCorrect(); } private Game createGameWithSinglePlayer(Player player) { Players players = new Players(); players.add(player); return new Game(players, null); } @Test public void correctAnswerShouldEndTurn() { Players players = mock(Players.class); Game game = new Game(players, null); game.correctAnswer(); verify(players).changeCurrentPlayer(); } }
package com.adaptionsoft.games.uglytrivia; import org.hamcrest.core.Is; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class GameCorrectAnswerTest { @Test public void correctAnswerShouldGetACoin() { Player player = mock(Player.class); Game game = createGameWithSinglePlayer(player); game.correctAnswer(); verify(player, times(1)).answeredCorrect(); } private Game createGameWithSinglePlayer(Player player) { Players players = new Players(); players.add(player); return new Game(players, null); } @Test public void correctAnswerShouldEndTurn() { Players players = mock(Players.class); Game game = new Game(players, null); game.correctAnswer(); verify(players).changeCurrentPlayer(); } @Test @Ignore("known defect in code") public void correctAnswerShouldGetPlayerOutOfPenaltyBoxIfLucky() { Player playerInPenaltyBox = mock(Player.class); when(playerInPenaltyBox.isInPenaltyBox()).thenReturn(true); when(playerInPenaltyBox.isGettingOutOfPenaltyBox()).thenReturn(true); Game game = createGameWithSinglePlayer(playerInPenaltyBox); game.correctAnswer(); // verify(playerInPenaltyBox).exitPenaltyBox(); } // right answer with enough previous couns should end game }
Test that player is can leave penalty box when lucky, but ignored because of defect
Test that player is can leave penalty box when lucky, but ignored because of defect
Java
bsd-3-clause
codecop/ugly-trivia-kata
java
## Code Before: package com.adaptionsoft.games.uglytrivia; import org.junit.Ignore; import org.junit.Test; import static org.mockito.Mockito.*; public class GameCorrectAnswerTest { @Test public void correctAnswerShouldGetACoin() { Player player = mock(Player.class); Game game = createGameWithSinglePlayer(player); game.correctAnswer(); verify(player, times(1)).answeredCorrect(); } private Game createGameWithSinglePlayer(Player player) { Players players = new Players(); players.add(player); return new Game(players, null); } @Test public void correctAnswerShouldEndTurn() { Players players = mock(Players.class); Game game = new Game(players, null); game.correctAnswer(); verify(players).changeCurrentPlayer(); } } ## Instruction: Test that player is can leave penalty box when lucky, but ignored because of defect ## Code After: package com.adaptionsoft.games.uglytrivia; import org.hamcrest.core.Is; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class GameCorrectAnswerTest { @Test public void correctAnswerShouldGetACoin() { Player player = mock(Player.class); Game game = createGameWithSinglePlayer(player); game.correctAnswer(); verify(player, times(1)).answeredCorrect(); } private Game createGameWithSinglePlayer(Player player) { Players players = new Players(); players.add(player); return new Game(players, null); } @Test public void correctAnswerShouldEndTurn() { Players players = mock(Players.class); Game game = new Game(players, null); game.correctAnswer(); verify(players).changeCurrentPlayer(); } @Test @Ignore("known defect in code") public void correctAnswerShouldGetPlayerOutOfPenaltyBoxIfLucky() { Player playerInPenaltyBox = mock(Player.class); when(playerInPenaltyBox.isInPenaltyBox()).thenReturn(true); when(playerInPenaltyBox.isGettingOutOfPenaltyBox()).thenReturn(true); Game game = createGameWithSinglePlayer(playerInPenaltyBox); game.correctAnswer(); // verify(playerInPenaltyBox).exitPenaltyBox(); } // right answer with enough previous couns should end game }
// ... existing code ... package com.adaptionsoft.games.uglytrivia; import org.hamcrest.core.Is; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class GameCorrectAnswerTest { // ... modified code ... verify(players).changeCurrentPlayer(); } @Test @Ignore("known defect in code") public void correctAnswerShouldGetPlayerOutOfPenaltyBoxIfLucky() { Player playerInPenaltyBox = mock(Player.class); when(playerInPenaltyBox.isInPenaltyBox()).thenReturn(true); when(playerInPenaltyBox.isGettingOutOfPenaltyBox()).thenReturn(true); Game game = createGameWithSinglePlayer(playerInPenaltyBox); game.correctAnswer(); // verify(playerInPenaltyBox).exitPenaltyBox(); } // right answer with enough previous couns should end game } // ... rest of the code ...
8e149bedc5cf185cd541e6b3a20b52738ebf0edf
src/main/java/sizebay/catalog/client/model/DevolutionSummary.java
src/main/java/sizebay/catalog/client/model/DevolutionSummary.java
package sizebay.catalog.client.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class DevolutionSummary { private Long id; private long tenantId; private int insertedReturns; private int invalidReturns; private int totalReturns; }
package sizebay.catalog.client.model; import lombok.Getter; import lombok.Setter; @Getter @Setter public class DevolutionSummary { private Long id; private long tenantId; private int insertedReturns; private int invalidReturns; private int totalReturns; public DevolutionSummary(long tenantId) { this.setTenantId(tenantId); } }
Create constructor in devolutionSummary class
feat: Create constructor in devolutionSummary class
Java
apache-2.0
sizebay/Sizebay-Catalog-API-Client,sizebay/Sizebay-Catalog-API-Client
java
## Code Before: package sizebay.catalog.client.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class DevolutionSummary { private Long id; private long tenantId; private int insertedReturns; private int invalidReturns; private int totalReturns; } ## Instruction: feat: Create constructor in devolutionSummary class ## Code After: package sizebay.catalog.client.model; import lombok.Getter; import lombok.Setter; @Getter @Setter public class DevolutionSummary { private Long id; private long tenantId; private int insertedReturns; private int invalidReturns; private int totalReturns; public DevolutionSummary(long tenantId) { this.setTenantId(tenantId); } }
# ... existing code ... package sizebay.catalog.client.model; import lombok.Getter; import lombok.Setter; # ... modified code ... @Getter @Setter public class DevolutionSummary { private Long id; private long tenantId; ... private int insertedReturns; private int invalidReturns; private int totalReturns; public DevolutionSummary(long tenantId) { this.setTenantId(tenantId); } } # ... rest of the code ...
98488392bca0fb13b692cf712fffaa0d2c954a76
src/main/java/b_stream/16-example_longest_word_in_file.java
src/main/java/b_stream/16-example_longest_word_in_file.java
package b_stream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Stream<String> lines = Files.lines(Paths.get("frankenstein.txt")); System.out.println(lines.flatMap(l -> Arrays.stream(l.split("[\\P{L}]+"))) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } }
package b_stream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Pattern wordSeparator = Pattern.compile("[\\P{L}]+"); try(Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"))) { System.out.println(lines.flatMap(l -> wordSeparator.splitAsStream(l)) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } } }
Work with files in close with resources. Extract pattern for better readablity.
Work with files in close with resources. Extract pattern for better readablity.
Java
apache-2.0
eggeral/java8-examples
java
## Code Before: package b_stream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Stream<String> lines = Files.lines(Paths.get("frankenstein.txt")); System.out.println(lines.flatMap(l -> Arrays.stream(l.split("[\\P{L}]+"))) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } } ## Instruction: Work with files in close with resources. Extract pattern for better readablity. ## Code After: package b_stream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Pattern wordSeparator = Pattern.compile("[\\P{L}]+"); try(Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"))) { System.out.println(lines.flatMap(l -> wordSeparator.splitAsStream(l)) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } } }
... import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Pattern wordSeparator = Pattern.compile("[\\P{L}]+"); try(Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"))) { System.out.println(lines.flatMap(l -> wordSeparator.splitAsStream(l)) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } } } ...
c6837af1af2939965976bfb45099bf7c2407a9da
twitter_api/middleware/ghetto_oauth.py
twitter_api/middleware/ghetto_oauth.py
from django.contrib.auth.models import User import re class GhettoOAuthMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): user_id = None if 'HTTP_AUTHORIZATION' in request.META and request.META['HTTP_AUTHORIZATION'].startswith('OAuth'): m = re.search(r'oauth_token="(\d+)"', request.META['HTTP_AUTHORIZATION']) if m: user_id = m.group(1) if 'oauth_token' in request.GET: user_id = request.GET['oauth_token'] if user_id: request.user = User.objects.get(pk=user_id) return view_func(request, *view_args, **view_kwargs)
from django.contrib.auth.models import User import re class GhettoOAuthMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): user_id = self._get_token_from_header(request, 'HTTP_AUTHORIZATION') if not user_id: user_id = self._get_token_from_header(request, 'HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION') if 'oauth_token' in request.GET: user_id = request.GET['oauth_token'] if user_id: request.user = User.objects.get(pk=user_id) return view_func(request, *view_args, **view_kwargs) def _get_token_from_header(self, request, header): if header in request.META and request.META[header].startswith('OAuth'): m = re.search(r'oauth_token="(\d+)"', request.META[header]) if m: return m.group(1)
Add more HTTP headers to GhettoOauth
Add more HTTP headers to GhettoOauth The official iPhone Twitter client uses HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION when it's connecting to image upload services.
Python
bsd-2-clause
simonw/bugle_project,devfort/bugle,simonw/bugle_project,devfort/bugle,devfort/bugle
python
## Code Before: from django.contrib.auth.models import User import re class GhettoOAuthMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): user_id = None if 'HTTP_AUTHORIZATION' in request.META and request.META['HTTP_AUTHORIZATION'].startswith('OAuth'): m = re.search(r'oauth_token="(\d+)"', request.META['HTTP_AUTHORIZATION']) if m: user_id = m.group(1) if 'oauth_token' in request.GET: user_id = request.GET['oauth_token'] if user_id: request.user = User.objects.get(pk=user_id) return view_func(request, *view_args, **view_kwargs) ## Instruction: Add more HTTP headers to GhettoOauth The official iPhone Twitter client uses HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION when it's connecting to image upload services. ## Code After: from django.contrib.auth.models import User import re class GhettoOAuthMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): user_id = self._get_token_from_header(request, 'HTTP_AUTHORIZATION') if not user_id: user_id = self._get_token_from_header(request, 'HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION') if 'oauth_token' in request.GET: user_id = request.GET['oauth_token'] if user_id: request.user = User.objects.get(pk=user_id) return view_func(request, *view_args, **view_kwargs) def _get_token_from_header(self, request, header): if header in request.META and request.META[header].startswith('OAuth'): m = re.search(r'oauth_token="(\d+)"', request.META[header]) if m: return m.group(1)
// ... existing code ... class GhettoOAuthMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): user_id = self._get_token_from_header(request, 'HTTP_AUTHORIZATION') if not user_id: user_id = self._get_token_from_header(request, 'HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION') if 'oauth_token' in request.GET: user_id = request.GET['oauth_token'] if user_id: request.user = User.objects.get(pk=user_id) return view_func(request, *view_args, **view_kwargs) def _get_token_from_header(self, request, header): if header in request.META and request.META[header].startswith('OAuth'): m = re.search(r'oauth_token="(\d+)"', request.META[header]) if m: return m.group(1) // ... rest of the code ...
0948e7a25e79b01dae3c5b6cf9b0c272e2d196b7
moviepy/video/fx/scroll.py
moviepy/video/fx/scroll.py
import numpy as np def scroll(clip, h=None, w=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"): """ Scrolls horizontally or vertically a clip, e.g. to make end credits """ if h is None: h = clip.h if w is None: w = clip.w xmax = clip.w-w-1 ymax = clip.h-h-1 def f(gf,t): x = max(0, min(xmax, x_start+ np.round(x_speed*t))) y = max(0, min(ymax, y_start+ np.round(y_speed*t))) return gf(t)[y:y+h, x:x+w] return clip.fl(f, apply_to = apply_to)
import numpy as np def scroll(clip, h=None, w=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"): """ Scrolls horizontally or vertically a clip, e.g. to make end credits """ if h is None: h = clip.h if w is None: w = clip.w xmax = clip.w-w-1 ymax = clip.h-h-1 def f(gf,t): x = int(max(0, min(xmax, x_start+ np.round(x_speed*t)))) y = int(max(0, min(ymax, y_start+ np.round(y_speed*t)))) return gf(t)[y:y+h, x:x+w] return clip.fl(f, apply_to = apply_to)
Add int() wrapper to prevent floats
Add int() wrapper to prevent floats
Python
mit
Zulko/moviepy,ssteo/moviepy,kerstin/moviepy
python
## Code Before: import numpy as np def scroll(clip, h=None, w=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"): """ Scrolls horizontally or vertically a clip, e.g. to make end credits """ if h is None: h = clip.h if w is None: w = clip.w xmax = clip.w-w-1 ymax = clip.h-h-1 def f(gf,t): x = max(0, min(xmax, x_start+ np.round(x_speed*t))) y = max(0, min(ymax, y_start+ np.round(y_speed*t))) return gf(t)[y:y+h, x:x+w] return clip.fl(f, apply_to = apply_to) ## Instruction: Add int() wrapper to prevent floats ## Code After: import numpy as np def scroll(clip, h=None, w=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"): """ Scrolls horizontally or vertically a clip, e.g. to make end credits """ if h is None: h = clip.h if w is None: w = clip.w xmax = clip.w-w-1 ymax = clip.h-h-1 def f(gf,t): x = int(max(0, min(xmax, x_start+ np.round(x_speed*t)))) y = int(max(0, min(ymax, y_start+ np.round(y_speed*t)))) return gf(t)[y:y+h, x:x+w] return clip.fl(f, apply_to = apply_to)
// ... existing code ... ymax = clip.h-h-1 def f(gf,t): x = int(max(0, min(xmax, x_start+ np.round(x_speed*t)))) y = int(max(0, min(ymax, y_start+ np.round(y_speed*t)))) return gf(t)[y:y+h, x:x+w] return clip.fl(f, apply_to = apply_to) // ... rest of the code ...
eae949e483e1d30e8c11b662bb07e9d30dcf39c5
lc0049_group_anagrams.py
lc0049_group_anagrams.py
class SolutionSortedDict(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """ from collections import defaultdict # Store in a dict with sorted string->string list. anagrams_d = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagrams_d[k].append(s) return anagrams_d.values() def main(): # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print SolutionSortedDict().groupAnagrams(strs) if __name__ == '__main__': main()
class SolutionSortedAnagramDict(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """ from collections import defaultdict # Store in a dict with sorted string->string list. anagram_lists = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagram_lists[k].append(s) return anagram_lists.values() def main(): # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print SolutionSortedAnagramDict().groupAnagrams(strs) if __name__ == '__main__': main()
Revise to anagram_lists and rename to sorted anagram dict class
Revise to anagram_lists and rename to sorted anagram dict class
Python
bsd-2-clause
bowen0701/algorithms_data_structures
python
## Code Before: class SolutionSortedDict(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """ from collections import defaultdict # Store in a dict with sorted string->string list. anagrams_d = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagrams_d[k].append(s) return anagrams_d.values() def main(): # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print SolutionSortedDict().groupAnagrams(strs) if __name__ == '__main__': main() ## Instruction: Revise to anagram_lists and rename to sorted anagram dict class ## Code After: class SolutionSortedAnagramDict(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] Output Limit Exceede. Time complexity: O(n*klogk), where - n is the length of strs, - k is the lenght of the longest string. Space complexity: O(n). """ from collections import defaultdict # Store in a dict with sorted string->string list. anagram_lists = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagram_lists[k].append(s) return anagram_lists.values() def main(): # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print SolutionSortedAnagramDict().groupAnagrams(strs) if __name__ == '__main__': main()
... class SolutionSortedAnagramDict(object): def groupAnagrams(self, strs): """ :type strs: List[str] ... from collections import defaultdict # Store in a dict with sorted string->string list. anagram_lists = defaultdict(list) for s in strs: # Use sorted string as dict key. k = ''.join(sorted(s)) anagram_lists[k].append(s) return anagram_lists.values() def main(): ... # ["bat"] # ] strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print SolutionSortedAnagramDict().groupAnagrams(strs) if __name__ == '__main__': ...
db41cf2df6c16cec5bc7834b6932a276dc49324e
arch/sparc/include/asm/asmmacro.h
arch/sparc/include/asm/asmmacro.h
/* asmmacro.h: Assembler macros. * * Copyright (C) 1996 David S. Miller ([email protected]) */ #ifndef _SPARC_ASMMACRO_H #define _SPARC_ASMMACRO_H #include <asm/btfixup.h> #include <asm/asi.h> #define GET_PROCESSOR4M_ID(reg) \ rd %tbr, %reg; \ srl %reg, 12, %reg; \ and %reg, 3, %reg; #define GET_PROCESSOR4D_ID(reg) \ lda [%g0] ASI_M_VIKING_TMP1, %reg; /* All trap entry points _must_ begin with this macro or else you * lose. It makes sure the kernel has a proper window so that * c-code can be called. */ #define SAVE_ALL_HEAD \ sethi %hi(trap_setup), %l4; \ jmpl %l4 + %lo(trap_setup), %l6; #define SAVE_ALL \ SAVE_ALL_HEAD \ nop; /* All traps low-level code here must end with this macro. */ #define RESTORE_ALL b ret_trap_entry; clr %l6; /* sun4 probably wants half word accesses to ASI_SEGMAP, while sun4c+ likes byte accesses. These are to avoid ifdef mania. */ #define lduXa lduba #define stXa stba #endif /* !(_SPARC_ASMMACRO_H) */
/* asmmacro.h: Assembler macros. * * Copyright (C) 1996 David S. Miller ([email protected]) */ #ifndef _SPARC_ASMMACRO_H #define _SPARC_ASMMACRO_H #include <asm/btfixup.h> #include <asm/asi.h> #define GET_PROCESSOR4M_ID(reg) \ rd %tbr, %reg; \ srl %reg, 12, %reg; \ and %reg, 3, %reg; #define GET_PROCESSOR4D_ID(reg) \ lda [%g0] ASI_M_VIKING_TMP1, %reg; /* All trap entry points _must_ begin with this macro or else you * lose. It makes sure the kernel has a proper window so that * c-code can be called. */ #define SAVE_ALL_HEAD \ sethi %hi(trap_setup), %l4; \ jmpl %l4 + %lo(trap_setup), %l6; #define SAVE_ALL \ SAVE_ALL_HEAD \ nop; /* All traps low-level code here must end with this macro. */ #define RESTORE_ALL b ret_trap_entry; clr %l6; #endif /* !(_SPARC_ASMMACRO_H) */
Remove ldXa and stXa defines, unused.
sparc32: Remove ldXa and stXa defines, unused. These were for sharing some MMU code between sun4 and sun4c. Signed-off-by: David S. Miller <[email protected]>
C
mit
KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,TeamVee-Kanas/android_kernel_samsung_kanas
c
## Code Before: /* asmmacro.h: Assembler macros. * * Copyright (C) 1996 David S. Miller ([email protected]) */ #ifndef _SPARC_ASMMACRO_H #define _SPARC_ASMMACRO_H #include <asm/btfixup.h> #include <asm/asi.h> #define GET_PROCESSOR4M_ID(reg) \ rd %tbr, %reg; \ srl %reg, 12, %reg; \ and %reg, 3, %reg; #define GET_PROCESSOR4D_ID(reg) \ lda [%g0] ASI_M_VIKING_TMP1, %reg; /* All trap entry points _must_ begin with this macro or else you * lose. It makes sure the kernel has a proper window so that * c-code can be called. */ #define SAVE_ALL_HEAD \ sethi %hi(trap_setup), %l4; \ jmpl %l4 + %lo(trap_setup), %l6; #define SAVE_ALL \ SAVE_ALL_HEAD \ nop; /* All traps low-level code here must end with this macro. */ #define RESTORE_ALL b ret_trap_entry; clr %l6; /* sun4 probably wants half word accesses to ASI_SEGMAP, while sun4c+ likes byte accesses. These are to avoid ifdef mania. */ #define lduXa lduba #define stXa stba #endif /* !(_SPARC_ASMMACRO_H) */ ## Instruction: sparc32: Remove ldXa and stXa defines, unused. These were for sharing some MMU code between sun4 and sun4c. Signed-off-by: David S. Miller <[email protected]> ## Code After: /* asmmacro.h: Assembler macros. * * Copyright (C) 1996 David S. Miller ([email protected]) */ #ifndef _SPARC_ASMMACRO_H #define _SPARC_ASMMACRO_H #include <asm/btfixup.h> #include <asm/asi.h> #define GET_PROCESSOR4M_ID(reg) \ rd %tbr, %reg; \ srl %reg, 12, %reg; \ and %reg, 3, %reg; #define GET_PROCESSOR4D_ID(reg) \ lda [%g0] ASI_M_VIKING_TMP1, %reg; /* All trap entry points _must_ begin with this macro or else you * lose. It makes sure the kernel has a proper window so that * c-code can be called. */ #define SAVE_ALL_HEAD \ sethi %hi(trap_setup), %l4; \ jmpl %l4 + %lo(trap_setup), %l6; #define SAVE_ALL \ SAVE_ALL_HEAD \ nop; /* All traps low-level code here must end with this macro. */ #define RESTORE_ALL b ret_trap_entry; clr %l6; #endif /* !(_SPARC_ASMMACRO_H) */
... /* All traps low-level code here must end with this macro. */ #define RESTORE_ALL b ret_trap_entry; clr %l6; #endif /* !(_SPARC_ASMMACRO_H) */ ...
df21a8558f28887b3f38a892e8c7f45c12169764
src/ansible/urls.py
src/ansible/urls.py
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ]
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
Add PlaybookFile edit view url
Add PlaybookFile edit view url
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
python
## Code Before: from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ] ## Instruction: Add PlaybookFile edit view url ## Code After: from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
// ... existing code ... from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views // ... modified code ... url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ] // ... rest of the code ...
78cb050afbd289324fea5323f39fef59d8dd13c7
cdi-injection/src/main/java/pl/dawidstepien/jee/examples/SimpleDateFormatProducer.java
cdi-injection/src/main/java/pl/dawidstepien/jee/examples/SimpleDateFormatProducer.java
package pl.dawidstepien.jee.examples; import java.text.SimpleDateFormat; import javax.enterprise.inject.Produces; import javax.inject.Inject; public class SimpleDateFormatProducer { @Inject @SimpleDatePattern private String pattern; @Produces public SimpleDateFormat produceSimpleDateFormat() { return new SimpleDateFormat(pattern); } }
package pl.dawidstepien.jee.examples; import java.text.SimpleDateFormat; import java.util.logging.Logger; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.inject.Inject; public class SimpleDateFormatProducer { @Inject Logger logger; @Inject @SimpleDatePattern private String pattern; @Produces public SimpleDateFormat produceSimpleDateFormat() { return new SimpleDateFormat(pattern); } private void objectCreated(@Disposes SimpleDateFormat simpleDateFormat) { logger.info("SimpleDateFormat object created."); } }
Add example of a disposer method
Add example of a disposer method
Java
mit
dstepien/jee7-examples
java
## Code Before: package pl.dawidstepien.jee.examples; import java.text.SimpleDateFormat; import javax.enterprise.inject.Produces; import javax.inject.Inject; public class SimpleDateFormatProducer { @Inject @SimpleDatePattern private String pattern; @Produces public SimpleDateFormat produceSimpleDateFormat() { return new SimpleDateFormat(pattern); } } ## Instruction: Add example of a disposer method ## Code After: package pl.dawidstepien.jee.examples; import java.text.SimpleDateFormat; import java.util.logging.Logger; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.inject.Inject; public class SimpleDateFormatProducer { @Inject Logger logger; @Inject @SimpleDatePattern private String pattern; @Produces public SimpleDateFormat produceSimpleDateFormat() { return new SimpleDateFormat(pattern); } private void objectCreated(@Disposes SimpleDateFormat simpleDateFormat) { logger.info("SimpleDateFormat object created."); } }
... package pl.dawidstepien.jee.examples; import java.text.SimpleDateFormat; import java.util.logging.Logger; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.inject.Inject; public class SimpleDateFormatProducer { @Inject Logger logger; @Inject @SimpleDatePattern private String pattern; ... public SimpleDateFormat produceSimpleDateFormat() { return new SimpleDateFormat(pattern); } private void objectCreated(@Disposes SimpleDateFormat simpleDateFormat) { logger.info("SimpleDateFormat object created."); } } ...
83f1dab96d5e9f82137dbe4142ed415a3e3e3f48
biobox_cli/biobox_file.py
biobox_cli/biobox_file.py
import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def get_biobox_file_contents(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : ref}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_} def create_biobox_directory(content): import tempfile as tmp dir_ = tmp.mkdtemp() with open(os.path.join(dir_, "biobox.yaml"), "w") as f: f.write(content) return dir_
import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def get_biobox_file_contents(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : ref}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_}
Remove no longer needed biobox_directory function
Remove no longer needed biobox_directory function
Python
mit
michaelbarton/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface,bioboxes/command-line-interface
python
## Code Before: import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def get_biobox_file_contents(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : ref}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_} def create_biobox_directory(content): import tempfile as tmp dir_ = tmp.mkdtemp() with open(os.path.join(dir_, "biobox.yaml"), "w") as f: f.write(content) return dir_ ## Instruction: Remove no longer needed biobox_directory function ## Code After: import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def get_biobox_file_contents(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : ref}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_}
# ... existing code ... def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_} # ... rest of the code ...
366ecdd77520004c307cbbf127bb374ab546ce7e
run-quince.py
run-quince.py
import os os.environ["QT_API"] = 'pyqt5' from qtpy.QtWidgets import QApplication import sys import argparse from quince.view import * if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help='Measurement library filename') args = parser.parse_args() app = QApplication([]) # Setup icon png_path = os.path.join(os.path.dirname(__file__), "assets/quince_icon.png") app.setWindowIcon(QIcon(png_path)) window = NodeWindow() window.load_yaml(args.filename) app.aboutToQuit.connect(window.cleanup) window.show() sys.exit(app.exec_())
import os os.environ["QT_API"] = 'pyqt5' from qtpy.QtWidgets import QApplication import sys import argparse import ctypes from quince.view import * if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help='Measurement library filename') args = parser.parse_args() app = QApplication([]) # Setup icon png_path = os.path.join(os.path.dirname(__file__), "assets/quince_icon.png") app.setWindowIcon(QIcon(png_path)) # Convince windows that this is a separate application to get the task bar icon working # https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7/1552105#1552105 if (os.name == 'nt'): myappid = u'BBN.quince.gui.0001' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) window = NodeWindow() window.load_yaml(args.filename) app.aboutToQuit.connect(window.cleanup) window.show() sys.exit(app.exec_())
Use windows API to change the AppID and use our icon.
Use windows API to change the AppID and use our icon.
Python
apache-2.0
BBN-Q/Quince
python
## Code Before: import os os.environ["QT_API"] = 'pyqt5' from qtpy.QtWidgets import QApplication import sys import argparse from quince.view import * if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help='Measurement library filename') args = parser.parse_args() app = QApplication([]) # Setup icon png_path = os.path.join(os.path.dirname(__file__), "assets/quince_icon.png") app.setWindowIcon(QIcon(png_path)) window = NodeWindow() window.load_yaml(args.filename) app.aboutToQuit.connect(window.cleanup) window.show() sys.exit(app.exec_()) ## Instruction: Use windows API to change the AppID and use our icon. ## Code After: import os os.environ["QT_API"] = 'pyqt5' from qtpy.QtWidgets import QApplication import sys import argparse import ctypes from quince.view import * if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help='Measurement library filename') args = parser.parse_args() app = QApplication([]) # Setup icon png_path = os.path.join(os.path.dirname(__file__), "assets/quince_icon.png") app.setWindowIcon(QIcon(png_path)) # Convince windows that this is a separate application to get the task bar icon working # https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7/1552105#1552105 if (os.name == 'nt'): myappid = u'BBN.quince.gui.0001' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) window = NodeWindow() window.load_yaml(args.filename) app.aboutToQuit.connect(window.cleanup) window.show() sys.exit(app.exec_())
# ... existing code ... from qtpy.QtWidgets import QApplication import sys import argparse import ctypes from quince.view import * # ... modified code ... png_path = os.path.join(os.path.dirname(__file__), "assets/quince_icon.png") app.setWindowIcon(QIcon(png_path)) # Convince windows that this is a separate application to get the task bar icon working # https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7/1552105#1552105 if (os.name == 'nt'): myappid = u'BBN.quince.gui.0001' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) window = NodeWindow() window.load_yaml(args.filename) app.aboutToQuit.connect(window.cleanup) # ... rest of the code ...
88f2af04e74e7f90e746958c43315da956b9bff4
src/main/java/org/moonlightcontroller/main/Main.java
src/main/java/org/moonlightcontroller/main/Main.java
package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("/home/tilon/Workspace/Moonlight/ml-temp/src/main/resources/apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } }
package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("./apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } }
Fix apps path for experiment
Fix apps path for experiment
Java
apache-2.0
til0n/ml-temp,til0n/ml-temp
java
## Code Before: package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("/home/tilon/Workspace/Moonlight/ml-temp/src/main/resources/apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } } ## Instruction: Fix apps path for experiment ## Code After: package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("./apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } }
// ... existing code ... } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("./apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); // ... rest of the code ...
83fed17149a8b65491b3f418a9f147e3ffe46e9d
prepare_data.py
prepare_data.py
class data_preparer(): def __init__():
import csv import pandas class data_preparer(): def __init__(self): pass def load(self, filename): # X = pandas.DataFrame() # with open(filename) as csvfile: # filereader = csv.reader(csvfile,delimiter=',') X = pandas.read_csv(filename) return X
Use 'pandas.read_csv' method to create dataframe
feat: Use 'pandas.read_csv' method to create dataframe
Python
mit
bwc126/MLND-Subvocal
python
## Code Before: class data_preparer(): def __init__(): ## Instruction: feat: Use 'pandas.read_csv' method to create dataframe ## Code After: import csv import pandas class data_preparer(): def __init__(self): pass def load(self, filename): # X = pandas.DataFrame() # with open(filename) as csvfile: # filereader = csv.reader(csvfile,delimiter=',') X = pandas.read_csv(filename) return X
// ... existing code ... import csv import pandas class data_preparer(): def __init__(self): pass def load(self, filename): # X = pandas.DataFrame() # with open(filename) as csvfile: # filereader = csv.reader(csvfile,delimiter=',') X = pandas.read_csv(filename) return X // ... rest of the code ...
fdc0bb75271b90a31072f79b95283e1156d50181
waffle/decorators.py
waffle/decorators.py
from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active = is_active(request, flag_name) @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if not active: raise Http404 return view(request, *args, **kwargs) return _wrapped_view return decorator
from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active = is_active(request, flag_name) if not active: raise Http404 return view(request, *args, **kwargs) return _wrapped_view return decorator
Make the decorator actually work again.
Make the decorator actually work again.
Python
bsd-3-clause
isotoma/django-waffle,TwigWorld/django-waffle,rlr/django-waffle,webus/django-waffle,groovecoder/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,safarijv/django-waffle,paulcwatts/django-waffle,JeLoueMonCampingCar/django-waffle,11craft/django-waffle,festicket/django-waffle,styleseat/django-waffle,mark-adams/django-waffle,rodgomes/django-waffle,crccheck/django-waffle,mark-adams/django-waffle,webus/django-waffle,groovecoder/django-waffle,mwaaas/django-waffle-session,hwkns/django-waffle,VladimirFilonov/django-waffle,ekohl/django-waffle,festicket/django-waffle,paulcwatts/django-waffle,TwigWorld/django-waffle,mwaaas/django-waffle-session,VladimirFilonov/django-waffle,rlr/django-waffle,willkg/django-waffle,engagespark/django-waffle,hwkns/django-waffle,crccheck/django-waffle,JeLoueMonCampingCar/django-waffle,TwigWorld/django-waffle,hwkns/django-waffle,safarijv/django-waffle,webus/django-waffle,rodgomes/django-waffle,engagespark/django-waffle,safarijv/django-waffle,festicket/django-waffle,groovecoder/django-waffle,styleseat/django-waffle,mwaaas/django-waffle-session,mark-adams/django-waffle,paulcwatts/django-waffle,VladimirFilonov/django-waffle,webus/django-waffle,rlr/django-waffle,willkg/django-waffle,ilanbm/django-waffle,festicket/django-waffle,crccheck/django-waffle,rodgomes/django-waffle,ilanbm/django-waffle,ekohl/django-waffle,groovecoder/django-waffle,hwkns/django-waffle,isotoma/django-waffle,11craft/django-waffle,rlr/django-waffle,ilanbm/django-waffle,JeLoueMonCampingCar/django-waffle,isotoma/django-waffle,paulcwatts/django-waffle,VladimirFilonov/django-waffle,engagespark/django-waffle,engagespark/django-waffle,rsalmaso/django-waffle,styleseat/django-waffle,mark-adams/django-waffle,rsalmaso/django-waffle,isotoma/django-waffle,rsalmaso/django-waffle,rsalmaso/django-waffle,rodgomes/django-waffle,mwaaas/django-waffle-session,styleseat/django-waffle,ilanbm/django-waffle,safarijv/django-waffle
python
## Code Before: from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active = is_active(request, flag_name) @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if not active: raise Http404 return view(request, *args, **kwargs) return _wrapped_view return decorator ## Instruction: Make the decorator actually work again. ## Code After: from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active = is_active(request, flag_name) if not active: raise Http404 return view(request, *args, **kwargs) return _wrapped_view return decorator
... def waffle(flag_name): def decorator(view): @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active = is_active(request, flag_name) if not active: raise Http404 return view(request, *args, **kwargs) ...
9737eced8e2d667e3413a7d65946658d94f5868c
yg/emanate/__init__.py
yg/emanate/__init__.py
from .events import Event __author__ = 'YouGov, plc' __email__ = '[email protected]' __version__ = '0.3.0' __all__ = ['Event']
from .events import Event __author__ = 'YouGov, plc' __email__ = '[email protected]' __all__ = ['Event'] try: import pkg_resources dist = pkg_resources.get_distribution('yg.emanate') __version__ = dist.version except Exception: __version__ = 'unknown'
Load the version from the package metadata rather than trying to maintain it in a third place.
Load the version from the package metadata rather than trying to maintain it in a third place.
Python
mit
yougov/emanate
python
## Code Before: from .events import Event __author__ = 'YouGov, plc' __email__ = '[email protected]' __version__ = '0.3.0' __all__ = ['Event'] ## Instruction: Load the version from the package metadata rather than trying to maintain it in a third place. ## Code After: from .events import Event __author__ = 'YouGov, plc' __email__ = '[email protected]' __all__ = ['Event'] try: import pkg_resources dist = pkg_resources.get_distribution('yg.emanate') __version__ = dist.version except Exception: __version__ = 'unknown'
... __author__ = 'YouGov, plc' __email__ = '[email protected]' __all__ = ['Event'] try: import pkg_resources dist = pkg_resources.get_distribution('yg.emanate') __version__ = dist.version except Exception: __version__ = 'unknown' ...
1650c9d9620ba9b9262598d3a47208c6c8180768
app/views.py
app/views.py
from flask import render_template, jsonify from app import app from models import Show, Episode @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route("/api/new-episodes/") def new_episodes(): data = { "items": [] } for episode in Episode.query.filter_by(showcase=True).all(): d = episode.to_api_dict() d['show'] = episode.getShow() d['show_slug'] = episode.getShowSlug() d['image'] = episode.getImage() data["items"].append(d) return jsonify(data) @app.route("/api/shows/") def shows(): shows_dict = { "shows": [] } for show in Show.query.order_by('name').all(): shows_dict["shows"].append(show.to_api_dict()) return jsonify(shows_dict) @app.route("/api/shows/<slug>") def episodes(slug): show = Show.query.filter_by(slug=slug).first() show_dict = show.to_api_dict() show_dict['episodes'] = [] for episode in show.get_episodes(): show_dict['episodes'].append(episode.to_api_dict()) return jsonify(show_dict)
from flask import render_template, jsonify from app import app from models import Show, Episode @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route("/api/new-episodes/") def new_episodes(): # Return all episodes with showcase set to True. data = { "items": [] } for episode in Episode.query.filter_by(showcase=True).all(): d = episode.to_api_dict() d['show'] = episode.getShow() d['show_slug'] = episode.getShowSlug() d['image'] = episode.getImage() data["items"].append(d) return jsonify(data) @app.route("/api/shows/") def shows(): shows_dict = { "shows": [] } for show in Show.query.order_by('name').all(): if show.published: shows_dict["shows"].append(show.to_api_dict()) return jsonify(shows_dict) @app.route("/api/shows/<slug>") def episodes(slug): show = Show.query.filter_by(slug=slug).first() show_dict = show.to_api_dict() show_dict['episodes'] = [] for episode in show.get_episodes(): if show.published: show_dict['episodes'].append(episode.to_api_dict()) return jsonify(show_dict)
Make shows and episodes only appear if published is true.
Make shows and episodes only appear if published is true.
Python
mit
frequencyasia/website,frequencyasia/website
python
## Code Before: from flask import render_template, jsonify from app import app from models import Show, Episode @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route("/api/new-episodes/") def new_episodes(): data = { "items": [] } for episode in Episode.query.filter_by(showcase=True).all(): d = episode.to_api_dict() d['show'] = episode.getShow() d['show_slug'] = episode.getShowSlug() d['image'] = episode.getImage() data["items"].append(d) return jsonify(data) @app.route("/api/shows/") def shows(): shows_dict = { "shows": [] } for show in Show.query.order_by('name').all(): shows_dict["shows"].append(show.to_api_dict()) return jsonify(shows_dict) @app.route("/api/shows/<slug>") def episodes(slug): show = Show.query.filter_by(slug=slug).first() show_dict = show.to_api_dict() show_dict['episodes'] = [] for episode in show.get_episodes(): show_dict['episodes'].append(episode.to_api_dict()) return jsonify(show_dict) ## Instruction: Make shows and episodes only appear if published is true. ## Code After: from flask import render_template, jsonify from app import app from models import Show, Episode @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route("/api/new-episodes/") def new_episodes(): # Return all episodes with showcase set to True. data = { "items": [] } for episode in Episode.query.filter_by(showcase=True).all(): d = episode.to_api_dict() d['show'] = episode.getShow() d['show_slug'] = episode.getShowSlug() d['image'] = episode.getImage() data["items"].append(d) return jsonify(data) @app.route("/api/shows/") def shows(): shows_dict = { "shows": [] } for show in Show.query.order_by('name').all(): if show.published: shows_dict["shows"].append(show.to_api_dict()) return jsonify(shows_dict) @app.route("/api/shows/<slug>") def episodes(slug): show = Show.query.filter_by(slug=slug).first() show_dict = show.to_api_dict() show_dict['episodes'] = [] for episode in show.get_episodes(): if show.published: show_dict['episodes'].append(episode.to_api_dict()) return jsonify(show_dict)
... @app.route("/api/new-episodes/") def new_episodes(): # Return all episodes with showcase set to True. data = { "items": [] } ... "shows": [] } for show in Show.query.order_by('name').all(): if show.published: shows_dict["shows"].append(show.to_api_dict()) return jsonify(shows_dict) @app.route("/api/shows/<slug>") ... show_dict = show.to_api_dict() show_dict['episodes'] = [] for episode in show.get_episodes(): if show.published: show_dict['episodes'].append(episode.to_api_dict()) return jsonify(show_dict) ...
eef628750711b8bb4b08eb5f913b731d76541ab1
shop_catalog/filters.py
shop_catalog/filters.py
from __future__ import unicode_literals from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ from shop_catalog.models import Product class ProductParentListFilter(SimpleListFilter): title = _('Parent') parameter_name = 'parent' def lookups(self, request, model_admin): lookups = () for product in Product.objects.all(): if product.is_group: lookups += (product.pk, product.get_name()), return lookups def queryset(self, request, queryset): if self.value(): try: return queryset.get(pk=self.value()).variants.all() except Product.DoesNotExist: pass return queryset
from __future__ import unicode_literals from django.db.models import Q from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ from shop_catalog.models import Product class ProductParentListFilter(SimpleListFilter): title = _('Parent') parameter_name = 'parent' def lookups(self, request, model_admin): lookups = () for product in Product.objects.all(): if product.is_group: lookups += (product.pk, product.get_name()), return lookups def queryset(self, request, queryset): if self.value(): queryset = queryset.filter( Q(pk=self.value()) | Q(parent_id=self.value())) return queryset
Modify parent filter to return variants and self
Modify parent filter to return variants and self
Python
bsd-3-clause
dinoperovic/django-shop-catalog,dinoperovic/django-shop-catalog
python
## Code Before: from __future__ import unicode_literals from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ from shop_catalog.models import Product class ProductParentListFilter(SimpleListFilter): title = _('Parent') parameter_name = 'parent' def lookups(self, request, model_admin): lookups = () for product in Product.objects.all(): if product.is_group: lookups += (product.pk, product.get_name()), return lookups def queryset(self, request, queryset): if self.value(): try: return queryset.get(pk=self.value()).variants.all() except Product.DoesNotExist: pass return queryset ## Instruction: Modify parent filter to return variants and self ## Code After: from __future__ import unicode_literals from django.db.models import Q from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ from shop_catalog.models import Product class ProductParentListFilter(SimpleListFilter): title = _('Parent') parameter_name = 'parent' def lookups(self, request, model_admin): lookups = () for product in Product.objects.all(): if product.is_group: lookups += (product.pk, product.get_name()), return lookups def queryset(self, request, queryset): if self.value(): queryset = queryset.filter( Q(pk=self.value()) | Q(parent_id=self.value())) return queryset
... from __future__ import unicode_literals from django.db.models import Q from django.contrib.admin import SimpleListFilter from django.utils.translation import ugettext_lazy as _ ... def queryset(self, request, queryset): if self.value(): queryset = queryset.filter( Q(pk=self.value()) | Q(parent_id=self.value())) return queryset ...
fc91e70bfa2d46ce923cdd3e2f2d591f8a5b367b
tests/test_person.py
tests/test_person.py
import unittest from classes.person import Person class PersonClassTest(unittest.TestCase): pass # def test_add_person_successfully(self): # my_class_instance = Person() # initial_person_count = len(my_class_instance.all_persons) # staff_neil = my_class_instance.add_person("Neil Armstrong", "staff", "Y") # self.assertTrue(staff_neil) # new_person_count = len(my_class_instance.all_persons) # self.assertEqual(new_person_count - initial_person_count, 1) # # def test_inputs_are_strings(self): # with self.assertRaises(ValueError, msg='Only strings are allowed as input'): # my_class_instance = Person() # my_class_instance.add_person("Fellow", "Peter", 23) # # def test_wants_accommodation_default_is_N(self): # my_class_instance = Person() # my_class_instance.add_person("Fellow", "Peter", "Musonye") # result = my_class_instance.all_persons # self.assertEqual(result[0]['fellow']['peter musonye'], 'N', msg="The value of wants_accommodation should be N if it is not provided")
import unittest from classes.person import Person class PersonClassTest(unittest.TestCase): def test_full_name_only_returns_strings(self): with self.assertRaises(ValueError, msg='Only strings are allowed as names'): my_class_instance = Person("staff", "Peter", "Musonye") my_class_instance.full_name()
Add tests for class Person
Add tests for class Person
Python
mit
peterpaints/room-allocator
python
## Code Before: import unittest from classes.person import Person class PersonClassTest(unittest.TestCase): pass # def test_add_person_successfully(self): # my_class_instance = Person() # initial_person_count = len(my_class_instance.all_persons) # staff_neil = my_class_instance.add_person("Neil Armstrong", "staff", "Y") # self.assertTrue(staff_neil) # new_person_count = len(my_class_instance.all_persons) # self.assertEqual(new_person_count - initial_person_count, 1) # # def test_inputs_are_strings(self): # with self.assertRaises(ValueError, msg='Only strings are allowed as input'): # my_class_instance = Person() # my_class_instance.add_person("Fellow", "Peter", 23) # # def test_wants_accommodation_default_is_N(self): # my_class_instance = Person() # my_class_instance.add_person("Fellow", "Peter", "Musonye") # result = my_class_instance.all_persons # self.assertEqual(result[0]['fellow']['peter musonye'], 'N', msg="The value of wants_accommodation should be N if it is not provided") ## Instruction: Add tests for class Person ## Code After: import unittest from classes.person import Person class PersonClassTest(unittest.TestCase): def test_full_name_only_returns_strings(self): with self.assertRaises(ValueError, msg='Only strings are allowed as names'): my_class_instance = Person("staff", "Peter", "Musonye") my_class_instance.full_name()
# ... existing code ... class PersonClassTest(unittest.TestCase): def test_full_name_only_returns_strings(self): with self.assertRaises(ValueError, msg='Only strings are allowed as names'): my_class_instance = Person("staff", "Peter", "Musonye") my_class_instance.full_name() # ... rest of the code ...
d19da22631536220f277e5170c936d3648cde409
src/main/java/com/faforever/api/db/SchemaVersionRepository.java
src/main/java/com/faforever/api/db/SchemaVersionRepository.java
package com.faforever.api.db; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SchemaVersionRepository extends JpaRepository<SchemaVersion, Integer> { @Query("select s.version from SchemaVersion s where s.installedRank = (select max (s.installedRank) from SchemaVersion s)") Optional<String> findMaxVersion(); }
package com.faforever.api.db; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SchemaVersionRepository extends JpaRepository<SchemaVersion, Integer> { @Query("select s.version from SchemaVersion s where s.installedRank = (select max (s.installedRank) from SchemaVersion s where s.version is not null)") Optional<String> findMaxVersion(); }
Fix crash on startup on repeatable migrations having highest rank
Fix crash on startup on repeatable migrations having highest rank
Java
mit
micheljung/faf-java-api,FAForever/faf-java-api,micheljung/faf-java-api,FAForever/faf-java-api,FAForever/faf-java-api
java
## Code Before: package com.faforever.api.db; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SchemaVersionRepository extends JpaRepository<SchemaVersion, Integer> { @Query("select s.version from SchemaVersion s where s.installedRank = (select max (s.installedRank) from SchemaVersion s)") Optional<String> findMaxVersion(); } ## Instruction: Fix crash on startup on repeatable migrations having highest rank ## Code After: package com.faforever.api.db; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SchemaVersionRepository extends JpaRepository<SchemaVersion, Integer> { @Query("select s.version from SchemaVersion s where s.installedRank = (select max (s.installedRank) from SchemaVersion s where s.version is not null)") Optional<String> findMaxVersion(); }
// ... existing code ... @Repository public interface SchemaVersionRepository extends JpaRepository<SchemaVersion, Integer> { @Query("select s.version from SchemaVersion s where s.installedRank = (select max (s.installedRank) from SchemaVersion s where s.version is not null)") Optional<String> findMaxVersion(); } // ... rest of the code ...
55960dde24a726614ebd87190e5a7275ea9e3224
bundles/es.core.redmine/src/info/elexis/server/core/redmine/internal/Constants.java
bundles/es.core.redmine/src/info/elexis/server/core/redmine/internal/Constants.java
package info.elexis.server.core.redmine.internal; public class Constants { /** * Expected environment variable containing the api key to use for the redmine connection */ public static final String ENV_VAR_REDMINE_API_KEY = "redmine.apikey"; /** * Optional environment variable containing the redmine base url to use, defaults to * <code>https://redmine.medelexis.ch</code> */ public static final String ENV_VAR_REDMINE_BASE_URL = "redmine.baseurl"; public static final String DEFAULT_REDMINE_BASE_URL = "https://redmine.medelexis.ch"; public static final String DEFAULT_REDMINE_PROJECT = "qfeedback3"; }
package info.elexis.server.core.redmine.internal; public class Constants { /** * Expected environment variable containing the api key to use for the redmine connection */ public static final String ENV_VAR_REDMINE_API_KEY = "REDMINE_APIKEY"; /** * Optional environment variable containing the redmine base url to use, defaults to * <code>https://redmine.medelexis.ch</code> */ public static final String ENV_VAR_REDMINE_BASE_URL = "REDMINE_BASEURL"; public static final String DEFAULT_REDMINE_BASE_URL = "https://redmine.medelexis.ch"; public static final String DEFAULT_REDMINE_PROJECT = "qfeedback3"; }
Refactor Redmine env constant names
[18039] Refactor Redmine env constant names
Java
epl-1.0
elexis/elexis-server,elexis/elexis-server
java
## Code Before: package info.elexis.server.core.redmine.internal; public class Constants { /** * Expected environment variable containing the api key to use for the redmine connection */ public static final String ENV_VAR_REDMINE_API_KEY = "redmine.apikey"; /** * Optional environment variable containing the redmine base url to use, defaults to * <code>https://redmine.medelexis.ch</code> */ public static final String ENV_VAR_REDMINE_BASE_URL = "redmine.baseurl"; public static final String DEFAULT_REDMINE_BASE_URL = "https://redmine.medelexis.ch"; public static final String DEFAULT_REDMINE_PROJECT = "qfeedback3"; } ## Instruction: [18039] Refactor Redmine env constant names ## Code After: package info.elexis.server.core.redmine.internal; public class Constants { /** * Expected environment variable containing the api key to use for the redmine connection */ public static final String ENV_VAR_REDMINE_API_KEY = "REDMINE_APIKEY"; /** * Optional environment variable containing the redmine base url to use, defaults to * <code>https://redmine.medelexis.ch</code> */ public static final String ENV_VAR_REDMINE_BASE_URL = "REDMINE_BASEURL"; public static final String DEFAULT_REDMINE_BASE_URL = "https://redmine.medelexis.ch"; public static final String DEFAULT_REDMINE_PROJECT = "qfeedback3"; }
// ... existing code ... /** * Expected environment variable containing the api key to use for the redmine connection */ public static final String ENV_VAR_REDMINE_API_KEY = "REDMINE_APIKEY"; /** * Optional environment variable containing the redmine base url to use, defaults to * <code>https://redmine.medelexis.ch</code> */ public static final String ENV_VAR_REDMINE_BASE_URL = "REDMINE_BASEURL"; public static final String DEFAULT_REDMINE_BASE_URL = "https://redmine.medelexis.ch"; public static final String DEFAULT_REDMINE_PROJECT = "qfeedback3"; // ... rest of the code ...
92da4abbcf1551d87192b627b3c5f44f2fe82e91
quickplots/textsize.py
quickplots/textsize.py
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return 10
"""Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return int(height)
Make very basic font size calculator
Make very basic font size calculator
Python
mit
samirelanduk/quickplots
python
## Code Before: """Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return 10 ## Instruction: Make very basic font size calculator ## Code After: """Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return int(height)
// ... existing code ... """Functions for working out what font_size text needs to be""" def get_font_size(s, width, height): return int(height) // ... rest of the code ...
83756f2f6cbbee09f9dfef908a82b9dc22c787d1
src/main/java/com/sibilantsolutions/iptools/util/Convert.java
src/main/java/com/sibilantsolutions/iptools/util/Convert.java
package com.sibilantsolutions.iptools.util; import java.nio.ByteOrder; public abstract class Convert { private Convert() {} //Prevent instantiation. static public long toNum( byte[] bytes, int offset, int length ) { return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN ); } static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder ) { long num = 0; final int endIndex = offset + length; if ( byteOrder == ByteOrder.BIG_ENDIAN ) { while ( offset < endIndex ) { char b = (char)( bytes[offset++] & 0xFF ); num <<= 8; num += b; } } else if ( byteOrder == ByteOrder.LITTLE_ENDIAN ) { for ( int i = endIndex - 1; i >= offset; i-- ) { char b = (char)( bytes[i] & 0xFF ); num <<= 8; num += b; } } else { throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder ); } return num; } }
package com.sibilantsolutions.iptools.util; import java.nio.ByteBuffer; import java.nio.ByteOrder; public abstract class Convert { private Convert() {} //Prevent instantiation. static public int byteToNum( byte b ) { return b & 0xFF; } static public int getByte( ByteBuffer bb ) { return byteToNum( bb.get() ); } static public long toNum( ByteBuffer bb, int numBytes ) { byte[] bytes = new byte[numBytes]; bb.get( bytes ); return toNum( bytes, 0, numBytes, bb.order() ); } static public long toNum( byte[] bytes, int offset, int length ) { return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN ); } static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder ) { long num = 0; final int endIndex = offset + length; if ( byteOrder == ByteOrder.BIG_ENDIAN ) { while ( offset < endIndex ) { char b = (char)( bytes[offset++] & 0xFF ); num <<= 8; num += b; } } else if ( byteOrder == ByteOrder.LITTLE_ENDIAN ) { for ( int i = endIndex - 1; i >= offset; i-- ) { char b = (char)( bytes[i] & 0xFF ); num <<= 8; num += b; } } else { throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder ); } return num; } }
Add methods to work with retrieving bytes from ByteBuffer.
Add methods to work with retrieving bytes from ByteBuffer.
Java
apache-2.0
jtgeiger/iptools
java
## Code Before: package com.sibilantsolutions.iptools.util; import java.nio.ByteOrder; public abstract class Convert { private Convert() {} //Prevent instantiation. static public long toNum( byte[] bytes, int offset, int length ) { return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN ); } static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder ) { long num = 0; final int endIndex = offset + length; if ( byteOrder == ByteOrder.BIG_ENDIAN ) { while ( offset < endIndex ) { char b = (char)( bytes[offset++] & 0xFF ); num <<= 8; num += b; } } else if ( byteOrder == ByteOrder.LITTLE_ENDIAN ) { for ( int i = endIndex - 1; i >= offset; i-- ) { char b = (char)( bytes[i] & 0xFF ); num <<= 8; num += b; } } else { throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder ); } return num; } } ## Instruction: Add methods to work with retrieving bytes from ByteBuffer. ## Code After: package com.sibilantsolutions.iptools.util; import java.nio.ByteBuffer; import java.nio.ByteOrder; public abstract class Convert { private Convert() {} //Prevent instantiation. static public int byteToNum( byte b ) { return b & 0xFF; } static public int getByte( ByteBuffer bb ) { return byteToNum( bb.get() ); } static public long toNum( ByteBuffer bb, int numBytes ) { byte[] bytes = new byte[numBytes]; bb.get( bytes ); return toNum( bytes, 0, numBytes, bb.order() ); } static public long toNum( byte[] bytes, int offset, int length ) { return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN ); } static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder ) { long num = 0; final int endIndex = offset + length; if ( byteOrder == ByteOrder.BIG_ENDIAN ) { while ( offset < endIndex ) { char b = (char)( bytes[offset++] & 0xFF ); num <<= 8; num += b; } } else if ( byteOrder == ByteOrder.LITTLE_ENDIAN ) { for ( int i = endIndex - 1; i >= offset; i-- ) { char b = (char)( bytes[i] & 0xFF ); num <<= 8; num += b; } } else { throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder ); } return num; } }
... package com.sibilantsolutions.iptools.util; import java.nio.ByteBuffer; import java.nio.ByteOrder; public abstract class Convert ... { private Convert() {} //Prevent instantiation. static public int byteToNum( byte b ) { return b & 0xFF; } static public int getByte( ByteBuffer bb ) { return byteToNum( bb.get() ); } static public long toNum( ByteBuffer bb, int numBytes ) { byte[] bytes = new byte[numBytes]; bb.get( bytes ); return toNum( bytes, 0, numBytes, bb.order() ); } static public long toNum( byte[] bytes, int offset, int length ) { ...
03cb0d30b60c3702edc0752fe535abb1ae41a32d
src/controllers/chooseyourcat.c
src/controllers/chooseyourcat.c
NEW_CONTROLLER(ChooseYourCat); static void p1_confirm() { Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } static void p2_confirm() { Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } static void ChooseYourCatController_init() { EVENT_ASSOCIATE(press, P1_MARU, p1_confirm); EVENT_ASSOCIATE(press, P2_MARU, p2_confirm); logprint(success_msg); }
static int P1_HAS_CHOSEN = false; /* false -> P1 escolhe o gato; true -> P2 escolhe o gato. */ NEW_CONTROLLER(ChooseYourCat); static void p1_confirm() { if (!P1_HAS_CHOSEN) { Sound_playSE(FX_SELECT); P1_HAS_CHOSEN = true; } } static void p2_confirm() { if (P1_HAS_CHOSEN) { /* code */ Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } } static void ChooseYourCatController_init() { EVENT_ASSOCIATE(press, P1_MARU, p1_confirm); EVENT_ASSOCIATE(press, P2_MARU, p2_confirm); logprint(success_msg); }
Add step for each player on choose your cat scene
Add step for each player on choose your cat scene
C
mit
OrenjiAkira/spacegame,OrenjiAkira/spacegame,OrenjiAkira/spacegame
c
## Code Before: NEW_CONTROLLER(ChooseYourCat); static void p1_confirm() { Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } static void p2_confirm() { Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } static void ChooseYourCatController_init() { EVENT_ASSOCIATE(press, P1_MARU, p1_confirm); EVENT_ASSOCIATE(press, P2_MARU, p2_confirm); logprint(success_msg); } ## Instruction: Add step for each player on choose your cat scene ## Code After: static int P1_HAS_CHOSEN = false; /* false -> P1 escolhe o gato; true -> P2 escolhe o gato. */ NEW_CONTROLLER(ChooseYourCat); static void p1_confirm() { if (!P1_HAS_CHOSEN) { Sound_playSE(FX_SELECT); P1_HAS_CHOSEN = true; } } static void p2_confirm() { if (P1_HAS_CHOSEN) { /* code */ Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } } static void ChooseYourCatController_init() { EVENT_ASSOCIATE(press, P1_MARU, p1_confirm); EVENT_ASSOCIATE(press, P2_MARU, p2_confirm); logprint(success_msg); }
// ... existing code ... static int P1_HAS_CHOSEN = false; /* false -> P1 escolhe o gato; true -> P2 escolhe o gato. */ NEW_CONTROLLER(ChooseYourCat); static void p1_confirm() { if (!P1_HAS_CHOSEN) { Sound_playSE(FX_SELECT); P1_HAS_CHOSEN = true; } } static void p2_confirm() { if (P1_HAS_CHOSEN) { /* code */ Sound_playSE(FX_SELECT); Scene_close(); Scene_load(SCENE_PRESSSTART); } } static void ChooseYourCatController_init() { // ... rest of the code ...
7c38eae5a07e07789713baf5ab3aaea772e76422
routes.py
routes.py
from flask import Flask, render_template, redirect import psycopg2 import os import urlparse app = Flask(__name__) # def connectDB(wrapped): # def inner(*args, **kwargs): # api_token = os.environ["API_TOKEN"] # urlparse.uses_netloc.append("postgres") # url = urlparse.urlparse(os.environ["DATABASE_URL"]) # conn = psycopg2.connect( # database=url.path[1:], # user=url.username, # password=url.password, # host=url.hostname, # port=url.port # ) # cur = conn.cursor() # ret = wrapped(*args, **kwargs) # return ret # return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') # @connectDB def participants(): return render_template('participants.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) # @connectDB def complete(): return redirect('/')
from flask import Flask, render_template, redirect, request import psycopg2 from functools import wraps import os import urlparse app = Flask(__name__) def connectDB(wrapped): @wraps(wrapped) def inner(*args, **kwargs): urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) cur = conn.cursor() return wrapped(cur, *args, **kwargs) return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') @connectDB def participants(*args): return args[0] @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) @connectDB def complete(*args): return render_template('/success.html')
Add decorator to connect to database
Add decorator to connect to database
Python
mit
AlexMathew/csipy-home
python
## Code Before: from flask import Flask, render_template, redirect import psycopg2 import os import urlparse app = Flask(__name__) # def connectDB(wrapped): # def inner(*args, **kwargs): # api_token = os.environ["API_TOKEN"] # urlparse.uses_netloc.append("postgres") # url = urlparse.urlparse(os.environ["DATABASE_URL"]) # conn = psycopg2.connect( # database=url.path[1:], # user=url.username, # password=url.password, # host=url.hostname, # port=url.port # ) # cur = conn.cursor() # ret = wrapped(*args, **kwargs) # return ret # return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') # @connectDB def participants(): return render_template('participants.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) # @connectDB def complete(): return redirect('/') ## Instruction: Add decorator to connect to database ## Code After: from flask import Flask, render_template, redirect, request import psycopg2 from functools import wraps import os import urlparse app = Flask(__name__) def connectDB(wrapped): @wraps(wrapped) def inner(*args, **kwargs): urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) cur = conn.cursor() return wrapped(cur, *args, **kwargs) return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') @connectDB def participants(*args): return args[0] @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) @connectDB def complete(*args): return render_template('/success.html')
# ... existing code ... from flask import Flask, render_template, redirect, request import psycopg2 from functools import wraps import os import urlparse app = Flask(__name__) def connectDB(wrapped): @wraps(wrapped) def inner(*args, **kwargs): urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) cur = conn.cursor() return wrapped(cur, *args, **kwargs) return inner @app.route('/') # ... modified code ... @app.route('/participants') @connectDB def participants(*args): return args[0] @app.route('/setup') ... @app.route('/complete', methods=['POST']) @connectDB def complete(*args): return render_template('/success.html') # ... rest of the code ...
027e78f3e88a17e05881259d1f29d472b02d0d3a
doc/source/scripts/titles.py
doc/source/scripts/titles.py
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line) if '.. toctree::' in line: if z: handle.write(' :maxdepth: {}\n'.format(z)) else: z += 1
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line)
Change to 3 spaces in front of toctree elements
Change to 3 spaces in front of toctree elements
Python
mit
AdamGagorik/pydarkstar
python
## Code Before: import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line) if '.. toctree::' in line: if z: handle.write(' :maxdepth: {}\n'.format(z)) else: z += 1 ## Instruction: Change to 3 spaces in front of toctree elements ## Code After: import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line)
// ... existing code ... line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line) // ... rest of the code ...
ae00c60510e28c0852ac6ad14bab86563b5e1399
mica/common.py
mica/common.py
import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1]
import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
Use os.pathsep instead of ':' for windows compat
Use os.pathsep instead of ':' for windows compat
Python
bsd-3-clause
sot/mica,sot/mica
python
## Code Before: import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1] ## Instruction: Use os.pathsep instead of ':' for windows compat ## Code After: import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
// ... existing code ... # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1] // ... rest of the code ...
84b907ad78f03d614e8af14578c21e1228ab723d
top.py
top.py
from api_connector import * from csv_io import * def main(): conn = ApiConnector() csvio = CsvIo() article_list = conn.get_top() stories = [] for i in article_list: try: story = conn.get_item(i) if story.get("deleted"): continue print csvio.story_to_csv(story) stories.append(story) except NetworkError as e: print e csvio.write_stories_csv(stories) for story in stories: try: conn.get_kids(story) except NetworkError as e: print e users = [] for u in sorted(conn.user_dict.keys()): try: userjson = conn.get_user(u) users.append(userjson) print u except NetworkError as e: print e csvio.write_users_csv(users) if __name__ == '__main__': main() CsvIo().concat_users() CsvIo().concat_stories()
from api_connector import * from csv_io import * def main(): conn = ApiConnector() csvio = CsvIo() article_list = conn.get_top() stories = [] for i in article_list: try: story = conn.get_item(i) if story.get("deleted"): continue print csvio.story_to_csv(story) stories.append(story) except NetworkError as e: print e csvio.write_stories_csv(stories) for story in stories: try: conn.get_kids(story) except NetworkError as e: print e users = [] for u in sorted(conn.user_dict.keys()): try: userjson = conn.get_user(u) users.append(userjson) print u except NetworkError as e: print e csvio.write_users_csv(users) if __name__ == '__main__': csvio = CsvIo() main() csvio.concat_users() csvio.concat_stories()
Use common object for csvio calls
Use common object for csvio calls
Python
apache-2.0
rylans/hackernews-top,davande/hackernews-top
python
## Code Before: from api_connector import * from csv_io import * def main(): conn = ApiConnector() csvio = CsvIo() article_list = conn.get_top() stories = [] for i in article_list: try: story = conn.get_item(i) if story.get("deleted"): continue print csvio.story_to_csv(story) stories.append(story) except NetworkError as e: print e csvio.write_stories_csv(stories) for story in stories: try: conn.get_kids(story) except NetworkError as e: print e users = [] for u in sorted(conn.user_dict.keys()): try: userjson = conn.get_user(u) users.append(userjson) print u except NetworkError as e: print e csvio.write_users_csv(users) if __name__ == '__main__': main() CsvIo().concat_users() CsvIo().concat_stories() ## Instruction: Use common object for csvio calls ## Code After: from api_connector import * from csv_io import * def main(): conn = ApiConnector() csvio = CsvIo() article_list = conn.get_top() stories = [] for i in article_list: try: story = conn.get_item(i) if story.get("deleted"): continue print csvio.story_to_csv(story) stories.append(story) except NetworkError as e: print e csvio.write_stories_csv(stories) for story in stories: try: conn.get_kids(story) except NetworkError as e: print e users = [] for u in sorted(conn.user_dict.keys()): try: userjson = conn.get_user(u) users.append(userjson) print u except NetworkError as e: print e csvio.write_users_csv(users) if __name__ == '__main__': csvio = CsvIo() main() csvio.concat_users() csvio.concat_stories()
... csvio.write_users_csv(users) if __name__ == '__main__': csvio = CsvIo() main() csvio.concat_users() csvio.concat_stories() ...
fe41ecce4b840374a561bbef0bbf4ad465e66180
tests/ml/test_fasttext_helpers.py
tests/ml/test_fasttext_helpers.py
import pandas import unittest import cocoscore.ml.fasttext_helpers as fth class CVTest(unittest.TestCase): train_path = 'ft_simple_test.txt' ft_path = '/home/lib/fastText' model_path = 'testmodel' def test_train_call_parameters(self): train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa': 1.0}, self.ft_path, self.model_path, thread=5) expected_train_call = self.ft_path + ' supervised -input ' + self.train_path + ' -output ' + self.model_path + \ ' -aaa 1.0 -thread 5 ' self.assertEqual(train_call, expected_train_call) expected_compress_call = self.ft_path + ' quantize -input ' + self.model_path + ' -output ' + self.model_path self.assertEqual(compress_call, expected_compress_call) if __name__ == '__main__': unittest.main()
import pandas import unittest import cocoscore.ml.fasttext_helpers as fth class CVTest(unittest.TestCase): train_path = 'ft_simple_test.txt' ft_path = '/home/lib/fastText' model_path = 'testmodel' test_path = 'ft_simple_test.txt' probability_path = 'ft_simple_prob.txt' def test_train_call_parameters(self): train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa': 1.0}, self.ft_path, self.model_path, thread=5) expected_train_call = self.ft_path + ' supervised -input ' + self.train_path + ' -output ' + self.model_path + \ ' -aaa 1.0 -thread 5 ' self.assertEqual(train_call, expected_train_call) expected_compress_call = self.ft_path + ' quantize -input ' + self.model_path + ' -output ' + self.model_path self.assertEqual(compress_call, expected_compress_call) def test_test_call_parameters(self): predict_call = fth.get_fasttext_test_calls(self.test_path, self.ft_path, self.model_path, self.probability_path) expected_predict_call = self.ft_path + ' predict-prob ' + self.model_path + ' ' + self.test_path + ' ' + \ str(2) + ' | gzip > ' + self.probability_path self.assertEqual(predict_call, expected_predict_call) if __name__ == '__main__': unittest.main()
Add unittest for testing file path
Add unittest for testing file path
Python
mit
JungeAlexander/cocoscore
python
## Code Before: import pandas import unittest import cocoscore.ml.fasttext_helpers as fth class CVTest(unittest.TestCase): train_path = 'ft_simple_test.txt' ft_path = '/home/lib/fastText' model_path = 'testmodel' def test_train_call_parameters(self): train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa': 1.0}, self.ft_path, self.model_path, thread=5) expected_train_call = self.ft_path + ' supervised -input ' + self.train_path + ' -output ' + self.model_path + \ ' -aaa 1.0 -thread 5 ' self.assertEqual(train_call, expected_train_call) expected_compress_call = self.ft_path + ' quantize -input ' + self.model_path + ' -output ' + self.model_path self.assertEqual(compress_call, expected_compress_call) if __name__ == '__main__': unittest.main() ## Instruction: Add unittest for testing file path ## Code After: import pandas import unittest import cocoscore.ml.fasttext_helpers as fth class CVTest(unittest.TestCase): train_path = 'ft_simple_test.txt' ft_path = '/home/lib/fastText' model_path = 'testmodel' test_path = 'ft_simple_test.txt' probability_path = 'ft_simple_prob.txt' def test_train_call_parameters(self): train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa': 1.0}, self.ft_path, self.model_path, thread=5) expected_train_call = self.ft_path + ' supervised -input ' + self.train_path + ' -output ' + self.model_path + \ ' -aaa 1.0 -thread 5 ' self.assertEqual(train_call, expected_train_call) expected_compress_call = self.ft_path + ' quantize -input ' + self.model_path + ' -output ' + self.model_path self.assertEqual(compress_call, expected_compress_call) def test_test_call_parameters(self): predict_call = fth.get_fasttext_test_calls(self.test_path, self.ft_path, self.model_path, self.probability_path) expected_predict_call = self.ft_path + ' predict-prob ' + self.model_path + ' ' + self.test_path + ' ' + \ str(2) + ' | gzip > ' + self.probability_path self.assertEqual(predict_call, expected_predict_call) if __name__ == '__main__': unittest.main()
// ... existing code ... train_path = 'ft_simple_test.txt' ft_path = '/home/lib/fastText' model_path = 'testmodel' test_path = 'ft_simple_test.txt' probability_path = 'ft_simple_prob.txt' def test_train_call_parameters(self): train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa': 1.0}, self.ft_path, // ... modified code ... expected_compress_call = self.ft_path + ' quantize -input ' + self.model_path + ' -output ' + self.model_path self.assertEqual(compress_call, expected_compress_call) def test_test_call_parameters(self): predict_call = fth.get_fasttext_test_calls(self.test_path, self.ft_path, self.model_path, self.probability_path) expected_predict_call = self.ft_path + ' predict-prob ' + self.model_path + ' ' + self.test_path + ' ' + \ str(2) + ' | gzip > ' + self.probability_path self.assertEqual(predict_call, expected_predict_call) if __name__ == '__main__': unittest.main() // ... rest of the code ...
47d9217b6ee9837987d25d77cc6e3c750766ed90
tests/test_formats.py
tests/test_formats.py
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: yield self.settings(ARCHIVE_DIRECTORY=directory) def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: with self.settings(ARCHIVE_DIRECTORY=directory): yield None def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
Fix bug in temporary directory generation.
Fix bug in temporary directory generation.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
python
## Code Before: from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: yield self.settings(ARCHIVE_DIRECTORY=directory) def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive') ## Instruction: Fix bug in temporary directory generation. ## Code After: from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: with self.settings(ARCHIVE_DIRECTORY=directory): yield None def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
# ... existing code ... @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: with self.settings(ARCHIVE_DIRECTORY=directory): yield None def test_archive(self): """ # ... rest of the code ...
d52222d0eb03d651c6598cbeaee7bba09cfec305
src/main/java/com/mongodb/memphis/config/Collection.java
src/main/java/com/mongodb/memphis/config/Collection.java
package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection.withReadConcern(readConcern); } if (readPreference != null) { collection.withReadPreference(readPreference); } return collection; } }
package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection = collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection = collection.withReadConcern(readConcern); } if (readPreference != null) { collection = collection.withReadPreference(readPreference); } return collection; } }
FIX - write concerns not added to collection
FIX - write concerns not added to collection
Java
apache-2.0
dioxic-gb/memphis
java
## Code Before: package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection.withReadConcern(readConcern); } if (readPreference != null) { collection.withReadPreference(readPreference); } return collection; } } ## Instruction: FIX - write concerns not added to collection ## Code After: package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection = collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection = collection.withReadConcern(readConcern); } if (readPreference != null) { collection = collection.withReadPreference(readPreference); } return collection; } }
# ... existing code ... MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection = collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection = collection.withReadConcern(readConcern); } if (readPreference != null) { collection = collection.withReadPreference(readPreference); } return collection; # ... rest of the code ...
3a163148278870fc26c7e1bcdd803a58b0547f32
src/test/java/com/reduks/reduks/repository/FakeData.kt
src/test/java/com/reduks/reduks/repository/FakeData.kt
package com.reduks.reduks.repository import com.reduks.reduks.Action import com.reduks.reduks.Store class FakeData { companion object Provider { var store = Store( FakeState(0, ""), { state, action -> action.action(state) } ) } } data class FakeState(val id: Int, val name: String) sealed class FakeActions : Action<FakeState> { class SetValidState : FakeActions() { override fun action(state: FakeState): FakeState = FakeState(1, "Bloder") } }
package com.reduks.reduks.repository import com.reduks.reduks.Action import com.reduks.reduks.Store class FakeData { companion object Provider { var store = Store( FakeState(0, ""), { state, action -> action.action(state) } ) } } data class FakeState(val id: Int, val name: String) sealed class FakeActions : Action<FakeState> { class SetValidState : FakeActions() { override fun action(state: FakeState): FakeState = FakeState(1, "Bloder") } class EmptyAction : FakeActions() }
Create empty action as example
Create empty action as example
Kotlin
mit
Reduks/Reduks
kotlin
## Code Before: package com.reduks.reduks.repository import com.reduks.reduks.Action import com.reduks.reduks.Store class FakeData { companion object Provider { var store = Store( FakeState(0, ""), { state, action -> action.action(state) } ) } } data class FakeState(val id: Int, val name: String) sealed class FakeActions : Action<FakeState> { class SetValidState : FakeActions() { override fun action(state: FakeState): FakeState = FakeState(1, "Bloder") } } ## Instruction: Create empty action as example ## Code After: package com.reduks.reduks.repository import com.reduks.reduks.Action import com.reduks.reduks.Store class FakeData { companion object Provider { var store = Store( FakeState(0, ""), { state, action -> action.action(state) } ) } } data class FakeState(val id: Int, val name: String) sealed class FakeActions : Action<FakeState> { class SetValidState : FakeActions() { override fun action(state: FakeState): FakeState = FakeState(1, "Bloder") } class EmptyAction : FakeActions() }
... class SetValidState : FakeActions() { override fun action(state: FakeState): FakeState = FakeState(1, "Bloder") } class EmptyAction : FakeActions() } ...
f4383f964643c7fa1c4de050feaf7d134e34d814
example/people.py
example/people.py
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Person('Paul Tagliamonte', district='6', chamber='upper') p.add_committee_membership(tech, role='chairman') p.add_source('https://example.com') yield p
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Legislator('Paul Tagliamonte', '6') p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
Make it so that the example runs without error
Make it so that the example runs without error
Python
bsd-3-clause
datamade/pupa,influence-usa/pupa,rshorey/pupa,datamade/pupa,opencivicdata/pupa,rshorey/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,influence-usa/pupa
python
## Code Before: from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Person('Paul Tagliamonte', district='6', chamber='upper') p.add_committee_membership(tech, role='chairman') p.add_source('https://example.com') yield p ## Instruction: Make it so that the example runs without error ## Code After: from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Legislator('Paul Tagliamonte', '6') p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
# ... existing code ... ecom.add_source('https://example.com') yield ecom p = Legislator('Paul Tagliamonte', '6') p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p # ... rest of the code ...
249c6bbd74174b3b053fed13a58b24c8d485163a
src/ggrc/models/custom_attribute_value.py
src/ggrc/models/custom_attribute_value.py
from ggrc import db from .mixins import ( deferred, Base ) class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column( db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
Fix code style for custom attribute value
Fix code style for custom attribute value
Python
apache-2.0
plamut/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,hyperNURb/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,hasanalom/ggrc-core
python
## Code Before: from ggrc import db from .mixins import ( deferred, Base ) class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column( db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ] ## Instruction: Fix code style for custom attribute value ## Code After: from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
# ... existing code ... from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') # ... modified code ... 'attributable_id', 'attributable_type', 'attribute_value' ] # ... rest of the code ...
66b0664aa1347df44ff7a5a7aa5b35d07df54ea5
fitz/base_memory.c
fitz/base_memory.c
void * fz_malloc(int n) { void *p = malloc(n); if (!p) fz_throw("cannot malloc %d bytes", n); return p; } void * fz_realloc(void *p, int n) { void *np = realloc(p, n); if (np == nil) fz_throw("cannot realloc %d bytes", n); return np; } void fz_free(void *p) { free(p); } char * fz_strdup(char *s) { char *ns = strdup(s); if (!ns) fz_throw("cannot strdup %d bytes", strlen(s) + 1); return ns; }
void * fz_malloc(int n) { void *p = malloc(n); if (!p) fz_throw("cannot malloc %d bytes", n); return p; } void * fz_realloc(void *p, int n) { void *np = realloc(p, n); if (np == nil) fz_throw("cannot realloc %d bytes", n); return np; } void fz_free(void *p) { free(p); } char * fz_strdup(char *s) { char *ns = strdup(s); if (!ns) fz_throw("cannot strdup %lu bytes", (unsigned long)strlen(s) + 1); return ns; }
Use the correct format specifier for size_t in fz_strdup.
Use the correct format specifier for size_t in fz_strdup. Prior to this patch, if the strdup failed, it would throw an error printing the number of bytes that could not be allocated. However, this was formatted as an int, while the actual argument passed is the return value of strdup itself, which is usually a size_t. This patch formats instead as an unsigned long, and adds a cast to ensure the types match even on platforms where this isn't already the case.
C
agpl-3.0
isavin/humblepdf,clchiou/mupdf,muennich/mupdf,michaelcadilhac/pdfannot,seagullua/MuPDF,tribals/mupdf,lustersir/MuPDF,loungeup/mupdf,nqv/mupdf,PuzzleFlow/mupdf,hjiayz/forkmupdf,robamler/mupdf-nacl,benoit-pierre/mupdf,tophyr/mupdf,xiangxw/mupdf,hackqiang/mupdf,Kalp695/mupdf,MokiMobility/muPDF,zeniko/mupdf,robamler/mupdf-nacl,PuzzleFlow/mupdf,lolo32/mupdf-mirror,PuzzleFlow/mupdf,loungeup/mupdf,FabriceSalvaire/mupdf-cmake,issuestand/mupdf,loungeup/mupdf,ziel/mupdf,MokiMobility/muPDF,seagullua/MuPDF,ziel/mupdf,FabriceSalvaire/mupdf-v1.3,benoit-pierre/mupdf,Kalp695/mupdf,andyhan/mupdf,TamirEvan/mupdf,michaelcadilhac/pdfannot,andyhan/mupdf,asbloomf/mupdf,issuestand/mupdf,hjiayz/forkmupdf,robamler/mupdf-nacl,ziel/mupdf,knielsen/mupdf,FabriceSalvaire/mupdf-cmake,nqv/mupdf,lustersir/MuPDF,nqv/mupdf,wild0/opened_mupdf,derek-watson/mupdf,flipstudio/MuPDF,michaelcadilhac/pdfannot,ccxvii/mupdf,knielsen/mupdf,poor-grad-student/mupdf,derek-watson/mupdf,benoit-pierre/mupdf,muennich/mupdf,PuzzleFlow/mupdf,clchiou/mupdf,github201407/MuPDF,kobolabs/mupdf,samturneruk/mupdf_secure_android,muennich/mupdf,github201407/MuPDF,kobolabs/mupdf,knielsen/mupdf,zeniko/mupdf,zeniko/mupdf,tribals/mupdf,clchiou/mupdf,kobolabs/mupdf,flipstudio/MuPDF,cgogolin/penandpdf,clchiou/mupdf,andyhan/mupdf,poor-grad-student/mupdf,xiangxw/mupdf,ccxvii/mupdf,poor-grad-student/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,seagullua/MuPDF,Kalp695/mupdf,seagullua/MuPDF,ziel/mupdf,issuestand/mupdf,FabriceSalvaire/mupdf-cmake,tophyr/mupdf,Kalp695/mupdf,geetakaur/NewApps,lustersir/MuPDF,isavin/humblepdf,benoit-pierre/mupdf,FabriceSalvaire/mupdf-v1.3,TamirEvan/mupdf,samturneruk/mupdf_secure_android,robamler/mupdf-nacl,PuzzleFlow/mupdf,andyhan/mupdf,Kalp695/mupdf,seagullua/MuPDF,geetakaur/NewApps,wzhsunn/mupdf,clchiou/mupdf,PuzzleFlow/mupdf,fluks/mupdf-x11-bookmarks,tophyr/mupdf,hxx0215/MuPDFMirror,Kalp695/mupdf,knielsen/mupdf,issuestand/mupdf,crow-misia/mupdf,TamirEvan/mupdf,wild0/opened_mupdf,muennich/mupdf,andyhan/mupdf,lustersir/MuPDF,tribals/mupdf,xiangxw/mupdf,crow-misia/mupdf,cgogolin/penandpdf,wild0/opened_mupdf,tophyr/mupdf,samturneruk/mupdf_secure_android,sebras/mupdf,xiangxw/mupdf,lamemate/mupdf,andyhan/mupdf,wild0/opened_mupdf,TamirEvan/mupdf,hackqiang/mupdf,ArtifexSoftware/mupdf,ylixir/mupdf,ziel/mupdf,derek-watson/mupdf,tribals/mupdf,ArtifexSoftware/mupdf,flipstudio/MuPDF,fluks/mupdf-x11-bookmarks,seagullua/MuPDF,knielsen/mupdf,lamemate/mupdf,michaelcadilhac/pdfannot,github201407/MuPDF,github201407/MuPDF,isavin/humblepdf,sebras/mupdf,ccxvii/mupdf,TamirEvan/mupdf,tribals/mupdf,FabriceSalvaire/mupdf-cmake,wzhsunn/mupdf,crow-misia/mupdf,kobolabs/mupdf,fluks/mupdf-x11-bookmarks,flipstudio/MuPDF,kobolabs/mupdf,ziel/mupdf,asbloomf/mupdf,asbloomf/mupdf,Kalp695/mupdf,flipstudio/MuPDF,cgogolin/penandpdf,kobolabs/mupdf,ylixir/mupdf,lolo32/mupdf-mirror,hackqiang/mupdf,geetakaur/NewApps,isavin/humblepdf,wzhsunn/mupdf,lolo32/mupdf-mirror,wild0/opened_mupdf,sebras/mupdf,wzhsunn/mupdf,poor-grad-student/mupdf,hxx0215/MuPDFMirror,geetakaur/NewApps,lolo32/mupdf-mirror,samturneruk/mupdf_secure_android,ylixir/mupdf,geetakaur/NewApps,derek-watson/mupdf,xiangxw/mupdf,derek-watson/mupdf,derek-watson/mupdf,ylixir/mupdf,lamemate/mupdf,lolo32/mupdf-mirror,issuestand/mupdf,isavin/humblepdf,lolo32/mupdf-mirror,hxx0215/MuPDFMirror,ArtifexSoftware/mupdf,lustersir/MuPDF,FabriceSalvaire/mupdf-cmake,tophyr/mupdf,MokiMobility/muPDF,hxx0215/MuPDFMirror,zeniko/mupdf,michaelcadilhac/pdfannot,tophyr/mupdf,loungeup/mupdf,ArtifexSoftware/mupdf,wzhsunn/mupdf,robamler/mupdf-nacl,TamirEvan/mupdf,kobolabs/mupdf,ArtifexSoftware/mupdf,ccxvii/mupdf,github201407/MuPDF,TamirEvan/mupdf,hjiayz/forkmupdf,nqv/mupdf,FabriceSalvaire/mupdf-v1.3,hackqiang/mupdf,fluks/mupdf-x11-bookmarks,fluks/mupdf-x11-bookmarks,loungeup/mupdf,asbloomf/mupdf,michaelcadilhac/pdfannot,ylixir/mupdf,crow-misia/mupdf,cgogolin/penandpdf,hjiayz/forkmupdf,PuzzleFlow/mupdf,isavin/humblepdf,ccxvii/mupdf,sebras/mupdf,loungeup/mupdf,poor-grad-student/mupdf,FabriceSalvaire/mupdf-v1.3,clchiou/mupdf,samturneruk/mupdf_secure_android,hackqiang/mupdf,lamemate/mupdf,ccxvii/mupdf,asbloomf/mupdf,wild0/opened_mupdf,samturneruk/mupdf_secure_android,xiangxw/mupdf,nqv/mupdf,isavin/humblepdf,github201407/MuPDF,MokiMobility/muPDF,tribals/mupdf,knielsen/mupdf,lolo32/mupdf-mirror,wzhsunn/mupdf,muennich/mupdf,FabriceSalvaire/mupdf-v1.3,crow-misia/mupdf,robamler/mupdf-nacl,poor-grad-student/mupdf,sebras/mupdf,benoit-pierre/mupdf,muennich/mupdf,hackqiang/mupdf,hjiayz/forkmupdf,ArtifexSoftware/mupdf,nqv/mupdf,fluks/mupdf-x11-bookmarks,MokiMobility/muPDF,asbloomf/mupdf,ylixir/mupdf,FabriceSalvaire/mupdf-v1.3,sebras/mupdf,hxx0215/MuPDFMirror,flipstudio/MuPDF,crow-misia/mupdf,xiangxw/mupdf,hxx0215/MuPDFMirror,zeniko/mupdf,wild0/opened_mupdf,issuestand/mupdf,lamemate/mupdf,cgogolin/penandpdf,hjiayz/forkmupdf,lustersir/MuPDF,fluks/mupdf-x11-bookmarks,zeniko/mupdf,geetakaur/NewApps,TamirEvan/mupdf,lamemate/mupdf,cgogolin/penandpdf,muennich/mupdf,FabriceSalvaire/mupdf-cmake,benoit-pierre/mupdf,MokiMobility/muPDF
c
## Code Before: void * fz_malloc(int n) { void *p = malloc(n); if (!p) fz_throw("cannot malloc %d bytes", n); return p; } void * fz_realloc(void *p, int n) { void *np = realloc(p, n); if (np == nil) fz_throw("cannot realloc %d bytes", n); return np; } void fz_free(void *p) { free(p); } char * fz_strdup(char *s) { char *ns = strdup(s); if (!ns) fz_throw("cannot strdup %d bytes", strlen(s) + 1); return ns; } ## Instruction: Use the correct format specifier for size_t in fz_strdup. Prior to this patch, if the strdup failed, it would throw an error printing the number of bytes that could not be allocated. However, this was formatted as an int, while the actual argument passed is the return value of strdup itself, which is usually a size_t. This patch formats instead as an unsigned long, and adds a cast to ensure the types match even on platforms where this isn't already the case. ## Code After: void * fz_malloc(int n) { void *p = malloc(n); if (!p) fz_throw("cannot malloc %d bytes", n); return p; } void * fz_realloc(void *p, int n) { void *np = realloc(p, n); if (np == nil) fz_throw("cannot realloc %d bytes", n); return np; } void fz_free(void *p) { free(p); } char * fz_strdup(char *s) { char *ns = strdup(s); if (!ns) fz_throw("cannot strdup %lu bytes", (unsigned long)strlen(s) + 1); return ns; }
... { char *ns = strdup(s); if (!ns) fz_throw("cannot strdup %lu bytes", (unsigned long)strlen(s) + 1); return ns; } ...
693561bbc1e6aabc9a7d0bc2e4688536afcde5a0
src/main/java/org/pacey/dropwizardpebble/PebbleViewRenderer.java
src/main/java/org/pacey/dropwizardpebble/PebbleViewRenderer.java
package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output)) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } }
package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output, Charset.forName("UTF-8"))) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } }
Fix the Charset to UTF-8
Fix the Charset to UTF-8
Java
mit
pacey/dropwizard-pebble
java
## Code Before: package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output)) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } } ## Instruction: Fix the Charset to UTF-8 ## Code After: package org.pacey.dropwizardpebble; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.error.PebbleException; import io.dropwizard.Configuration; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { private final PebbleEngineConfigurable<T> pebbleEngineConfigurable; private final TemplateResolver templateResolver; private PebbleEngine pebbleEngine; public PebbleViewRenderer(PebbleEngineConfigurable<T> pebbleEngineConfigurable, TemplateResolver templateResolver) { this.pebbleEngineConfigurable = pebbleEngineConfigurable; this.templateResolver = templateResolver; } public void configure(LifecycleEnvironment lifecycleEnvironment, T configuration) { final PebbleEngine.Builder builder = new PebbleEngine.Builder(); this.pebbleEngine = pebbleEngineConfigurable.configure(lifecycleEnvironment, configuration, builder); } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output, Charset.forName("UTF-8"))) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } }
// ... existing code ... import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Locale; public class PebbleViewRenderer<T extends Configuration> implements ViewRenderer<T> { // ... modified code ... } public void render(PebbleView pebbleView, Locale locale, OutputStream output) throws IOException, PebbleException { try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output, Charset.forName("UTF-8"))) { pebbleEngine.getTemplate(templateResolver.resolve(pebbleView)).evaluate(outputStreamWriter, pebbleView.getContext(), locale); } } // ... rest of the code ...
7c690e65fd1fe0a139eaca8df7799acf0f696ea5
mqtt/tests/test_client.py
mqtt/tests/test_client.py
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(TestMQTT, MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
Add more time to mqtt.test.client
Add more time to mqtt.test.client
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
python
## Code Before: import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(TestMQTT, MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True) ## Instruction: Add more time to mqtt.test.client ## Code After: import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
# ... existing code ... from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): # ... rest of the code ...
54b1e3d095c54096798aadf20bc006ae4dc258de
app/src/main/java/com/supinfo/jva/geocar/About.java
app/src/main/java/com/supinfo/jva/geocar/About.java
package com.supinfo.jva.geocar; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class About extends ActionBarActivity { private TextView version = null; private Button gitButton = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); version = (TextView) findViewById(R.id.version); gitButton = (Button) findViewById(R.id.button_git); Resources res = getResources(); String actualVersion = res.getString(R.string.version, "1.0.0"); version.setText(actualVersion); gitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String urlProject = "https://github.com/Carmain/Geocar"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlProject)); startActivity(intent); } }); } }
package com.supinfo.jva.geocar; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class About extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView version = (TextView) findViewById(R.id.version); Button gitButton = (Button) findViewById(R.id.button_git); Resources res = getResources(); String actualVersion = res.getString(R.string.version, "1.0.0"); version.setText(actualVersion); gitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String urlProject = "https://github.com/Carmain/Geocar"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlProject)); startActivity(intent); } }); } }
Use local vars instead of global
Use local vars instead of global
Java
apache-2.0
Carmain/Geocar
java
## Code Before: package com.supinfo.jva.geocar; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class About extends ActionBarActivity { private TextView version = null; private Button gitButton = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); version = (TextView) findViewById(R.id.version); gitButton = (Button) findViewById(R.id.button_git); Resources res = getResources(); String actualVersion = res.getString(R.string.version, "1.0.0"); version.setText(actualVersion); gitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String urlProject = "https://github.com/Carmain/Geocar"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlProject)); startActivity(intent); } }); } } ## Instruction: Use local vars instead of global ## Code After: package com.supinfo.jva.geocar; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class About extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView version = (TextView) findViewById(R.id.version); Button gitButton = (Button) findViewById(R.id.button_git); Resources res = getResources(); String actualVersion = res.getString(R.string.version, "1.0.0"); version.setText(actualVersion); gitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String urlProject = "https://github.com/Carmain/Geocar"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlProject)); startActivity(intent); } }); } }
// ... existing code ... public class About extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView version = (TextView) findViewById(R.id.version); Button gitButton = (Button) findViewById(R.id.button_git); Resources res = getResources(); String actualVersion = res.getString(R.string.version, "1.0.0"); // ... rest of the code ...
6caca3259f4ec8f298b1d35f15e4492efbcff6b1
tests/basics/dict1.py
tests/basics/dict1.py
d = {} print(d) d[2] = 123 print(d) d = {1:2} d[3] = 3 print(len(d), d[1], d[3]) d[1] = 0 print(len(d), d[1], d[3]) print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}') x = 1 while x < 100: d[x] = x x += 1 print(d[50]) # equality operator on dicts of different size print({} == {1:1}) # equality operator on dicts of same size but with different keys print({1:1} == {2:1}) # value not found try: {}[0] except KeyError: print('KeyError') # unsupported unary op try: +{} except TypeError: print('TypeError') # unsupported binary op try: {} + {} except TypeError: print('TypeError')
d = {} print(d) d[2] = 123 print(d) d = {1:2} d[3] = 3 print(len(d), d[1], d[3]) d[1] = 0 print(len(d), d[1], d[3]) print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}') x = 1 while x < 100: d[x] = x x += 1 print(d[50]) # equality operator on dicts of different size print({} == {1:1}) # equality operator on dicts of same size but with different keys print({1:1} == {2:1}) # value not found try: {}[0] except KeyError as er: print('KeyError', er, repr(er), er.args) # unsupported unary op try: +{} except TypeError: print('TypeError') # unsupported binary op try: {} + {} except TypeError: print('TypeError')
Add test to print full KeyError exc from failed dict lookup.
tests: Add test to print full KeyError exc from failed dict lookup.
Python
mit
jmarcelino/pycom-micropython,alex-march/micropython,hiway/micropython,AriZuu/micropython,chrisdearman/micropython,kerneltask/micropython,jmarcelino/pycom-micropython,selste/micropython,tuc-osg/micropython,blazewicz/micropython,oopy/micropython,ryannathans/micropython,micropython/micropython-esp32,trezor/micropython,infinnovation/micropython,MrSurly/micropython,puuu/micropython,adafruit/micropython,torwag/micropython,pfalcon/micropython,micropython/micropython-esp32,AriZuu/micropython,ryannathans/micropython,pozetroninc/micropython,tuc-osg/micropython,pozetroninc/micropython,cwyark/micropython,dmazzella/micropython,pramasoul/micropython,tobbad/micropython,lowRISC/micropython,HenrikSolver/micropython,TDAbboud/micropython,pramasoul/micropython,infinnovation/micropython,puuu/micropython,blazewicz/micropython,SHA2017-badge/micropython-esp32,infinnovation/micropython,selste/micropython,AriZuu/micropython,adafruit/micropython,swegener/micropython,mhoffma/micropython,adafruit/circuitpython,mhoffma/micropython,oopy/micropython,deshipu/micropython,trezor/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,tobbad/micropython,ryannathans/micropython,tobbad/micropython,bvernoux/micropython,chrisdearman/micropython,pozetroninc/micropython,blazewicz/micropython,HenrikSolver/micropython,hiway/micropython,torwag/micropython,ryannathans/micropython,AriZuu/micropython,henriknelson/micropython,henriknelson/micropython,mhoffma/micropython,dmazzella/micropython,PappaPeppar/micropython,Timmenem/micropython,mhoffma/micropython,blazewicz/micropython,infinnovation/micropython,oopy/micropython,tralamazza/micropython,dxxb/micropython,TDAbboud/micropython,puuu/micropython,chrisdearman/micropython,PappaPeppar/micropython,Timmenem/micropython,alex-march/micropython,pozetroninc/micropython,TDAbboud/micropython,Peetz0r/micropython-esp32,HenrikSolver/micropython,pramasoul/micropython,TDAbboud/micropython,HenrikSolver/micropython,AriZuu/micropython,oopy/micropython,alex-march/micropython,pramasoul/micropython,tobbad/micropython,alex-robbins/micropython,kerneltask/micropython,pfalcon/micropython,henriknelson/micropython,pfalcon/micropython,adafruit/circuitpython,torwag/micropython,Timmenem/micropython,cwyark/micropython,tuc-osg/micropython,tuc-osg/micropython,MrSurly/micropython,toolmacher/micropython,SHA2017-badge/micropython-esp32,henriknelson/micropython,adafruit/circuitpython,pozetroninc/micropython,micropython/micropython-esp32,alex-robbins/micropython,alex-robbins/micropython,adafruit/micropython,SHA2017-badge/micropython-esp32,dmazzella/micropython,Peetz0r/micropython-esp32,puuu/micropython,swegener/micropython,dxxb/micropython,tuc-osg/micropython,adafruit/micropython,lowRISC/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,MrSurly/micropython-esp32,hosaka/micropython,bvernoux/micropython,selste/micropython,PappaPeppar/micropython,matthewelse/micropython,matthewelse/micropython,trezor/micropython,MrSurly/micropython-esp32,hiway/micropython,SHA2017-badge/micropython-esp32,MrSurly/micropython,adafruit/circuitpython,hiway/micropython,blazewicz/micropython,kerneltask/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,selste/micropython,kerneltask/micropython,MrSurly/micropython,micropython/micropython-esp32,alex-march/micropython,pfalcon/micropython,matthewelse/micropython,alex-robbins/micropython,toolmacher/micropython,puuu/micropython,toolmacher/micropython,tralamazza/micropython,torwag/micropython,hosaka/micropython,hosaka/micropython,alex-march/micropython,trezor/micropython,Timmenem/micropython,hosaka/micropython,ryannathans/micropython,swegener/micropython,jmarcelino/pycom-micropython,mhoffma/micropython,Peetz0r/micropython-esp32,dxxb/micropython,Peetz0r/micropython-esp32,swegener/micropython,toolmacher/micropython,torwag/micropython,deshipu/micropython,deshipu/micropython,adafruit/circuitpython,dxxb/micropython,lowRISC/micropython,cwyark/micropython,Timmenem/micropython,matthewelse/micropython,MrSurly/micropython-esp32,tralamazza/micropython,oopy/micropython,MrSurly/micropython,chrisdearman/micropython,dxxb/micropython,tralamazza/micropython,bvernoux/micropython,hiway/micropython,deshipu/micropython,matthewelse/micropython,toolmacher/micropython,hosaka/micropython,HenrikSolver/micropython,TDAbboud/micropython,tobbad/micropython,swegener/micropython,adafruit/circuitpython,infinnovation/micropython,cwyark/micropython,bvernoux/micropython,adafruit/micropython,trezor/micropython,MrSurly/micropython-esp32,dmazzella/micropython,lowRISC/micropython,kerneltask/micropython,SHA2017-badge/micropython-esp32,lowRISC/micropython,deshipu/micropython,chrisdearman/micropython,matthewelse/micropython,cwyark/micropython,selste/micropython,alex-robbins/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,pramasoul/micropython,bvernoux/micropython
python
## Code Before: d = {} print(d) d[2] = 123 print(d) d = {1:2} d[3] = 3 print(len(d), d[1], d[3]) d[1] = 0 print(len(d), d[1], d[3]) print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}') x = 1 while x < 100: d[x] = x x += 1 print(d[50]) # equality operator on dicts of different size print({} == {1:1}) # equality operator on dicts of same size but with different keys print({1:1} == {2:1}) # value not found try: {}[0] except KeyError: print('KeyError') # unsupported unary op try: +{} except TypeError: print('TypeError') # unsupported binary op try: {} + {} except TypeError: print('TypeError') ## Instruction: tests: Add test to print full KeyError exc from failed dict lookup. ## Code After: d = {} print(d) d[2] = 123 print(d) d = {1:2} d[3] = 3 print(len(d), d[1], d[3]) d[1] = 0 print(len(d), d[1], d[3]) print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}') x = 1 while x < 100: d[x] = x x += 1 print(d[50]) # equality operator on dicts of different size print({} == {1:1}) # equality operator on dicts of same size but with different keys print({1:1} == {2:1}) # value not found try: {}[0] except KeyError as er: print('KeyError', er, repr(er), er.args) # unsupported unary op try: +{} except TypeError: print('TypeError') # unsupported binary op try: {} + {} except TypeError: print('TypeError')
... # value not found try: {}[0] except KeyError as er: print('KeyError', er, repr(er), er.args) # unsupported unary op try: ...
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f
OMDB_api_scrape.py
OMDB_api_scrape.py
import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile)
import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
Convert OMDB scrapper to grab xml
Convert OMDB scrapper to grab xml
Python
mit
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
python
## Code Before: import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile) ## Instruction: Convert OMDB scrapper to grab xml ## Code After: import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
... import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' ... sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: ... print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text) ...
99609e3643c320484c7978440ffedd892f8bb088
Toolkit/PlayPen/xscale_2_hkl.py
Toolkit/PlayPen/xscale_2_hkl.py
from iotbx.xds.read_ascii import reader import sys for n, argv in enumerate(sys.argv[1:]): r = reader(open(argv)) mas = r.as_miller_arrays(merge_equivalents = False) assert(len(mas) == 1) ma = mas[0].apply_scaling(target_max = 9.99e5) i = ma.data() s = ma.sigmas() hkl = ma.indices() for j, h in enumerate(hkl): _i = ('%f' % i[j])[:7] assert('.' in _i) _s = ('%f' % s[j])[:7] assert('.' in _s) print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2], _i, _s, n + 1)
from iotbx.xds.read_ascii import reader import sys for n, argv in enumerate(sys.argv[1:]): r = reader(open(argv)) mas = r.as_miller_arrays(merge_equivalents = False) assert(len(mas) == 1) ma = mas[0].apply_scaling(target_max = 9.99e5) i = ma.data() s = ma.sigmas() hkl = ma.indices() for j, h in enumerate(hkl): _i = ('%f' % i[j])[:7] assert('.' in _i) _s = ('%f' % s[j])[:7] assert('.' in _s) if s[j] >= 0.0: print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2], _i, _s, n + 1)
Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input)
Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input)
Python
bsd-3-clause
xia2/xia2,xia2/xia2
python
## Code Before: from iotbx.xds.read_ascii import reader import sys for n, argv in enumerate(sys.argv[1:]): r = reader(open(argv)) mas = r.as_miller_arrays(merge_equivalents = False) assert(len(mas) == 1) ma = mas[0].apply_scaling(target_max = 9.99e5) i = ma.data() s = ma.sigmas() hkl = ma.indices() for j, h in enumerate(hkl): _i = ('%f' % i[j])[:7] assert('.' in _i) _s = ('%f' % s[j])[:7] assert('.' in _s) print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2], _i, _s, n + 1) ## Instruction: Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) ## Code After: from iotbx.xds.read_ascii import reader import sys for n, argv in enumerate(sys.argv[1:]): r = reader(open(argv)) mas = r.as_miller_arrays(merge_equivalents = False) assert(len(mas) == 1) ma = mas[0].apply_scaling(target_max = 9.99e5) i = ma.data() s = ma.sigmas() hkl = ma.indices() for j, h in enumerate(hkl): _i = ('%f' % i[j])[:7] assert('.' in _i) _s = ('%f' % s[j])[:7] assert('.' in _s) if s[j] >= 0.0: print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2], _i, _s, n + 1)
# ... existing code ... _s = ('%f' % s[j])[:7] assert('.' in _s) if s[j] >= 0.0: print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2], _i, _s, n + 1) # ... rest of the code ...
201ba3681790ed109be1502cfa9ad891de1e2097
copasi/output/output.h
copasi/output/output.h
/* include files for the package output */ #include "CDatum.h" #include "COutput.h" #include "COutputLine.h" #include "COutputList.h" #include "COutputEvent.h"
/* include files for the package output */ #include "CDatum.h" #include "COutput.h" #include "COutputLine.h" #include "COutputList.h" #include "COutputEvent.h" #include "CNodeO.h" #include "CUDFunction.h" #include "CUDFunctionDB.h"
Add 3 new classes about User Defined Functions
Add 3 new classes about User Defined Functions
C
artistic-2.0
copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI
c
## Code Before: /* include files for the package output */ #include "CDatum.h" #include "COutput.h" #include "COutputLine.h" #include "COutputList.h" #include "COutputEvent.h" ## Instruction: Add 3 new classes about User Defined Functions ## Code After: /* include files for the package output */ #include "CDatum.h" #include "COutput.h" #include "COutputLine.h" #include "COutputList.h" #include "COutputEvent.h" #include "CNodeO.h" #include "CUDFunction.h" #include "CUDFunctionDB.h"
... #include "COutputLine.h" #include "COutputList.h" #include "COutputEvent.h" #include "CNodeO.h" #include "CUDFunction.h" #include "CUDFunctionDB.h" ...
3b3a8dc6aa0b38cfbb68105eb5ef31e8e73ff3a4
gcm_flask/application/models.py
gcm_flask/application/models.py
from google.appengine.ext import db class ExampleModel(db.Model): """Example Model""" example_name = db.StringProperty(required=True) example_description = db.TextProperty(required=True) added_by = db.UserProperty() timestamp = db.DateTimeProperty(auto_now_add=True) class RegIDModel(db.Model): """Regl IDs Model""" regID = db.StringProperty(required=True) class MessagesModel(db.Model): """Model for storing messages sent""" message = db.StringProperty(required=True) messagetype = db.StringProperty(required=True) added_by = db.UserProperty() sent_at = db.DateTimeProperty(auto_now_add=True)
from google.appengine.ext import db class ExampleModel(db.Model): """Example Model""" example_name = db.StringProperty(required=True) example_description = db.TextProperty(required=True) added_by = db.UserProperty() timestamp = db.DateTimeProperty(auto_now_add=True) class RegIDModel(db.Model): """Regl IDs Model""" regID = db.StringProperty(required=True) class MessagesModel(db.Model): """Model for storing messages sent""" message = db.StringProperty(required=True) messagetype = db.StringProperty(required=True) added_by = db.UserProperty(auto_current_user=True) sent_at = db.DateTimeProperty(auto_now_add=True)
Update user who sent the message
Update user who sent the message
Python
apache-2.0
BarcampBangalore/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App,BarcampBangalore/Barcamp-Bangalore-Android-App,rajeefmk/Barcamp-Bangalore-Android-App
python
## Code Before: from google.appengine.ext import db class ExampleModel(db.Model): """Example Model""" example_name = db.StringProperty(required=True) example_description = db.TextProperty(required=True) added_by = db.UserProperty() timestamp = db.DateTimeProperty(auto_now_add=True) class RegIDModel(db.Model): """Regl IDs Model""" regID = db.StringProperty(required=True) class MessagesModel(db.Model): """Model for storing messages sent""" message = db.StringProperty(required=True) messagetype = db.StringProperty(required=True) added_by = db.UserProperty() sent_at = db.DateTimeProperty(auto_now_add=True) ## Instruction: Update user who sent the message ## Code After: from google.appengine.ext import db class ExampleModel(db.Model): """Example Model""" example_name = db.StringProperty(required=True) example_description = db.TextProperty(required=True) added_by = db.UserProperty() timestamp = db.DateTimeProperty(auto_now_add=True) class RegIDModel(db.Model): """Regl IDs Model""" regID = db.StringProperty(required=True) class MessagesModel(db.Model): """Model for storing messages sent""" message = db.StringProperty(required=True) messagetype = db.StringProperty(required=True) added_by = db.UserProperty(auto_current_user=True) sent_at = db.DateTimeProperty(auto_now_add=True)
# ... existing code ... """Model for storing messages sent""" message = db.StringProperty(required=True) messagetype = db.StringProperty(required=True) added_by = db.UserProperty(auto_current_user=True) sent_at = db.DateTimeProperty(auto_now_add=True) # ... rest of the code ...
c8fb57c122aadfb83c8e9efa9904cc664aa4b786
Include/structseq.h
Include/structseq.h
/* Tuple object interface */ #ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { char *name; char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { char *name; char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ (((PyStructSequence *)(op))->ob_item[i] = v) #ifdef __cplusplus } #endif #endif /* !Py_STRUCTSEQ_H */
/* Tuple object interface */ #ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { char *name; char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { char *name; char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ (((PyStructSequence *)(op))->ob_item[i] = v) #ifdef __cplusplus } #endif #endif /* !Py_STRUCTSEQ_H */
Clean up some whitespace to be consistent with Python's C style.
Clean up some whitespace to be consistent with Python's C style.
C
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
c
## Code Before: /* Tuple object interface */ #ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { char *name; char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { char *name; char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ (((PyStructSequence *)(op))->ob_item[i] = v) #ifdef __cplusplus } #endif #endif /* !Py_STRUCTSEQ_H */ ## Instruction: Clean up some whitespace to be consistent with Python's C style. ## Code After: /* Tuple object interface */ #ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { char *name; char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { char *name; char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ (((PyStructSequence *)(op))->ob_item[i] = v) #ifdef __cplusplus } #endif #endif /* !Py_STRUCTSEQ_H */
// ... existing code ... #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { char *name; char *doc; // ... modified code ... extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { // ... rest of the code ...
8112c82609b3307c193ffefae01690ecd6e99968
BlocksKit/NSCache+BlocksKit.h
BlocksKit/NSCache+BlocksKit.h
// // NSCache+BlocksKit.h // %PROJECT // #import "BKGlobals.h" /** NSCache with block adding of objects This category allows you to conditionally add objects to an instance of NSCache using blocks. Both the normal delegation pattern and a block callback for NSCache's one delegate method are allowed. These methods emulate Rails caching behavior. Created by Igor Evsukov and contributed to BlocksKit. */ @interface NSCache (BlocksKit) /** Returns the value associated with a given key. If there is no object for that key, it uses the result of the block, saves that to the cache, and returns it. This mimics the cache behavior of Ruby on Rails. The following code: @products = Rails.cache.fetch('products') do Product.all end becomes: NSMutableArray *products = [cache objectForKey:@"products" withGetter:^id{ return [Product all]; }]; @return The value associated with *key*, or the object returned by the block if no value is associated with *key*. @param key An object identifying the value. @param getterBlock A block used to get an object if there is no value in the cache. */ - (id)objectForKey:(id)key withGetter:(BKReturnBlock)getterBlock; /** Called when an object is about to be evicted from the cache. This block callback is an analog for the cache:willEviceObject: method of NSCacheDelegate. */ @property (copy) BKSenderBlock willEvictBlock; @end
// // NSCache+BlocksKit.h // %PROJECT // #import "BKGlobals.h" /** NSCache with block adding of objects This category allows you to conditionally add objects to an instance of NSCache using blocks. Both the normal delegation pattern and a block callback for NSCache's one delegate method are allowed. These methods emulate Rails caching behavior. Created by Igor Evsukov and contributed to BlocksKit. */ @interface NSCache (BlocksKit) /** Returns the value associated with a given key. If there is no object for that key, it uses the result of the block, saves that to the cache, and returns it. This mimics the cache behavior of Ruby on Rails. The following code: @products = Rails.cache.fetch('products') do Product.all end becomes: NSMutableArray *products = [cache objectForKey:@"products" withGetter:^id{ return [Product all]; }]; @return The value associated with *key*, or the object returned by the block if no value is associated with *key*. @param key An object identifying the value. @param getterBlock A block used to get an object if there is no value in the cache. */ - (id)objectForKey:(id)key withGetter:(BKReturnBlock)getterBlock; /** Called when an object is about to be evicted from the cache. This block callback is an analog for the cache:willEviceObject: method of NSCacheDelegate. */ @property (copy) void(^willEvictBlock)(NSCache *, id); @end
Fix block property type in NSCache.
Fix block property type in NSCache.
C
mit
AlexanderMazaletskiy/BlocksKit,zxq3220122/BlocksKit-1,HarrisLee/BlocksKit,zwaldowski/BlocksKit,yimouleng/BlocksKit,z8927623/BlocksKit,Herbert77/BlocksKit,tattocau/BlocksKit,pilot34/BlocksKit,hq804116393/BlocksKit,stevenxiaoyang/BlocksKit,Gitub/BlocksKit,dachaoisme/BlocksKit,demonnico/BlocksKit,pomu0325/BlocksKit,anton-matosov/BlocksKit,ManagerOrganization/BlocksKit,yaoxiaoyong/BlocksKit,shenhzou654321/BlocksKit,owers19856/BlocksKit,hartbit/BlocksKit,Voxer/BlocksKit,xinlehou/BlocksKit,aipeople/BlocksKit,zhaoguohui/BlocksKit,TomBin647/BlocksKit,coneman/BlocksKit
c
## Code Before: // // NSCache+BlocksKit.h // %PROJECT // #import "BKGlobals.h" /** NSCache with block adding of objects This category allows you to conditionally add objects to an instance of NSCache using blocks. Both the normal delegation pattern and a block callback for NSCache's one delegate method are allowed. These methods emulate Rails caching behavior. Created by Igor Evsukov and contributed to BlocksKit. */ @interface NSCache (BlocksKit) /** Returns the value associated with a given key. If there is no object for that key, it uses the result of the block, saves that to the cache, and returns it. This mimics the cache behavior of Ruby on Rails. The following code: @products = Rails.cache.fetch('products') do Product.all end becomes: NSMutableArray *products = [cache objectForKey:@"products" withGetter:^id{ return [Product all]; }]; @return The value associated with *key*, or the object returned by the block if no value is associated with *key*. @param key An object identifying the value. @param getterBlock A block used to get an object if there is no value in the cache. */ - (id)objectForKey:(id)key withGetter:(BKReturnBlock)getterBlock; /** Called when an object is about to be evicted from the cache. This block callback is an analog for the cache:willEviceObject: method of NSCacheDelegate. */ @property (copy) BKSenderBlock willEvictBlock; @end ## Instruction: Fix block property type in NSCache. ## Code After: // // NSCache+BlocksKit.h // %PROJECT // #import "BKGlobals.h" /** NSCache with block adding of objects This category allows you to conditionally add objects to an instance of NSCache using blocks. Both the normal delegation pattern and a block callback for NSCache's one delegate method are allowed. These methods emulate Rails caching behavior. Created by Igor Evsukov and contributed to BlocksKit. */ @interface NSCache (BlocksKit) /** Returns the value associated with a given key. If there is no object for that key, it uses the result of the block, saves that to the cache, and returns it. This mimics the cache behavior of Ruby on Rails. The following code: @products = Rails.cache.fetch('products') do Product.all end becomes: NSMutableArray *products = [cache objectForKey:@"products" withGetter:^id{ return [Product all]; }]; @return The value associated with *key*, or the object returned by the block if no value is associated with *key*. @param key An object identifying the value. @param getterBlock A block used to get an object if there is no value in the cache. */ - (id)objectForKey:(id)key withGetter:(BKReturnBlock)getterBlock; /** Called when an object is about to be evicted from the cache. This block callback is an analog for the cache:willEviceObject: method of NSCacheDelegate. */ @property (copy) void(^willEvictBlock)(NSCache *, id); @end
... This block callback is an analog for the cache:willEviceObject: method of NSCacheDelegate. */ @property (copy) void(^willEvictBlock)(NSCache *, id); @end ...