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
ae78e44461ec710c65479b094dcff257944e1f83
pyof/v0x01/controller2switch/stats_request.py
pyof/v0x01/controller2switch/stats_request.py
"""Query the datapath about its current state.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ConstantTypeList, UBInt16 # Local imports from pyof.v0x01.common.header import Header, Type from pyof.v0x01.controller2switch.common import StatsTypes __all__ = ('StatsRequest',) class StatsRequest(GenericMessage): """Response to the config request.""" #: OpenFlow :class:`.Header` header = Header(message_type=Type.OFPT_STATS_REQUEST) body_type = UBInt16(enum_ref=StatsTypes) flags = UBInt16() body = ConstantTypeList() def __init__(self, xid=None, body_type=None, flags=None, body=None): """The constructor just assings parameters to object attributes. Args: body_type (StatsTypes): One of the OFPST_* constants. flags (int): OFPSF_REQ_* flags (none yet defined). body (ConstantTypeList): Body of the request. """ super().__init__(xid) self.body_type = body_type self.flags = flags self.body = [] if body is None else body
"""Query the datapath about its current state.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData, UBInt16 # Local imports from pyof.v0x01.common.header import Header, Type from pyof.v0x01.controller2switch.common import StatsTypes __all__ = ('StatsRequest',) class StatsRequest(GenericMessage): """Response to the config request.""" #: OpenFlow :class:`.Header` header = Header(message_type=Type.OFPT_STATS_REQUEST) body_type = UBInt16(enum_ref=StatsTypes) flags = UBInt16() body = BinaryData() def __init__(self, xid=None, body_type=None, flags=0, body=b''): """The constructor just assings parameters to object attributes. Args: body_type (StatsTypes): One of the OFPST_* constants. flags (int): OFPSF_REQ_* flags (none yet defined). body (ConstantTypeList): Body of the request. """ super().__init__(xid) self.body_type = body_type self.flags = flags self.body = body
Fix StatsRequest body type; add default values
Fix StatsRequest body type; add default values
Python
mit
cemsbr/python-openflow,kytos/python-openflow
python
## Code Before: """Query the datapath about its current state.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ConstantTypeList, UBInt16 # Local imports from pyof.v0x01.common.header import Header, Type from pyof.v0x01.controller2switch.common import StatsTypes __all__ = ('StatsRequest',) class StatsRequest(GenericMessage): """Response to the config request.""" #: OpenFlow :class:`.Header` header = Header(message_type=Type.OFPT_STATS_REQUEST) body_type = UBInt16(enum_ref=StatsTypes) flags = UBInt16() body = ConstantTypeList() def __init__(self, xid=None, body_type=None, flags=None, body=None): """The constructor just assings parameters to object attributes. Args: body_type (StatsTypes): One of the OFPST_* constants. flags (int): OFPSF_REQ_* flags (none yet defined). body (ConstantTypeList): Body of the request. """ super().__init__(xid) self.body_type = body_type self.flags = flags self.body = [] if body is None else body ## Instruction: Fix StatsRequest body type; add default values ## Code After: """Query the datapath about its current state.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData, UBInt16 # Local imports from pyof.v0x01.common.header import Header, Type from pyof.v0x01.controller2switch.common import StatsTypes __all__ = ('StatsRequest',) class StatsRequest(GenericMessage): """Response to the config request.""" #: OpenFlow :class:`.Header` header = Header(message_type=Type.OFPT_STATS_REQUEST) body_type = UBInt16(enum_ref=StatsTypes) flags = UBInt16() body = BinaryData() def __init__(self, xid=None, body_type=None, flags=0, body=b''): """The constructor just assings parameters to object attributes. Args: body_type (StatsTypes): One of the OFPST_* constants. flags (int): OFPSF_REQ_* flags (none yet defined). body (ConstantTypeList): Body of the request. """ super().__init__(xid) self.body_type = body_type self.flags = flags self.body = body
# ... existing code ... # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData, UBInt16 # Local imports from pyof.v0x01.common.header import Header, Type from pyof.v0x01.controller2switch.common import StatsTypes # ... modified code ... header = Header(message_type=Type.OFPT_STATS_REQUEST) body_type = UBInt16(enum_ref=StatsTypes) flags = UBInt16() body = BinaryData() def __init__(self, xid=None, body_type=None, flags=0, body=b''): """The constructor just assings parameters to object attributes. Args: ... super().__init__(xid) self.body_type = body_type self.flags = flags self.body = body # ... rest of the code ...
40edb65ee751dfe4cf6e04ee59891266d8b14f30
spacy/tests/regression/test_issue1380.py
spacy/tests/regression/test_issue1380.py
import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
Make test work for Python 2.7
Make test work for Python 2.7
Python
mit
recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy
python
## Code Before: import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0 ## Instruction: Make test work for Python 2.7 ## Code After: from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
// ... existing code ... from __future__ import unicode_literals import pytest from ...language import Language // ... rest of the code ...
2917e089734ace4fd212ef9a16e8adf71d671312
test/partial_double_test.py
test/partial_double_test.py
from doubles import allow, teardown class User(object): def __init__(self, name): self.name = name def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice'
from doubles import allow, teardown class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25
Test that only stubbed methods are altered on partial doubles.
Test that only stubbed methods are altered on partial doubles.
Python
mit
uber/doubles
python
## Code Before: from doubles import allow, teardown class User(object): def __init__(self, name): self.name = name def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice') allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' ## Instruction: Test that only stubbed methods are altered on partial doubles. ## Code After: from doubles import allow, teardown class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def get_name(self): return self.name class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25
# ... existing code ... class User(object): def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def get_name(self): return self.name # ... modified code ... class TestPartialDouble(object): def test_stubs_real_object(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') ... assert user.get_name() == 'Bob' def test_restores_original(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') teardown() assert user.get_name() == 'Alice' def test_only_affects_stubbed_method(self): user = User('Alice', 25) allow(user).to_receive('get_name').and_return('Bob') assert user.age == 25 # ... rest of the code ...
bb59028a3dab81139a83f9a0eb8a4c58b9c25829
sample_application/app.py
sample_application/app.py
import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTime, '/time') api.add_resource(PrintArg,'/print/<string:arg>') api.add_resource(ExampleApiUsage,'/search') app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False app.config.from_object('sample_application.config') try: app.config.from_object('sample_application.local_config') except ImportError: pass app.register_blueprint(blueprint) app.client = Client(app.config['CLIENT']) return app
import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTime, '/time') api.add_resource(PrintArg,'/print/<string:arg>') api.add_resource(ExampleApiUsage,'/search') app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False app.config.from_pyfile('config.py') try: app.config.from_pyfile('local_config.py') except IOError: pass app.register_blueprint(blueprint) app.client = Client(app.config['CLIENT']) return app
Change config import strategy to config.from_pyfile()
Change config import strategy to config.from_pyfile()
Python
mit
adsabs/adsabs-webservices-blueprint,jonnybazookatone/adsabs-webservices-blueprint
python
## Code Before: import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTime, '/time') api.add_resource(PrintArg,'/print/<string:arg>') api.add_resource(ExampleApiUsage,'/search') app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False app.config.from_object('sample_application.config') try: app.config.from_object('sample_application.local_config') except ImportError: pass app.register_blueprint(blueprint) app.client = Client(app.config['CLIENT']) return app ## Instruction: Change config import strategy to config.from_pyfile() ## Code After: import os from flask import Blueprint, Flask from flask import Flask, g from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage from flask.ext.restful import Api from client import Client def create_app(): api = Api(blueprint) api.add_resource(Resources, '/resources') api.add_resource(UnixTime, '/time') api.add_resource(PrintArg,'/print/<string:arg>') api.add_resource(ExampleApiUsage,'/search') app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False app.config.from_pyfile('config.py') try: app.config.from_pyfile('local_config.py') except IOError: pass app.register_blueprint(blueprint) app.client = Client(app.config['CLIENT']) return app
# ... existing code ... app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False app.config.from_pyfile('config.py') try: app.config.from_pyfile('local_config.py') except IOError: pass app.register_blueprint(blueprint) app.client = Client(app.config['CLIENT']) # ... rest of the code ...
7bdd06f568856c010a4eacb1e70c262fa4c3388c
bin/trigger_upload.py
bin/trigger_upload.py
import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.services.ec2 import EC2Service, EC2ServiceException import fedimg.uploader from fedimg.util import virt_types_from_url if len(sys.argv) != 2: print 'Usage: trigger_upload.py <rawxz_image_url>' sys.exit(1) logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') upload_pool = multiprocessing.pool.ThreadPool(processes=4) url = sys.argv[1] fedimg.uploader.upload(upload_pool, [url])
""" Triggers an upload process with the specified raw.xz URL. """ import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.services.ec2 import EC2Service, EC2ServiceException import fedimg.uploader from fedimg.util import virt_types_from_url if len(sys.argv) != 3: print 'Usage: trigger_upload.py <rawxz_image_url> <compose_id>' sys.exit(1) logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') upload_pool = multiprocessing.pool.ThreadPool(processes=4) url = sys.argv[1] compose_id = sys.argv[2] compose_meta = { 'compose_id': compose_id } fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta)
Fix the manual upload trigger script
scripts: Fix the manual upload trigger script Signed-off-by: Sayan Chowdhury <[email protected]>
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
python
## Code Before: import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.services.ec2 import EC2Service, EC2ServiceException import fedimg.uploader from fedimg.util import virt_types_from_url if len(sys.argv) != 2: print 'Usage: trigger_upload.py <rawxz_image_url>' sys.exit(1) logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') upload_pool = multiprocessing.pool.ThreadPool(processes=4) url = sys.argv[1] fedimg.uploader.upload(upload_pool, [url]) ## Instruction: scripts: Fix the manual upload trigger script Signed-off-by: Sayan Chowdhury <[email protected]> ## Code After: """ Triggers an upload process with the specified raw.xz URL. """ import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.services.ec2 import EC2Service, EC2ServiceException import fedimg.uploader from fedimg.util import virt_types_from_url if len(sys.argv) != 3: print 'Usage: trigger_upload.py <rawxz_image_url> <compose_id>' sys.exit(1) logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') upload_pool = multiprocessing.pool.ThreadPool(processes=4) url = sys.argv[1] compose_id = sys.argv[2] compose_meta = { 'compose_id': compose_id } fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta)
# ... existing code ... """ Triggers an upload process with the specified raw.xz URL. """ import logging import logging.config # ... modified code ... import fedimg.uploader from fedimg.util import virt_types_from_url if len(sys.argv) != 3: print 'Usage: trigger_upload.py <rawxz_image_url> <compose_id>' sys.exit(1) logging.config.dictConfig(fedmsg.config.load_config()['logging']) ... upload_pool = multiprocessing.pool.ThreadPool(processes=4) url = sys.argv[1] compose_id = sys.argv[2] compose_meta = { 'compose_id': compose_id } fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta) # ... rest of the code ...
a85c21dc324750c3fa7e96d2d0baf3c45657201e
sconsole/static.py
sconsole/static.py
''' Holds static data components, like the palette ''' def msg(msg, logfile='console_log.txt'): ''' Send a message to a logfile, defaults to console_log.txt. This is useful to replace a print statement since curses does put a bit of a damper on this ''' with open(logfile, 'a+') as fp_: fp_.write(str(msg)) def get_palette(theme='std'): ''' Return the preferred palette theme Themes: std The standard theme used by the console ''' if theme == 'bright': return [ ('banner', 'white', 'dark blue') ] else: return [ ('banner', 'white', 'dark blue') ]
''' Holds static data components, like the palette ''' import pprint def tree_seed(): return {'jids': [ {'_|-76789876543456787654': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, {'_|-76789876543456787655': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, ], } def msg(msg, logfile='console_log.txt'): ''' Send a message to a logfile, defaults to console_log.txt. This is useful to replace a print statement since curses does put a bit of a damper on this ''' with open(logfile, 'a+') as fp_: fp_.write('{0}\n'.format(pprint.pformat(msg))) def get_palette(theme='std'): ''' Return the preferred palette theme Themes: std The standard theme used by the console ''' if theme == 'bright': return [ ('banner', 'white', 'dark blue') ] else: return [ ('banner', 'white', 'dark blue') ]
Add convenience function to load in some test data
Add convenience function to load in some test data
Python
apache-2.0
saltstack/salt-console
python
## Code Before: ''' Holds static data components, like the palette ''' def msg(msg, logfile='console_log.txt'): ''' Send a message to a logfile, defaults to console_log.txt. This is useful to replace a print statement since curses does put a bit of a damper on this ''' with open(logfile, 'a+') as fp_: fp_.write(str(msg)) def get_palette(theme='std'): ''' Return the preferred palette theme Themes: std The standard theme used by the console ''' if theme == 'bright': return [ ('banner', 'white', 'dark blue') ] else: return [ ('banner', 'white', 'dark blue') ] ## Instruction: Add convenience function to load in some test data ## Code After: ''' Holds static data components, like the palette ''' import pprint def tree_seed(): return {'jids': [ {'_|-76789876543456787654': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, {'_|-76789876543456787655': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, ], } def msg(msg, logfile='console_log.txt'): ''' Send a message to a logfile, defaults to console_log.txt. This is useful to replace a print statement since curses does put a bit of a damper on this ''' with open(logfile, 'a+') as fp_: fp_.write('{0}\n'.format(pprint.pformat(msg))) def get_palette(theme='std'): ''' Return the preferred palette theme Themes: std The standard theme used by the console ''' if theme == 'bright': return [ ('banner', 'white', 'dark blue') ] else: return [ ('banner', 'white', 'dark blue') ]
// ... existing code ... ''' Holds static data components, like the palette ''' import pprint def tree_seed(): return {'jids': [ {'_|-76789876543456787654': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, {'_|-76789876543456787655': [{'localhost': {'return': True}}, {'otherhost': {'return': True}}],}, ], } def msg(msg, logfile='console_log.txt'): ''' // ... modified code ... a bit of a damper on this ''' with open(logfile, 'a+') as fp_: fp_.write('{0}\n'.format(pprint.pformat(msg))) def get_palette(theme='std'): // ... rest of the code ...
d86144aa09ea0d6a679a661b0b2f887d6a2a725d
examples/python/values.py
examples/python/values.py
from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) print('get value from atom: {}'.format(boundingBox.get_value(featureKey)))
from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) value = boundingBox.get_value(featureKey) print('get value from atom: {}'.format(value)) list = value.to_list() print('get python list from value: {}'.format(list))
Add example of Value to Python list conversion
Add example of Value to Python list conversion
Python
agpl-3.0
rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace,AmeBel/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace
python
## Code Before: from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) print('get value from atom: {}'.format(boundingBox.get_value(featureKey))) ## Instruction: Add example of Value to Python list conversion ## Code After: from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) value = boundingBox.get_value(featureKey) print('get value from atom: {}'.format(value)) list = value.to_list() print('get python list from value: {}'.format(list))
# ... existing code ... boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) value = boundingBox.get_value(featureKey) print('get value from atom: {}'.format(value)) list = value.to_list() print('get python list from value: {}'.format(list)) # ... rest of the code ...
db987f6f54dd04dd292237ff534e035605427239
extract/extract-meeting-log/src/eml.py
extract/extract-meeting-log/src/eml.py
import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. If omitted then is today's date.", default = datetime.date.today().strftime("%Y-%m-%d"), metavar = "<date>") parser.add_argument( 'outputPath', help = "Output path for the generated chat log.", metavar = "<output-path>") parser.add_argument( 'logPath', help = "Path to the chat log file.", metavar = "<chat-log-path>", nargs = '+') opt = parser.parse_args() #print "Date: %s" % opt.date #print "LogPath: %s" % opt.logPath date = opt.date.translate(string.maketrans("-", "/")) with open(opt.outputPath, 'w') as o: for path in opt.logPath: with open(path) as f: for line in f: if line.startswith("[%s" % date): o.write(line)
import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. If omitted then is today's date.", default = datetime.date.today().strftime("%Y-%m-%d"), metavar = "<date>") parser.add_argument( 'outputPath', help = "Output path for the generated chat log.", metavar = "<output-path>") parser.add_argument( 'logPath', help = "Path to the chat log file.", metavar = "<chat-log-path>", nargs = '+') opt = parser.parse_args() #print "Date: %s" % opt.date #print "LogPath: %s" % opt.logPath date = opt.date.translate(string.maketrans("-", "/")) linesFound = 0 with open(opt.outputPath, 'w') as o: for path in opt.logPath: with open(path) as f: for line in f: if line.startswith("[%s" % date): o.write(line) linesFound += 1 print "Found %s lines for %s" % (linesFound, date)
Print out number of lines found for chatlog
Print out number of lines found for chatlog
Python
apache-2.0
justincc/viewer-tools
python
## Code Before: import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. If omitted then is today's date.", default = datetime.date.today().strftime("%Y-%m-%d"), metavar = "<date>") parser.add_argument( 'outputPath', help = "Output path for the generated chat log.", metavar = "<output-path>") parser.add_argument( 'logPath', help = "Path to the chat log file.", metavar = "<chat-log-path>", nargs = '+') opt = parser.parse_args() #print "Date: %s" % opt.date #print "LogPath: %s" % opt.logPath date = opt.date.translate(string.maketrans("-", "/")) with open(opt.outputPath, 'w') as o: for path in opt.logPath: with open(path) as f: for line in f: if line.startswith("[%s" % date): o.write(line) ## Instruction: Print out number of lines found for chatlog ## Code After: import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. If omitted then is today's date.", default = datetime.date.today().strftime("%Y-%m-%d"), metavar = "<date>") parser.add_argument( 'outputPath', help = "Output path for the generated chat log.", metavar = "<output-path>") parser.add_argument( 'logPath', help = "Path to the chat log file.", metavar = "<chat-log-path>", nargs = '+') opt = parser.parse_args() #print "Date: %s" % opt.date #print "LogPath: %s" % opt.logPath date = opt.date.translate(string.maketrans("-", "/")) linesFound = 0 with open(opt.outputPath, 'w') as o: for path in opt.logPath: with open(path) as f: for line in f: if line.startswith("[%s" % date): o.write(line) linesFound += 1 print "Found %s lines for %s" % (linesFound, date)
... #print "LogPath: %s" % opt.logPath date = opt.date.translate(string.maketrans("-", "/")) linesFound = 0 with open(opt.outputPath, 'w') as o: for path in opt.logPath: ... for line in f: if line.startswith("[%s" % date): o.write(line) linesFound += 1 print "Found %s lines for %s" % (linesFound, date) ...
035fa5877a05bb70b8207693c547c97cfd104db3
libqtile/widget/textbox.py
libqtile/widget/textbox.py
from .. import bar, manager import base class TextBox(base._TextBox): """ A flexible textbox that can be updated from bound keys, scripts and qsh. """ defaults = manager.Defaults( ("font", "Arial", "Text font"), ("fontsize", None, "Font pixel size. Calculated if None."), ("fontshadow", None, "font shadow color, default is None(no shadow)"), ("padding", None, "Padding left and right. Calculated if None."), ("background", None, "Background colour."), ("foreground", "#ffffff", "Foreground colour.") ) def __init__(self, name, text=" ", width=bar.CALCULATED, **config): """ - name: Name for this widget. Used to address the widget from scripts, commands and qsh. - text: Initial widget text. - width: An integer width, bar.STRETCH, or bar.CALCULATED . """ self.name = name base._TextBox.__init__(self, text, width, **config) def update(self, text): self.text = text self.bar.draw() def cmd_update(self, text): """ Update the text in a TextBox widget. """ self.update(text) def cmd_get(self): """ Retrieve the text in a TextBox widget. """ return self.text
from .. import bar, manager import base class TextBox(base._TextBox): """ A flexible textbox that can be updated from bound keys, scripts and qsh. """ defaults = manager.Defaults( ("font", "Arial", "Text font"), ("fontsize", None, "Font pixel size. Calculated if None."), ("fontshadow", None, "font shadow color, default is None(no shadow)"), ("padding", None, "Padding left and right. Calculated if None."), ("background", None, "Background colour."), ("foreground", "#ffffff", "Foreground colour.") ) def __init__(self, text=" ", width=bar.CALCULATED, **config): """ - text: Initial widget text. - width: An integer width, bar.STRETCH, or bar.CALCULATED . """ base._TextBox.__init__(self, text, width, **config) def update(self, text): self.text = text self.bar.draw() def cmd_update(self, text): """ Update the text in a TextBox widget. """ self.update(text) def cmd_get(self): """ Retrieve the text in a TextBox widget. """ return self.text
Remove positional argument "name" from Textbox
Remove positional argument "name" from Textbox Users should just use the kwarg name; no sense in having both. Closes #239
Python
mit
andrewyoung1991/qtile,StephenBarnes/qtile,de-vri-es/qtile,tych0/qtile,apinsard/qtile,nxnfufunezn/qtile,soulchainer/qtile,encukou/qtile,ramnes/qtile,jdowner/qtile,jdowner/qtile,soulchainer/qtile,de-vri-es/qtile,kopchik/qtile,tych0/qtile,qtile/qtile,kiniou/qtile,kynikos/qtile,kiniou/qtile,EndPointCorp/qtile,himaaaatti/qtile,zordsdavini/qtile,StephenBarnes/qtile,frostidaho/qtile,aniruddhkanojia/qtile,kseistrup/qtile,cortesi/qtile,xplv/qtile,qtile/qtile,nxnfufunezn/qtile,flacjacket/qtile,flacjacket/qtile,andrewyoung1991/qtile,ramnes/qtile,aniruddhkanojia/qtile,dequis/qtile,rxcomm/qtile,zordsdavini/qtile,farebord/qtile,EndPointCorp/qtile,kynikos/qtile,dequis/qtile,w1ndy/qtile,encukou/qtile,kopchik/qtile,rxcomm/qtile,xplv/qtile,farebord/qtile,frostidaho/qtile,w1ndy/qtile,cortesi/qtile,kseistrup/qtile,apinsard/qtile,himaaaatti/qtile
python
## Code Before: from .. import bar, manager import base class TextBox(base._TextBox): """ A flexible textbox that can be updated from bound keys, scripts and qsh. """ defaults = manager.Defaults( ("font", "Arial", "Text font"), ("fontsize", None, "Font pixel size. Calculated if None."), ("fontshadow", None, "font shadow color, default is None(no shadow)"), ("padding", None, "Padding left and right. Calculated if None."), ("background", None, "Background colour."), ("foreground", "#ffffff", "Foreground colour.") ) def __init__(self, name, text=" ", width=bar.CALCULATED, **config): """ - name: Name for this widget. Used to address the widget from scripts, commands and qsh. - text: Initial widget text. - width: An integer width, bar.STRETCH, or bar.CALCULATED . """ self.name = name base._TextBox.__init__(self, text, width, **config) def update(self, text): self.text = text self.bar.draw() def cmd_update(self, text): """ Update the text in a TextBox widget. """ self.update(text) def cmd_get(self): """ Retrieve the text in a TextBox widget. """ return self.text ## Instruction: Remove positional argument "name" from Textbox Users should just use the kwarg name; no sense in having both. Closes #239 ## Code After: from .. import bar, manager import base class TextBox(base._TextBox): """ A flexible textbox that can be updated from bound keys, scripts and qsh. """ defaults = manager.Defaults( ("font", "Arial", "Text font"), ("fontsize", None, "Font pixel size. Calculated if None."), ("fontshadow", None, "font shadow color, default is None(no shadow)"), ("padding", None, "Padding left and right. Calculated if None."), ("background", None, "Background colour."), ("foreground", "#ffffff", "Foreground colour.") ) def __init__(self, text=" ", width=bar.CALCULATED, **config): """ - text: Initial widget text. - width: An integer width, bar.STRETCH, or bar.CALCULATED . """ base._TextBox.__init__(self, text, width, **config) def update(self, text): self.text = text self.bar.draw() def cmd_update(self, text): """ Update the text in a TextBox widget. """ self.update(text) def cmd_get(self): """ Retrieve the text in a TextBox widget. """ return self.text
# ... existing code ... ("foreground", "#ffffff", "Foreground colour.") ) def __init__(self, text=" ", width=bar.CALCULATED, **config): """ - text: Initial widget text. - width: An integer width, bar.STRETCH, or bar.CALCULATED . """ base._TextBox.__init__(self, text, width, **config) def update(self, text): # ... rest of the code ...
3170407aaaeffbc76e31e5fc78d4dacd008e27d2
backbone_calendar/ajax/mixins.py
backbone_calendar/ajax/mixins.py
from django import http from django.utils import simplejson as json class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context)
import json from django import http class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context)
Use json and not simplejson
Use json and not simplejson
Python
agpl-3.0
rezometz/django-backbone-calendar,rezometz/django-backbone-calendar,rezometz/django-backbone-calendar
python
## Code Before: from django import http from django.utils import simplejson as json class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context) ## Instruction: Use json and not simplejson ## Code After: import json from django import http class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context)
// ... existing code ... import json from django import http class JSONResponseMixin(object): // ... rest of the code ...
695304372ebe4ad76c5d6ce7dea7f39c28ffba07
libexec/wlint/punctuation-style.py
libexec/wlint/punctuation-style.py
import re import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: print( "{}-{}:{} {}".format(fileHandle.name, lineNumber, pos, message))): self.result = 1 punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result)
import operator import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 hits = [] for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: hits.append(lineNumber, pos, message)): self.result = 1 hits.sort() for (line, col, message) in hits: print("{}-{}:{} {}".format(fileHandle.name, line, pos, message)) punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result)
Sort punctuation hits so output is based on line and column, not the order rules are checked
Sort punctuation hits so output is based on line and column, not the order rules are checked
Python
bsd-2-clause
snewell/wlint,snewell/wlint,snewell/writing-tools,snewell/writing-tools
python
## Code Before: import re import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: print( "{}-{}:{} {}".format(fileHandle.name, lineNumber, pos, message))): self.result = 1 punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result) ## Instruction: Sort punctuation hits so output is based on line and column, not the order rules are checked ## Code After: import operator import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 hits = [] for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: hits.append(lineNumber, pos, message)): self.result = 1 hits.sort() for (line, col, message) in hits: print("{}-{}:{} {}".format(fileHandle.name, line, pos, message)) punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result)
// ... existing code ... import operator import wlint.common import wlint.punctuation // ... modified code ... def process(self, fileHandle): lineNumber = 0 hits = [] for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: hits.append(lineNumber, pos, message)): self.result = 1 hits.sort() for (line, col, message) in hits: print("{}-{}:{} {}".format(fileHandle.name, line, pos, message)) punctuationStyle = PunctuationStyle("Check for common punctuation issues") // ... rest of the code ...
bfd71a98a31af02ca43cd10345301c340986fbd7
core/src/main/java/com/github/sergejsamsonow/codegenerator/pojo/renderer/Setter.java
core/src/main/java/com/github/sergejsamsonow/codegenerator/pojo/renderer/Setter.java
package com.github.sergejsamsonow.codegenerator.pojo.renderer; import com.github.sergejsamsonow.codegenerator.api.CodeFormat; import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty; public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> { public Setter(CodeFormat format) { super(format); } @Override protected void writePropertyCode(PojoProperty property) { String type = property.getDeclarationType(); String field = property.getFieldName(); String setter = property.getSetterName(); MethodCodeWriter writer = getMethodCodeWriter(); writer.start("public void %s(%s %s) {", setter, type, field); writer.code("this.%s = %s;", field, field); writer.end(); } }
package com.github.sergejsamsonow.codegenerator.pojo.renderer; import com.github.sergejsamsonow.codegenerator.api.CodeFormat; import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty; public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> { public Setter(CodeFormat format) { super(format); } @Override protected void writePropertyCode(PojoProperty property) { String type = property.getDeclarationType(); String field = property.getFieldName(); String name = property.getSetterName(); MethodCodeWriter method = getMethodCodeWriter(); method.start("public void %s(%s %s) {", name, type, field); method.code("this.%s = %s;", field, field); method.end(); } }
Implement example producer Small refactoring
3: Implement example producer Small refactoring Task-Url: http://github.com/sergej-samsonow/code-generator/issues/issue/3
Java
apache-2.0
sergej-samsonow/code-generator
java
## Code Before: package com.github.sergejsamsonow.codegenerator.pojo.renderer; import com.github.sergejsamsonow.codegenerator.api.CodeFormat; import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty; public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> { public Setter(CodeFormat format) { super(format); } @Override protected void writePropertyCode(PojoProperty property) { String type = property.getDeclarationType(); String field = property.getFieldName(); String setter = property.getSetterName(); MethodCodeWriter writer = getMethodCodeWriter(); writer.start("public void %s(%s %s) {", setter, type, field); writer.code("this.%s = %s;", field, field); writer.end(); } } ## Instruction: 3: Implement example producer Small refactoring Task-Url: http://github.com/sergej-samsonow/code-generator/issues/issue/3 ## Code After: package com.github.sergejsamsonow.codegenerator.pojo.renderer; import com.github.sergejsamsonow.codegenerator.api.CodeFormat; import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean; import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty; public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> { public Setter(CodeFormat format) { super(format); } @Override protected void writePropertyCode(PojoProperty property) { String type = property.getDeclarationType(); String field = property.getFieldName(); String name = property.getSetterName(); MethodCodeWriter method = getMethodCodeWriter(); method.start("public void %s(%s %s) {", name, type, field); method.code("this.%s = %s;", field, field); method.end(); } }
// ... existing code ... protected void writePropertyCode(PojoProperty property) { String type = property.getDeclarationType(); String field = property.getFieldName(); String name = property.getSetterName(); MethodCodeWriter method = getMethodCodeWriter(); method.start("public void %s(%s %s) {", name, type, field); method.code("this.%s = %s;", field, field); method.end(); } } // ... rest of the code ...
a3df62c7da4aa29ab9977a0307e0634fd43e37e8
pywebfaction/exceptions.py
pywebfaction/exceptions.py
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying_fault): self.underlying_fault = underlying_fault exc_type, exc_message = underlying_fault.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message)
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying): self.underlying_fault = underlying try: exc_type, exc_message = underlying.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) except ValueError: self.exception_type = None self.exception_message = None
Make code immune to bad fault messages
Make code immune to bad fault messages
Python
bsd-3-clause
dominicrodger/pywebfaction,dominicrodger/pywebfaction
python
## Code Before: import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying_fault): self.underlying_fault = underlying_fault exc_type, exc_message = underlying_fault.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) ## Instruction: Make code immune to bad fault messages ## Code After: import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswith(EXCEPTION_TYPE_PREFIX): return None if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX): return None return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1] def _parse_exc_message(exc_message): if not exc_message: return None message = ast.literal_eval(exc_message) if isinstance(message, list): if not message: return None return message[0] return message class WebFactionFault(Exception): def __init__(self, underlying): self.underlying_fault = underlying try: exc_type, exc_message = underlying.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) except ValueError: self.exception_type = None self.exception_message = None
// ... existing code ... class WebFactionFault(Exception): def __init__(self, underlying): self.underlying_fault = underlying try: exc_type, exc_message = underlying.faultString.split(':', 1) self.exception_type = _parse_exc_type(exc_type) self.exception_message = _parse_exc_message(exc_message) except ValueError: self.exception_type = None self.exception_message = None // ... rest of the code ...
0249741443cad6e6de2f1c63765d9508733ec711
Hauth/Hauth.h
Hauth/Hauth.h
// // Hauth.h // Hauth // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Hauth. FOUNDATION_EXPORT double HauthVersionNumber; //! Project version string for Hauth. FOUNDATION_EXPORT const unsigned char HauthVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Hauth/PublicHeader.h> #import <Hauth/HauthStreamsController.h> #import <Hauth/HauthClient.h> #import <Hauth/HauthServer.h>
// // Hauth.h // Hauth // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Hauth. FOUNDATION_EXPORT double HauthVersionNumber; //! Project version string for Hauth. FOUNDATION_EXPORT const unsigned char HauthVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Hauth/PublicHeader.h> // NOTE: In Xcode 7.1, if two frameworks have the same module name ("Hauth"), // then sometimes one of the frameworks (in my case, tvOS) doesn't compile correctly, // complaining of the inclusion of "non-modular headers". So make these // non modular import calls here. #import "HauthStreamsController.h" #import "HauthClient.h" #import "HauthServer.h" //#import <Hauth/HauthStreamsController.h> //#import <Hauth/HauthClient.h> //#import <Hauth/HauthServer.h>
Use "" imports instead of <> in main fmwk header
Use "" imports instead of <> in main fmwk header Xcode 7.1 seems to be having issues with the framework being the same module name and existing as 2 different targets (one tvOS, and one iOS). It complains in the tvOS app that the framework includes 'non-modular' headers in the framework. Changing it to quotes for now seems to fix this. Let's revisit with Xcode 7.2
C
mit
almas73/Voucher,rsattar/Voucher,almas73/Voucher,rsattar/Voucher
c
## Code Before: // // Hauth.h // Hauth // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Hauth. FOUNDATION_EXPORT double HauthVersionNumber; //! Project version string for Hauth. FOUNDATION_EXPORT const unsigned char HauthVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Hauth/PublicHeader.h> #import <Hauth/HauthStreamsController.h> #import <Hauth/HauthClient.h> #import <Hauth/HauthServer.h> ## Instruction: Use "" imports instead of <> in main fmwk header Xcode 7.1 seems to be having issues with the framework being the same module name and existing as 2 different targets (one tvOS, and one iOS). It complains in the tvOS app that the framework includes 'non-modular' headers in the framework. Changing it to quotes for now seems to fix this. Let's revisit with Xcode 7.2 ## Code After: // // Hauth.h // Hauth // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Hauth. FOUNDATION_EXPORT double HauthVersionNumber; //! Project version string for Hauth. FOUNDATION_EXPORT const unsigned char HauthVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Hauth/PublicHeader.h> // NOTE: In Xcode 7.1, if two frameworks have the same module name ("Hauth"), // then sometimes one of the frameworks (in my case, tvOS) doesn't compile correctly, // complaining of the inclusion of "non-modular headers". So make these // non modular import calls here. #import "HauthStreamsController.h" #import "HauthClient.h" #import "HauthServer.h" //#import <Hauth/HauthStreamsController.h> //#import <Hauth/HauthClient.h> //#import <Hauth/HauthServer.h>
... FOUNDATION_EXPORT const unsigned char HauthVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Hauth/PublicHeader.h> // NOTE: In Xcode 7.1, if two frameworks have the same module name ("Hauth"), // then sometimes one of the frameworks (in my case, tvOS) doesn't compile correctly, // complaining of the inclusion of "non-modular headers". So make these // non modular import calls here. #import "HauthStreamsController.h" #import "HauthClient.h" #import "HauthServer.h" //#import <Hauth/HauthStreamsController.h> //#import <Hauth/HauthClient.h> //#import <Hauth/HauthServer.h> ...
824985d096b87629cd96151df6f5621bbd44dbd0
governator-core/src/main/java/com/netflix/governator/visitors/WarnOfToInstanceInjectionVisitor.java
governator-core/src/main/java/com/netflix/governator/visitors/WarnOfToInstanceInjectionVisitor.java
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.ProviderInstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } public String visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", providerInstanceBinding.getSource()); } }); } }
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } }); } }
Remove ProviderInstanceBinding as it also captures @Provides methods
Remove ProviderInstanceBinding as it also captures @Provides methods
Java
apache-2.0
elandau/governator,Netflix/governator,tcellucci/governator,tcellucci/governator,tcellucci/governator,elandau/governator,elandau/governator,Netflix/governator
java
## Code Before: package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.ProviderInstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } public String visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", providerInstanceBinding.getSource()); } }); } } ## Instruction: Remove ProviderInstanceBinding as it also captures @Provides methods ## Code After: package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } }); } }
... import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { ... "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } }); } } ...
d4d448adff71b609d5efb269d1a9a2ea4aba3590
radio/templatetags/radio_js_config.py
radio/templatetags/radio_js_config.py
import random import json from django import template from django.conf import settings register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
import random import json from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
Allow SiteOption to load into the JS
Allow SiteOption to load into the JS
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
python
## Code Before: import random import json from django import template from django.conf import settings register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json) ## Instruction: Allow SiteOption to load into the JS ## Code After: import random import json from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
// ... existing code ... from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() // ... modified code ... for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True // ... rest of the code ...
013fa911c7b882a0b362549d4d9b1f9e1e688bc8
violations/py_unittest.py
violations/py_unittest.py
import re from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS, STATUS_FAILED from .base import library @library.register('py_unittest') def py_unittest_violation(data): """Python unittest violation parser""" lines = data['raw'].split('\n') line = '' while len(lines) and not line.startswith('Ran'): line = lines.pop(0) summary = line status = lines.pop(1) data['status'] =\ STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED data['preview'] = render_to_string('violations/py_tests/preview.html', { 'summary': summary, 'status': status, }) data['prepared'] = render_to_string('violations/py_tests/prepared.html', { 'raw': data['raw'], }) plot = {'failures': 0, 'errors': 0} fail_match = re.match(r'.*failures=(\d*).*', status) if fail_match: plot['failures'] = int(fail_match.groups()[0]) error_match = re.match(r'.*errors=(\d*).*', status) if error_match: plot['errors'] = int(error_match.groups()[0]) data['plot'] = plot return data
import re from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS, STATUS_FAILED from .base import library @library.register('py_unittest') def py_unittest_violation(data): """Python unittest violation parser""" lines = data['raw'].split('\n') line = '' while len(lines) and not line.startswith('Ran'): line = lines.pop(0) summary = line status = lines.pop(1) data['status'] =\ STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED data['preview'] = render_to_string('violations/py_tests/preview.html', { 'summary': summary, 'status': status, }) data['prepared'] = render_to_string('violations/py_tests/prepared.html', { 'raw': data['raw'], }) plot = {'failures': 0, 'errors': 0} fail_match = re.match(r'.*failures=(\d*).*', status) if fail_match: plot['failures'] = int(fail_match.groups()[0]) error_match = re.match(r'.*errors=(\d*).*', status) if error_match: plot['errors'] = int(error_match.groups()[0]) total_match = re.match(r'Ran (\d*) tests .*', summary) if total_match: plot['test_count'] = int(total_match.groups()[0]) data['plot'] = plot return data
Add total tests count to py unittest graph
Add total tests count to py unittest graph
Python
mit
nvbn/coviolations_web,nvbn/coviolations_web
python
## Code Before: import re from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS, STATUS_FAILED from .base import library @library.register('py_unittest') def py_unittest_violation(data): """Python unittest violation parser""" lines = data['raw'].split('\n') line = '' while len(lines) and not line.startswith('Ran'): line = lines.pop(0) summary = line status = lines.pop(1) data['status'] =\ STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED data['preview'] = render_to_string('violations/py_tests/preview.html', { 'summary': summary, 'status': status, }) data['prepared'] = render_to_string('violations/py_tests/prepared.html', { 'raw': data['raw'], }) plot = {'failures': 0, 'errors': 0} fail_match = re.match(r'.*failures=(\d*).*', status) if fail_match: plot['failures'] = int(fail_match.groups()[0]) error_match = re.match(r'.*errors=(\d*).*', status) if error_match: plot['errors'] = int(error_match.groups()[0]) data['plot'] = plot return data ## Instruction: Add total tests count to py unittest graph ## Code After: import re from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS, STATUS_FAILED from .base import library @library.register('py_unittest') def py_unittest_violation(data): """Python unittest violation parser""" lines = data['raw'].split('\n') line = '' while len(lines) and not line.startswith('Ran'): line = lines.pop(0) summary = line status = lines.pop(1) data['status'] =\ STATUS_SUCCESS if status.find('OK') == 0 else STATUS_FAILED data['preview'] = render_to_string('violations/py_tests/preview.html', { 'summary': summary, 'status': status, }) data['prepared'] = render_to_string('violations/py_tests/prepared.html', { 'raw': data['raw'], }) plot = {'failures': 0, 'errors': 0} fail_match = re.match(r'.*failures=(\d*).*', status) if fail_match: plot['failures'] = int(fail_match.groups()[0]) error_match = re.match(r'.*errors=(\d*).*', status) if error_match: plot['errors'] = int(error_match.groups()[0]) total_match = re.match(r'Ran (\d*) tests .*', summary) if total_match: plot['test_count'] = int(total_match.groups()[0]) data['plot'] = plot return data
... error_match = re.match(r'.*errors=(\d*).*', status) if error_match: plot['errors'] = int(error_match.groups()[0]) total_match = re.match(r'Ran (\d*) tests .*', summary) if total_match: plot['test_count'] = int(total_match.groups()[0]) data['plot'] = plot return data ...
ca7eb53ac812ec6bfa3c22300eb7992dcd1ad7dc
src/java/wall_follower/Main.java
src/java/wall_follower/Main.java
/* @(#)Main.java */ /** * * * @author <a href="mailto:[email protected]">Geoff Peter Shannon</a> */ package wall_follower; import lejos.hardware.port.SensorPort; import lejos.hardware.sensor.EV3TouchSensor; import lejos.hardware.sensor.EV3UltrasonicSensor; import lejos.hardware.Button; import lejos.hardware.LCD; public class Main { private EV3TouchSensor leftTouch; private EV3TouchSensor rightTouch; private EV3UltrasonicSensor distance; public static void main(String[] args) { Main current = new Main(); Button.waitForAnyEvent(); LCD.clear(); LCD.drawString("Hello, lein java world!", 1, 3); } public Main() { setupSensors(); } void setupSensors() { leftTouch = new EV3TouchSensor(SensorPort.S1); rightTouch = new EV3TouchSensor(SensorPort.S4); distance = new EV3UltrasonicSensor(SensorPort.S3); } }
/* @(#)Main.java */ /** * * * @author <a href="mailto:[email protected]">Geoff Peter Shannon</a> */ package wall_follower; import lejos.hardware.port.SensorPort; import lejos.hardware.sensor.EV3ColorSensor; import lejos.hardware.sensor.EV3TouchSensor; import lejos.hardware.sensor.EV3UltrasonicSensor; import lejos.hardware.Button; import lejos.hardware.LCD; public class Main { private EV3TouchSensor leftTouch; private EV3TouchSensor rightTouch; private EV3ColorSensor color; private EV3UltrasonicSensor distance; public static void main(String[] args) { Main current = new Main(); boolean done = false; while (!done) { current.printSensors(); if (Button.waitForAnyPress(100) != 0) { done = true; } } } public Main() { setupSensors(); } void setupSensors() { leftTouch = new EV3TouchSensor(SensorPort.S1); rightTouch = new EV3TouchSensor(SensorPort.S4); color = new EV3ColorSensor(SensorPort.S2); distance = new EV3UltrasonicSensor(SensorPort.S3); } void printSensors() { LCD.clear(); LCD.drawString("Printing sensor data:", 0, 0); } }
Add color sensor and setup loop to show sensor values
Add color sensor and setup loop to show sensor values
Java
epl-1.0
RadicalZephyr/ev3java
java
## Code Before: /* @(#)Main.java */ /** * * * @author <a href="mailto:[email protected]">Geoff Peter Shannon</a> */ package wall_follower; import lejos.hardware.port.SensorPort; import lejos.hardware.sensor.EV3TouchSensor; import lejos.hardware.sensor.EV3UltrasonicSensor; import lejos.hardware.Button; import lejos.hardware.LCD; public class Main { private EV3TouchSensor leftTouch; private EV3TouchSensor rightTouch; private EV3UltrasonicSensor distance; public static void main(String[] args) { Main current = new Main(); Button.waitForAnyEvent(); LCD.clear(); LCD.drawString("Hello, lein java world!", 1, 3); } public Main() { setupSensors(); } void setupSensors() { leftTouch = new EV3TouchSensor(SensorPort.S1); rightTouch = new EV3TouchSensor(SensorPort.S4); distance = new EV3UltrasonicSensor(SensorPort.S3); } } ## Instruction: Add color sensor and setup loop to show sensor values ## Code After: /* @(#)Main.java */ /** * * * @author <a href="mailto:[email protected]">Geoff Peter Shannon</a> */ package wall_follower; import lejos.hardware.port.SensorPort; import lejos.hardware.sensor.EV3ColorSensor; import lejos.hardware.sensor.EV3TouchSensor; import lejos.hardware.sensor.EV3UltrasonicSensor; import lejos.hardware.Button; import lejos.hardware.LCD; public class Main { private EV3TouchSensor leftTouch; private EV3TouchSensor rightTouch; private EV3ColorSensor color; private EV3UltrasonicSensor distance; public static void main(String[] args) { Main current = new Main(); boolean done = false; while (!done) { current.printSensors(); if (Button.waitForAnyPress(100) != 0) { done = true; } } } public Main() { setupSensors(); } void setupSensors() { leftTouch = new EV3TouchSensor(SensorPort.S1); rightTouch = new EV3TouchSensor(SensorPort.S4); color = new EV3ColorSensor(SensorPort.S2); distance = new EV3UltrasonicSensor(SensorPort.S3); } void printSensors() { LCD.clear(); LCD.drawString("Printing sensor data:", 0, 0); } }
... package wall_follower; import lejos.hardware.port.SensorPort; import lejos.hardware.sensor.EV3ColorSensor; import lejos.hardware.sensor.EV3TouchSensor; import lejos.hardware.sensor.EV3UltrasonicSensor; import lejos.hardware.Button; ... private EV3TouchSensor leftTouch; private EV3TouchSensor rightTouch; private EV3ColorSensor color; private EV3UltrasonicSensor distance; public static void main(String[] args) { Main current = new Main(); boolean done = false; while (!done) { current.printSensors(); if (Button.waitForAnyPress(100) != 0) { done = true; } } } public Main() { ... leftTouch = new EV3TouchSensor(SensorPort.S1); rightTouch = new EV3TouchSensor(SensorPort.S4); color = new EV3ColorSensor(SensorPort.S2); distance = new EV3UltrasonicSensor(SensorPort.S3); } void printSensors() { LCD.clear(); LCD.drawString("Printing sensor data:", 0, 0); } } ...
9676024c92348ed52c78620f2a8b0b4cd104430d
location.py
location.py
from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval __all__ = ['Location'] __metaclass__ = PoolMeta class Location: __name__ = "stock.location" return_address = fields.Many2One( "party.address", "Return Address", states={ 'invisible': Eval('type') != 'warehouse', 'readonly': ~Eval('active'), }, depends=['type', 'active'], help="Return address to print on shipping label" )
from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval __all__ = ['Location'] __metaclass__ = PoolMeta class Location: __name__ = "stock.location" return_address = fields.Many2One( "party.address", "Return Address", states={ 'invisible': Eval('type') != 'warehouse', 'readonly': ~Eval('active'), }, depends=['type', 'active'], help="Return undelivered shipments to this address" )
Rename help text of return address field
Rename help text of return address field
Python
bsd-3-clause
joeirimpan/trytond-shipping,trytonus/trytond-shipping,fulfilio/trytond-shipping,prakashpp/trytond-shipping,tarunbhardwaj/trytond-shipping
python
## Code Before: from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval __all__ = ['Location'] __metaclass__ = PoolMeta class Location: __name__ = "stock.location" return_address = fields.Many2One( "party.address", "Return Address", states={ 'invisible': Eval('type') != 'warehouse', 'readonly': ~Eval('active'), }, depends=['type', 'active'], help="Return address to print on shipping label" ) ## Instruction: Rename help text of return address field ## Code After: from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval __all__ = ['Location'] __metaclass__ = PoolMeta class Location: __name__ = "stock.location" return_address = fields.Many2One( "party.address", "Return Address", states={ 'invisible': Eval('type') != 'warehouse', 'readonly': ~Eval('active'), }, depends=['type', 'active'], help="Return undelivered shipments to this address" )
// ... existing code ... 'invisible': Eval('type') != 'warehouse', 'readonly': ~Eval('active'), }, depends=['type', 'active'], help="Return undelivered shipments to this address" ) // ... rest of the code ...
787494af73a0b0e316547c3ec8536aa9ac21575e
clients.py
clients.py
from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() tcpCliSock.close()
import argparse from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 parser = argparse.ArgumentParser(description='Allow the user to specify a hostname and a port.') parser.add_argument('--hostname', default=HOST, help='Add hostname') parser.add_argument('--port', default=PORT, help='Add port') args = parser.parse_args() ADDR = (args.hostname, int(args.port)) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() tcpCliSock.close()
Allow the user to specify a hostname and port
Allow the user to specify a hostname and port
Python
mit
ccandillo/chapter2
python
## Code Before: from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() tcpCliSock.close() ## Instruction: Allow the user to specify a hostname and port ## Code After: import argparse from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 parser = argparse.ArgumentParser(description='Allow the user to specify a hostname and a port.') parser.add_argument('--hostname', default=HOST, help='Add hostname') parser.add_argument('--port', default=PORT, help='Add port') args = parser.parse_args() ADDR = (args.hostname, int(args.port)) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() tcpCliSock.close()
# ... existing code ... import argparse from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 parser = argparse.ArgumentParser(description='Allow the user to specify a hostname and a port.') parser.add_argument('--hostname', default=HOST, help='Add hostname') parser.add_argument('--port', default=PORT, help='Add port') args = parser.parse_args() ADDR = (args.hostname, int(args.port)) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) # ... rest of the code ...
caaa59ca23d7405ff16726d509e3c0d4e659baec
djstripe/migrations/0023_auto_20170307_0937.py
djstripe/migrations/0023_auto_20170307_0937.py
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('djstripe', '0022_fix_subscriber_delete'), ] operations = [ migrations.AlterField( model_name='customer', name='subscriber', field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=settings.AUTH_USER_MODEL), ), migrations.AlterUniqueTogether( name='customer', unique_together=set([('subscriber', 'livemode')]), ), ]
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL) class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('djstripe', '0022_fix_subscriber_delete'), ] operations = [ migrations.AlterField( model_name='customer', name='subscriber', field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=DJSTRIPE_SUBSCRIBER_MODEL), ), migrations.AlterUniqueTogether( name='customer', unique_together=set([('subscriber', 'livemode')]), ), ]
Fix migration 0023 subscriber model reference
Fix migration 0023 subscriber model reference
Python
mit
pydanny/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,pydanny/dj-stripe,jleclanche/dj-stripe,jleclanche/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,kavdev/dj-stripe,dj-stripe/dj-stripe
python
## Code Before: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('djstripe', '0022_fix_subscriber_delete'), ] operations = [ migrations.AlterField( model_name='customer', name='subscriber', field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=settings.AUTH_USER_MODEL), ), migrations.AlterUniqueTogether( name='customer', unique_together=set([('subscriber', 'livemode')]), ), ] ## Instruction: Fix migration 0023 subscriber model reference ## Code After: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL) class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('djstripe', '0022_fix_subscriber_delete'), ] operations = [ migrations.AlterField( model_name='customer', name='subscriber', field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=DJSTRIPE_SUBSCRIBER_MODEL), ), migrations.AlterUniqueTogether( name='customer', unique_together=set([('subscriber', 'livemode')]), ), ]
// ... existing code ... from django.conf import settings from django.db import migrations, models DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL) class Migration(migrations.Migration): // ... modified code ... migrations.AlterField( model_name='customer', name='subscriber', field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=DJSTRIPE_SUBSCRIBER_MODEL), ), migrations.AlterUniqueTogether( name='customer', // ... rest of the code ...
62818c327997e804090ad8fab328e05410d65d89
resolwe/flow/tests/test_backend.py
resolwe/flow/tests/test_backend.py
from __future__ import absolute_import, division, print_function, unicode_literals import os import shutil from django.conf import settings from django.contrib.auth import get_user_model from django.test import TestCase from resolwe.flow.engines.local import manager from resolwe.flow.models import Data, Process class BackendTest(TestCase): def setUp(self): u = get_user_model().objects.create_superuser('test', '[email protected]', 'test') self.p = Process(slug='test-processor', name='Test Process', contributor=u, type='data:test', version=1) self.p.save() self.d = Data(slug='test-data', name='Test Data', contributor=u, process=self.p) self.d.save() data_path = settings.FLOW_EXECUTOR['DATA_PATH'] if os.path.exists(data_path): shutil.rmtree(data_path) os.makedirs(data_path) def test_manager(self): manager.communicate(verbosity=0) def test_dtlbash(self): self.p.slug = 'test-processor-dtlbash' self.p.run = {'script': """ gen-info \"Test processor info\" gen-warning \"Test processor warning\" echo '{"proc.info": "foo"}' """} self.p.save() self.d.slug = 'test-data-dtlbash' self.d.process = self.p self.d.save() self.d = Data(id=self.d.id)
from __future__ import absolute_import, division, print_function, unicode_literals import os import shutil from django.conf import settings from django.contrib.auth import get_user_model from django.test import TestCase from resolwe.flow.engines.local import manager from resolwe.flow.models import Data, Process class BackendTest(TestCase): def setUp(self): u = get_user_model().objects.create_superuser('test', '[email protected]', 'test') self.p = Process(slug='test-processor', name='Test Process', contributor=u, type='data:test', version=1) self.p.save() self.d = Data(slug='test-data', name='Test Data', contributor=u, process=self.p) self.d.save() def test_manager(self): manager.communicate(verbosity=0) def test_dtlbash(self): self.p.slug = 'test-processor-dtlbash' self.p.run = {'script': """ gen-info \"Test processor info\" gen-warning \"Test processor warning\" echo '{"proc.info": "foo"}' """} self.p.save() self.d.slug = 'test-data-dtlbash' self.d.process = self.p self.d.save() self.d = Data(id=self.d.id)
Remove (potentialy dangerous) data path recreation
Remove (potentialy dangerous) data path recreation
Python
apache-2.0
jberci/resolwe,genialis/resolwe,jberci/resolwe,genialis/resolwe
python
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals import os import shutil from django.conf import settings from django.contrib.auth import get_user_model from django.test import TestCase from resolwe.flow.engines.local import manager from resolwe.flow.models import Data, Process class BackendTest(TestCase): def setUp(self): u = get_user_model().objects.create_superuser('test', '[email protected]', 'test') self.p = Process(slug='test-processor', name='Test Process', contributor=u, type='data:test', version=1) self.p.save() self.d = Data(slug='test-data', name='Test Data', contributor=u, process=self.p) self.d.save() data_path = settings.FLOW_EXECUTOR['DATA_PATH'] if os.path.exists(data_path): shutil.rmtree(data_path) os.makedirs(data_path) def test_manager(self): manager.communicate(verbosity=0) def test_dtlbash(self): self.p.slug = 'test-processor-dtlbash' self.p.run = {'script': """ gen-info \"Test processor info\" gen-warning \"Test processor warning\" echo '{"proc.info": "foo"}' """} self.p.save() self.d.slug = 'test-data-dtlbash' self.d.process = self.p self.d.save() self.d = Data(id=self.d.id) ## Instruction: Remove (potentialy dangerous) data path recreation ## Code After: from __future__ import absolute_import, division, print_function, unicode_literals import os import shutil from django.conf import settings from django.contrib.auth import get_user_model from django.test import TestCase from resolwe.flow.engines.local import manager from resolwe.flow.models import Data, Process class BackendTest(TestCase): def setUp(self): u = get_user_model().objects.create_superuser('test', '[email protected]', 'test') self.p = Process(slug='test-processor', name='Test Process', contributor=u, type='data:test', version=1) self.p.save() self.d = Data(slug='test-data', name='Test Data', contributor=u, process=self.p) self.d.save() def test_manager(self): manager.communicate(verbosity=0) def test_dtlbash(self): self.p.slug = 'test-processor-dtlbash' self.p.run = {'script': """ gen-info \"Test processor info\" gen-warning \"Test processor warning\" echo '{"proc.info": "foo"}' """} self.p.save() self.d.slug = 'test-data-dtlbash' self.d.process = self.p self.d.save() self.d = Data(id=self.d.id)
// ... existing code ... contributor=u, process=self.p) self.d.save() def test_manager(self): manager.communicate(verbosity=0) // ... rest of the code ...
96286fd56572d17ccfc86d465add2f31863ec078
src/main/java/com/alexrnl/jbetaseries/request/parameters/Note.java
src/main/java/com/alexrnl/jbetaseries/request/parameters/Note.java
package com.alexrnl.jbetaseries.request.parameters; /** * Parameter which allow to set the note of a show or an episode.<br /> * @author Alex */ public class Note extends Parameter<Integer> { /** Name of the note parameter */ public static final String PARAMETER_NOTE = "note"; /** * Constructor #1.<br /> * @param note * the note to set. * @throws IllegalArgumentException * if the not is outside the range [1;5]. */ public Note (final Integer note) throws IllegalArgumentException { super(PARAMETER_NOTE, note); if (note < 1 || 5 < note) { throw new IllegalArgumentException("The note must be comprise between 1 and 5."); } } }
package com.alexrnl.jbetaseries.request.parameters; /** * Parameter which allow to set the note of a show or an episode.<br /> * @author Alex */ public class Note extends Parameter<Integer> { /** Name of the note parameter */ public static final String PARAMETER_NOTE = "note"; /** The minimum note allowed by the API */ public static final int NOTE_MIN = 1; /** The maximum note allowed by the API */ public static final int NOTE_MAX = 5; /** * Constructor #1.<br /> * @param note * the note to set. * @throws IllegalArgumentException * if the not is outside the range [1;5]. */ public Note (final Integer note) throws IllegalArgumentException { super(PARAMETER_NOTE, note); if (note < NOTE_MIN || note > NOTE_MAX) { throw new IllegalArgumentException("The note must be comprise between 1 and 5."); } } }
Fix Sonar violation: create constants for note min/max
Fix Sonar violation: create constants for note min/max
Java
bsd-3-clause
AlexRNL/jSeries
java
## Code Before: package com.alexrnl.jbetaseries.request.parameters; /** * Parameter which allow to set the note of a show or an episode.<br /> * @author Alex */ public class Note extends Parameter<Integer> { /** Name of the note parameter */ public static final String PARAMETER_NOTE = "note"; /** * Constructor #1.<br /> * @param note * the note to set. * @throws IllegalArgumentException * if the not is outside the range [1;5]. */ public Note (final Integer note) throws IllegalArgumentException { super(PARAMETER_NOTE, note); if (note < 1 || 5 < note) { throw new IllegalArgumentException("The note must be comprise between 1 and 5."); } } } ## Instruction: Fix Sonar violation: create constants for note min/max ## Code After: package com.alexrnl.jbetaseries.request.parameters; /** * Parameter which allow to set the note of a show or an episode.<br /> * @author Alex */ public class Note extends Parameter<Integer> { /** Name of the note parameter */ public static final String PARAMETER_NOTE = "note"; /** The minimum note allowed by the API */ public static final int NOTE_MIN = 1; /** The maximum note allowed by the API */ public static final int NOTE_MAX = 5; /** * Constructor #1.<br /> * @param note * the note to set. * @throws IllegalArgumentException * if the not is outside the range [1;5]. */ public Note (final Integer note) throws IllegalArgumentException { super(PARAMETER_NOTE, note); if (note < NOTE_MIN || note > NOTE_MAX) { throw new IllegalArgumentException("The note must be comprise between 1 and 5."); } } }
... public class Note extends Parameter<Integer> { /** Name of the note parameter */ public static final String PARAMETER_NOTE = "note"; /** The minimum note allowed by the API */ public static final int NOTE_MIN = 1; /** The maximum note allowed by the API */ public static final int NOTE_MAX = 5; /** * Constructor #1.<br /> ... */ public Note (final Integer note) throws IllegalArgumentException { super(PARAMETER_NOTE, note); if (note < NOTE_MIN || note > NOTE_MAX) { throw new IllegalArgumentException("The note must be comprise between 1 and 5."); } } ...
73373c893c1fe8412b5a3fecc83767988b1bccdf
genshi/__init__.py
genshi/__init__.py
__docformat__ = 'restructuredtext en' try: from pkg_resources import get_distribution, ResolutionError try: __version__ = get_distribution('Genshi').version except ResolutionError: __version__ = None # unknown except ImportError: __version__ = None # unknown from genshi.core import * from genshi.input import ParseError, XML, HTML
__docformat__ = 'restructuredtext en' __version__ = '0.6' from genshi.core import * from genshi.input import ParseError, XML, HTML
Remove pkg_resources import from top-level package, will just need to remember updating the version in two places.
Remove pkg_resources import from top-level package, will just need to remember updating the version in two places.
Python
bsd-3-clause
hodgestar/genshi,hodgestar/genshi,hodgestar/genshi,hodgestar/genshi
python
## Code Before: __docformat__ = 'restructuredtext en' try: from pkg_resources import get_distribution, ResolutionError try: __version__ = get_distribution('Genshi').version except ResolutionError: __version__ = None # unknown except ImportError: __version__ = None # unknown from genshi.core import * from genshi.input import ParseError, XML, HTML ## Instruction: Remove pkg_resources import from top-level package, will just need to remember updating the version in two places. ## Code After: __docformat__ = 'restructuredtext en' __version__ = '0.6' from genshi.core import * from genshi.input import ParseError, XML, HTML
# ... existing code ... __docformat__ = 'restructuredtext en' __version__ = '0.6' from genshi.core import * from genshi.input import ParseError, XML, HTML # ... rest of the code ...
122ba850fb9d7c9ca51d66714dd38cb2187134f3
Lib/setup.py
Lib/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Python
bsd-3-clause
josephcslater/scipy,rmcgibbo/scipy,ndchorley/scipy,lukauskas/scipy,vberaudi/scipy,dch312/scipy,gfyoung/scipy,andyfaff/scipy,chatcannon/scipy,WarrenWeckesser/scipy,mtrbean/scipy,argriffing/scipy,nvoron23/scipy,WillieMaddox/scipy,aarchiba/scipy,anntzer/scipy,lhilt/scipy,nonhermitian/scipy,teoliphant/scipy,minhlongdo/scipy,WarrenWeckesser/scipy,piyush0609/scipy,dominicelse/scipy,mingwpy/scipy,ales-erjavec/scipy,gef756/scipy,mtrbean/scipy,pnedunuri/scipy,zerothi/scipy,andim/scipy,nvoron23/scipy,jseabold/scipy,lukauskas/scipy,lhilt/scipy,minhlongdo/scipy,Stefan-Endres/scipy,chatcannon/scipy,gef756/scipy,niknow/scipy,rgommers/scipy,scipy/scipy,mortada/scipy,andyfaff/scipy,giorgiop/scipy,sauliusl/scipy,mortonjt/scipy,arokem/scipy,raoulbq/scipy,ChanderG/scipy,Shaswat27/scipy,argriffing/scipy,felipebetancur/scipy,gef756/scipy,sonnyhu/scipy,endolith/scipy,grlee77/scipy,niknow/scipy,kleskjr/scipy,Shaswat27/scipy,mgaitan/scipy,niknow/scipy,surhudm/scipy,pizzathief/scipy,josephcslater/scipy,mhogg/scipy,pyramania/scipy,Stefan-Endres/scipy,efiring/scipy,nonhermitian/scipy,WillieMaddox/scipy,ales-erjavec/scipy,cpaulik/scipy,gfyoung/scipy,kalvdans/scipy,jjhelmus/scipy,hainm/scipy,maniteja123/scipy,witcxc/scipy,ortylp/scipy,gef756/scipy,fernand/scipy,Srisai85/scipy,njwilson23/scipy,pyramania/scipy,pschella/scipy,jjhelmus/scipy,behzadnouri/scipy,mhogg/scipy,rmcgibbo/scipy,ndchorley/scipy,trankmichael/scipy,pizzathief/scipy,jjhelmus/scipy,woodscn/scipy,anntzer/scipy,anielsen001/scipy,chatcannon/scipy,ChanderG/scipy,gfyoung/scipy,Gillu13/scipy,sargas/scipy,futurulus/scipy,vberaudi/scipy,tylerjereddy/scipy,jsilter/scipy,woodscn/scipy,tylerjereddy/scipy,perimosocordiae/scipy,matthewalbani/scipy,ales-erjavec/scipy,woodscn/scipy,Newman101/scipy,andim/scipy,jonycgn/scipy,njwilson23/scipy,hainm/scipy,vhaasteren/scipy,pbrod/scipy,newemailjdm/scipy,behzadnouri/scipy,aman-iitj/scipy,scipy/scipy,juliantaylor/scipy,ChanderG/scipy,mortonjt/scipy,Eric89GXL/scipy,jor-/scipy,aeklant/scipy,aman-iitj/scipy,mikebenfield/scipy,sonnyhu/scipy,pschella/scipy,matthewalbani/scipy,petebachant/scipy,zaxliu/scipy,jonycgn/scipy,mgaitan/scipy,aarchiba/scipy,hainm/scipy,kalvdans/scipy,minhlongdo/scipy,Stefan-Endres/scipy,jjhelmus/scipy,kleskjr/scipy,behzadnouri/scipy,e-q/scipy,newemailjdm/scipy,witcxc/scipy,Kamp9/scipy,endolith/scipy,aarchiba/scipy,rmcgibbo/scipy,piyush0609/scipy,rgommers/scipy,rgommers/scipy,jsilter/scipy,pizzathief/scipy,argriffing/scipy,futurulus/scipy,sonnyhu/scipy,piyush0609/scipy,ilayn/scipy,pnedunuri/scipy,vhaasteren/scipy,ndchorley/scipy,e-q/scipy,fredrikw/scipy,vanpact/scipy,newemailjdm/scipy,nvoron23/scipy,mortada/scipy,ogrisel/scipy,pbrod/scipy,matthew-brett/scipy,tylerjereddy/scipy,scipy/scipy,Srisai85/scipy,FRidh/scipy,pschella/scipy,maciejkula/scipy,jor-/scipy,trankmichael/scipy,Eric89GXL/scipy,mtrbean/scipy,jsilter/scipy,grlee77/scipy,ogrisel/scipy,anielsen001/scipy,jakevdp/scipy,Stefan-Endres/scipy,juliantaylor/scipy,nmayorov/scipy,befelix/scipy,jakevdp/scipy,raoulbq/scipy,rmcgibbo/scipy,ndchorley/scipy,futurulus/scipy,zxsted/scipy,befelix/scipy,sonnyhu/scipy,petebachant/scipy,haudren/scipy,Gillu13/scipy,trankmichael/scipy,endolith/scipy,gertingold/scipy,mtrbean/scipy,raoulbq/scipy,efiring/scipy,ortylp/scipy,gertingold/scipy,mingwpy/scipy,befelix/scipy,zaxliu/scipy,njwilson23/scipy,maciejkula/scipy,mdhaber/scipy,raoulbq/scipy,dominicelse/scipy,bkendzior/scipy,Kamp9/scipy,Newman101/scipy,argriffing/scipy,sriki18/scipy,maniteja123/scipy,pbrod/scipy,zxsted/scipy,haudren/scipy,FRidh/scipy,kleskjr/scipy,larsmans/scipy,grlee77/scipy,richardotis/scipy,jonycgn/scipy,dch312/scipy,futurulus/scipy,futurulus/scipy,sauliusl/scipy,andim/scipy,matthew-brett/scipy,sauliusl/scipy,rmcgibbo/scipy,rgommers/scipy,ogrisel/scipy,Shaswat27/scipy,jakevdp/scipy,aeklant/scipy,mingwpy/scipy,vanpact/scipy,pyramania/scipy,Shaswat27/scipy,bkendzior/scipy,njwilson23/scipy,mhogg/scipy,gdooper/scipy,Dapid/scipy,raoulbq/scipy,felipebetancur/scipy,ilayn/scipy,pnedunuri/scipy,anielsen001/scipy,Dapid/scipy,nonhermitian/scipy,rgommers/scipy,cpaulik/scipy,andyfaff/scipy,Gillu13/scipy,gertingold/scipy,matthewalbani/scipy,jsilter/scipy,jonycgn/scipy,kleskjr/scipy,haudren/scipy,jakevdp/scipy,efiring/scipy,e-q/scipy,perimosocordiae/scipy,minhlongdo/scipy,Eric89GXL/scipy,fredrikw/scipy,nmayorov/scipy,Eric89GXL/scipy,mortada/scipy,cpaulik/scipy,Stefan-Endres/scipy,matthew-brett/scipy,apbard/scipy,anntzer/scipy,sriki18/scipy,nmayorov/scipy,witcxc/scipy,Shaswat27/scipy,bkendzior/scipy,jamestwebber/scipy,jonycgn/scipy,pyramania/scipy,petebachant/scipy,mdhaber/scipy,larsmans/scipy,cpaulik/scipy,minhlongdo/scipy,jonycgn/scipy,njwilson23/scipy,apbard/scipy,josephcslater/scipy,trankmichael/scipy,sonnyhu/scipy,person142/scipy,ales-erjavec/scipy,sargas/scipy,gertingold/scipy,mhogg/scipy,efiring/scipy,ilayn/scipy,vhaasteren/scipy,piyush0609/scipy,futurulus/scipy,Gillu13/scipy,maniteja123/scipy,arokem/scipy,fernand/scipy,surhudm/scipy,dch312/scipy,vigna/scipy,josephcslater/scipy,andim/scipy,jseabold/scipy,woodscn/scipy,perimosocordiae/scipy,mikebenfield/scipy,kleskjr/scipy,zerothi/scipy,surhudm/scipy,zerothi/scipy,arokem/scipy,dominicelse/scipy,mhogg/scipy,pizzathief/scipy,vhaasteren/scipy,nonhermitian/scipy,mingwpy/scipy,anntzer/scipy,mortada/scipy,aman-iitj/scipy,richardotis/scipy,zxsted/scipy,petebachant/scipy,mhogg/scipy,zerothi/scipy,sonnyhu/scipy,pnedunuri/scipy,nonhermitian/scipy,mortonjt/scipy,mikebenfield/scipy,fredrikw/scipy,Newman101/scipy,vigna/scipy,efiring/scipy,anntzer/scipy,niknow/scipy,vhaasteren/scipy,tylerjereddy/scipy,andyfaff/scipy,ndchorley/scipy,giorgiop/scipy,fredrikw/scipy,jjhelmus/scipy,piyush0609/scipy,ortylp/scipy,richardotis/scipy,zerothi/scipy,aarchiba/scipy,andyfaff/scipy,jamestwebber/scipy,ortylp/scipy,fernand/scipy,teoliphant/scipy,ales-erjavec/scipy,bkendzior/scipy,sargas/scipy,lukauskas/scipy,e-q/scipy,maniteja123/scipy,dominicelse/scipy,petebachant/scipy,endolith/scipy,maciejkula/scipy,anntzer/scipy,jseabold/scipy,sauliusl/scipy,larsmans/scipy,gef756/scipy,richardotis/scipy,Srisai85/scipy,anielsen001/scipy,josephcslater/scipy,WarrenWeckesser/scipy,felipebetancur/scipy,piyush0609/scipy,vberaudi/scipy,apbard/scipy,woodscn/scipy,person142/scipy,mdhaber/scipy,zaxliu/scipy,maniteja123/scipy,pbrod/scipy,njwilson23/scipy,kleskjr/scipy,ChanderG/scipy,Newman101/scipy,felipebetancur/scipy,behzadnouri/scipy,argriffing/scipy,maciejkula/scipy,matthewalbani/scipy,grlee77/scipy,nmayorov/scipy,Dapid/scipy,jor-/scipy,Srisai85/scipy,matthew-brett/scipy,minhlongdo/scipy,apbard/scipy,mortonjt/scipy,mdhaber/scipy,giorgiop/scipy,larsmans/scipy,ndchorley/scipy,scipy/scipy,mtrbean/scipy,WarrenWeckesser/scipy,dch312/scipy,lukauskas/scipy,juliantaylor/scipy,mgaitan/scipy,fernand/scipy,perimosocordiae/scipy,pbrod/scipy,gfyoung/scipy,person142/scipy,richardotis/scipy,zaxliu/scipy,mgaitan/scipy,trankmichael/scipy,Kamp9/scipy,haudren/scipy,mikebenfield/scipy,trankmichael/scipy,aman-iitj/scipy,surhudm/scipy,jseabold/scipy,kalvdans/scipy,gertingold/scipy,person142/scipy,fernand/scipy,Shaswat27/scipy,ogrisel/scipy,mortonjt/scipy,nvoron23/scipy,giorgiop/scipy,WillieMaddox/scipy,pizzathief/scipy,mgaitan/scipy,zxsted/scipy,Eric89GXL/scipy,mortada/scipy,fredrikw/scipy,apbard/scipy,woodscn/scipy,Kamp9/scipy,ilayn/scipy,sriki18/scipy,arokem/scipy,WillieMaddox/scipy,newemailjdm/scipy,andyfaff/scipy,kalvdans/scipy,vigna/scipy,nvoron23/scipy,aman-iitj/scipy,dominicelse/scipy,endolith/scipy,aarchiba/scipy,sargas/scipy,lhilt/scipy,juliantaylor/scipy,cpaulik/scipy,felipebetancur/scipy,arokem/scipy,Newman101/scipy,FRidh/scipy,andim/scipy,mdhaber/scipy,scipy/scipy,zaxliu/scipy,jor-/scipy,Gillu13/scipy,sauliusl/scipy,felipebetancur/scipy,jseabold/scipy,surhudm/scipy,WillieMaddox/scipy,dch312/scipy,jor-/scipy,zxsted/scipy,pnedunuri/scipy,gdooper/scipy,ortylp/scipy,Newman101/scipy,zaxliu/scipy,mgaitan/scipy,vanpact/scipy,Stefan-Endres/scipy,sriki18/scipy,teoliphant/scipy,aeklant/scipy,witcxc/scipy,bkendzior/scipy,mingwpy/scipy,e-q/scipy,efiring/scipy,anielsen001/scipy,vigna/scipy,hainm/scipy,behzadnouri/scipy,andim/scipy,FRidh/scipy,FRidh/scipy,sargas/scipy,lhilt/scipy,hainm/scipy,aeklant/scipy,perimosocordiae/scipy,jseabold/scipy,scipy/scipy,rmcgibbo/scipy,Eric89GXL/scipy,befelix/scipy,gef756/scipy,ilayn/scipy,pbrod/scipy,jsilter/scipy,matthewalbani/scipy,vberaudi/scipy,vanpact/scipy,anielsen001/scipy,kalvdans/scipy,haudren/scipy,surhudm/scipy,jamestwebber/scipy,newemailjdm/scipy,witcxc/scipy,nmayorov/scipy,sriki18/scipy,Srisai85/scipy,giorgiop/scipy,Dapid/scipy,fredrikw/scipy,gfyoung/scipy,mingwpy/scipy,zerothi/scipy,person142/scipy,WillieMaddox/scipy,sriki18/scipy,maniteja123/scipy,vberaudi/scipy,chatcannon/scipy,matthew-brett/scipy,perimosocordiae/scipy,hainm/scipy,ortylp/scipy,raoulbq/scipy,sauliusl/scipy,vanpact/scipy,chatcannon/scipy,larsmans/scipy,pnedunuri/scipy,ogrisel/scipy,maciejkula/scipy,WarrenWeckesser/scipy,mtrbean/scipy,nvoron23/scipy,ales-erjavec/scipy,juliantaylor/scipy,Kamp9/scipy,jakevdp/scipy,vhaasteren/scipy,niknow/scipy,aman-iitj/scipy,Dapid/scipy,pschella/scipy,lukauskas/scipy,jamestwebber/scipy,vigna/scipy,teoliphant/scipy,ChanderG/scipy,argriffing/scipy,Srisai85/scipy,behzadnouri/scipy,niknow/scipy,mortonjt/scipy,Dapid/scipy,FRidh/scipy,aeklant/scipy,giorgiop/scipy,endolith/scipy,larsmans/scipy,vanpact/scipy,ChanderG/scipy,WarrenWeckesser/scipy,mikebenfield/scipy,mdhaber/scipy,haudren/scipy,grlee77/scipy,pyramania/scipy,gdooper/scipy,fernand/scipy,lhilt/scipy,newemailjdm/scipy,gdooper/scipy,gdooper/scipy,zxsted/scipy,lukauskas/scipy,Kamp9/scipy,jamestwebber/scipy,richardotis/scipy,tylerjereddy/scipy,chatcannon/scipy,befelix/scipy,mortada/scipy,pschella/scipy,petebachant/scipy,Gillu13/scipy,vberaudi/scipy,teoliphant/scipy,ilayn/scipy,cpaulik/scipy
python
## Code Before: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) ## Instruction: Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too. ## Code After: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
... def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config ...
9a57656c946e138a0eb805aad47724bcfc9ca7c7
src/test/java/org/jboss/loom/migrators/_ext/ExternalMigratorsTestEnv.java
src/test/java/org/jboss/loom/migrators/_ext/ExternalMigratorsTestEnv.java
package org.jboss.loom.migrators._ext; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.loom.utils.ClassUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class to prepare external migrators test environment (copies files etc.). * * @author Ondrej Zizka, ozizka at redhat.com */ public class ExternalMigratorsTestEnv { private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class ); protected static File workDir; @BeforeClass public static void copyTestExtMigratorFiles() throws IOException { workDir = new File("target/extMigrators/"); FileUtils.forceMkdir( workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy", workDir ); } @AfterClass public static void deleteTestExtMigratorFiles() throws IOException { FileUtils.forceDelete( workDir ); } }// class
package org.jboss.loom.migrators._ext; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.loom.utils.ClassUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class to prepare external migrators test environment (copies files etc.). * * @author Ondrej Zizka, ozizka at redhat.com */ public class ExternalMigratorsTestEnv { private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class ); protected static File workDir; @BeforeClass public static void copyTestExtMigratorFiles() throws IOException { workDir = new File("target/extMigrators/"); FileUtils.forceMkdir( workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestMigrator.mig.xml", workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestJaxbBean.groovy", workDir ); } @AfterClass public static void deleteTestExtMigratorFiles() throws IOException { FileUtils.forceDelete( workDir ); } }// class
Move test to test src
Move test to test src
Java
apache-2.0
OndraZizka/jboss-migration,OndraZizka/jboss-migration,OndraZizka/jboss-migration
java
## Code Before: package org.jboss.loom.migrators._ext; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.loom.utils.ClassUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class to prepare external migrators test environment (copies files etc.). * * @author Ondrej Zizka, ozizka at redhat.com */ public class ExternalMigratorsTestEnv { private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class ); protected static File workDir; @BeforeClass public static void copyTestExtMigratorFiles() throws IOException { workDir = new File("target/extMigrators/"); FileUtils.forceMkdir( workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy", workDir ); } @AfterClass public static void deleteTestExtMigratorFiles() throws IOException { FileUtils.forceDelete( workDir ); } }// class ## Instruction: Move test to test src ## Code After: package org.jboss.loom.migrators._ext; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.loom.utils.ClassUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class to prepare external migrators test environment (copies files etc.). * * @author Ondrej Zizka, ozizka at redhat.com */ public class ExternalMigratorsTestEnv { private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class ); protected static File workDir; @BeforeClass public static void copyTestExtMigratorFiles() throws IOException { workDir = new File("target/extMigrators/"); FileUtils.forceMkdir( workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestMigrator.mig.xml", workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestJaxbBean.groovy", workDir ); } @AfterClass public static void deleteTestExtMigratorFiles() throws IOException { FileUtils.forceDelete( workDir ); } }// class
... public static void copyTestExtMigratorFiles() throws IOException { workDir = new File("target/extMigrators/"); FileUtils.forceMkdir( workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestMigrator.mig.xml", workDir ); ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestJaxbBean.groovy", workDir ); } @AfterClass ...
92ca956dc8f4229a1c427cb24843c7fe3baef405
tests/integration/test_parked.py
tests/integration/test_parked.py
"""Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' }
"""Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' } def test_parked_query_on_broken_domain(webapp): """Test the parked API against a domain that doesn't exist.""" request = webapp.get('/api/parked/there-is-little-chance-this-domain-exists-i-hope.com') assert request.status_code == 200 assert request.json['score'] == 0 assert request.json['redirects'] is False assert request.json['redirects_to'] is None assert request.json['score_text'] == 'Unlikely'
Test for parked check against unresolvable domain
Test for parked check against unresolvable domain
Python
unlicense
thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister
python
## Code Before: """Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' } ## Instruction: Test for parked check against unresolvable domain ## Code After: """Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' } def test_parked_query_on_broken_domain(webapp): """Test the parked API against a domain that doesn't exist.""" request = webapp.get('/api/parked/there-is-little-chance-this-domain-exists-i-hope.com') assert request.status_code == 200 assert request.json['score'] == 0 assert request.json['redirects'] is False assert request.json['redirects_to'] is None assert request.json['score_text'] == 'Unlikely'
... u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' } def test_parked_query_on_broken_domain(webapp): """Test the parked API against a domain that doesn't exist.""" request = webapp.get('/api/parked/there-is-little-chance-this-domain-exists-i-hope.com') assert request.status_code == 200 assert request.json['score'] == 0 assert request.json['redirects'] is False assert request.json['redirects_to'] is None assert request.json['score_text'] == 'Unlikely' ...
65d2d80d5c0121ef30d42e236819a0b3db8017cd
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/vdscommands/gluster/GlusterServicesListVDSParameters.java
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/vdscommands/gluster/GlusterServicesListVDSParameters.java
package org.ovirt.engine.core.common.vdscommands.gluster; import java.util.List; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; import org.ovirt.engine.core.compat.Guid; /** * VDS parameters class with Server ID and service names as parameters, Used by the "Gluster Services List" command. */ public class GlusterServicesListVDSParameters extends VdsIdVDSCommandParametersBase { private List<String> serviceNames; public GlusterServicesListVDSParameters(Guid serverId, List<String> serviceNames) { super(serverId); this.serviceNames = serviceNames; } public List<String> getServiceNames() { return serviceNames; } }
package org.ovirt.engine.core.common.vdscommands.gluster; import java.util.Set; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; import org.ovirt.engine.core.compat.Guid; /** * VDS parameters class with Server ID and service names as parameters, Used by the "Gluster Services List" command. */ public class GlusterServicesListVDSParameters extends VdsIdVDSCommandParametersBase { private Set<String> serviceNames; public GlusterServicesListVDSParameters(Guid serverId, Set<String> serviceNames) { super(serverId); this.serviceNames = serviceNames; } public Set<String> getServiceNames() { return serviceNames; } }
Use Set instead of List for serviceNames
gluster: Use Set instead of List for serviceNames Use Set instead of List for serviceNames in GlusterServicesListVDSParameters Change-Id: I26109a71448968fea0055c3d2df3c843e23d70f3 Signed-off-by: Shireesh Anjal <[email protected]>
Java
apache-2.0
walteryang47/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine
java
## Code Before: package org.ovirt.engine.core.common.vdscommands.gluster; import java.util.List; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; import org.ovirt.engine.core.compat.Guid; /** * VDS parameters class with Server ID and service names as parameters, Used by the "Gluster Services List" command. */ public class GlusterServicesListVDSParameters extends VdsIdVDSCommandParametersBase { private List<String> serviceNames; public GlusterServicesListVDSParameters(Guid serverId, List<String> serviceNames) { super(serverId); this.serviceNames = serviceNames; } public List<String> getServiceNames() { return serviceNames; } } ## Instruction: gluster: Use Set instead of List for serviceNames Use Set instead of List for serviceNames in GlusterServicesListVDSParameters Change-Id: I26109a71448968fea0055c3d2df3c843e23d70f3 Signed-off-by: Shireesh Anjal <[email protected]> ## Code After: package org.ovirt.engine.core.common.vdscommands.gluster; import java.util.Set; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; import org.ovirt.engine.core.compat.Guid; /** * VDS parameters class with Server ID and service names as parameters, Used by the "Gluster Services List" command. */ public class GlusterServicesListVDSParameters extends VdsIdVDSCommandParametersBase { private Set<String> serviceNames; public GlusterServicesListVDSParameters(Guid serverId, Set<String> serviceNames) { super(serverId); this.serviceNames = serviceNames; } public Set<String> getServiceNames() { return serviceNames; } }
# ... existing code ... package org.ovirt.engine.core.common.vdscommands.gluster; import java.util.Set; import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase; import org.ovirt.engine.core.compat.Guid; # ... modified code ... * VDS parameters class with Server ID and service names as parameters, Used by the "Gluster Services List" command. */ public class GlusterServicesListVDSParameters extends VdsIdVDSCommandParametersBase { private Set<String> serviceNames; public GlusterServicesListVDSParameters(Guid serverId, Set<String> serviceNames) { super(serverId); this.serviceNames = serviceNames; } public Set<String> getServiceNames() { return serviceNames; } } # ... rest of the code ...
978b41a29eda295974ed5cf1a7cd5b79b148f479
coverage/execfile.py
coverage/execfile.py
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) try: src = open(filename) imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) src = open(filename) try: imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
Move the open outside the try, since the finally is only needed once the file is successfully opened.
Move the open outside the try, since the finally is only needed once the file is successfully opened.
Python
apache-2.0
7WebPages/coveragepy,blueyed/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,nedbat/coveragepy,blueyed/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,blueyed/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,hugovk/coveragepy
python
## Code Before: """Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) try: src = open(filename) imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close() ## Instruction: Move the open outside the try, since the finally is only needed once the file is successfully opened. ## Code After: """Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.argv. """ # Most code that does this does it in a way that leaves __main__ or __file__ # with the wrong values. Importing the code as __main__ gets all of this # right automatically. # # One difference from python.exe: if I run foo.py from the command line, it # always uses foo.py. With this code, it might find foo.pyc instead. sys.argv = args sys.path[0] = os.path.dirname(filename) src = open(filename) try: imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
# ... existing code ... sys.argv = args sys.path[0] = os.path.dirname(filename) src = open(filename) try: imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close() # ... rest of the code ...
0ca07405b864f761ae1d7ed659cac67c799bf39a
src/core/queue.py
src/core/queue.py
class ActionsQueue: def __init__(self): self.queue = [] # Normal buttons def btnBrowse(self, val): print(val) def actionReset(self, val): print(val) def btnRedirect(self, val): print(val) # Radio buttons def radioColor256(self, val): print(val) def radioColor16b(self, val): print(val) def radioModelLow(self, val): print(val) def radioModelFast(self, val): print(val) def radioModelHigh(self, val): print(val) def radioTexFast(self, val): print(val) def radioTexHigh(self, val): print(val) # Check boxes def chkCursor(self, val): print(val) def chkDraw3D(self, val): print(val) def chkFlipVideo(self, val): print(val) def chkFullscreen(self, val): print(val) def chkJoystick(self, val): print(val) def chkMusic(self, val): print(val) def chkSound(self, val): print(val) # Direct3D dropdown selection def comboD3D(self, val): print(val)
class ActionsQueue: def __init__(self): self.queue = [] class Responses: def __init__(self): pass # Normal buttons def btnBrowse(self, val): print(val) def actionReset(self, val): print(val) def btnRedirect(self, val): print(val) # Radio buttons def radioColor256(self, val): print(val) def radioColor16b(self, val): print(val) def radioModelLow(self, val): print(val) def radioModelFast(self, val): print(val) def radioModelHigh(self, val): print(val) def radioTexFast(self, val): print(val) def radioTexHigh(self, val): print(val) # Check boxes def chkCursor(self, val): print(val) def chkDraw3D(self, val): print(val) def chkFlipVideo(self, val): print(val) def chkFullscreen(self, val): print(val) def chkJoystick(self, val): print(val) def chkMusic(self, val): print(val) def chkSound(self, val): print(val) # Direct3D dropdown selection def comboD3D(self, val): print(val)
Move those methods to own class
Move those methods to own class [ci skip]
Python
mit
le717/ICU
python
## Code Before: class ActionsQueue: def __init__(self): self.queue = [] # Normal buttons def btnBrowse(self, val): print(val) def actionReset(self, val): print(val) def btnRedirect(self, val): print(val) # Radio buttons def radioColor256(self, val): print(val) def radioColor16b(self, val): print(val) def radioModelLow(self, val): print(val) def radioModelFast(self, val): print(val) def radioModelHigh(self, val): print(val) def radioTexFast(self, val): print(val) def radioTexHigh(self, val): print(val) # Check boxes def chkCursor(self, val): print(val) def chkDraw3D(self, val): print(val) def chkFlipVideo(self, val): print(val) def chkFullscreen(self, val): print(val) def chkJoystick(self, val): print(val) def chkMusic(self, val): print(val) def chkSound(self, val): print(val) # Direct3D dropdown selection def comboD3D(self, val): print(val) ## Instruction: Move those methods to own class [ci skip] ## Code After: class ActionsQueue: def __init__(self): self.queue = [] class Responses: def __init__(self): pass # Normal buttons def btnBrowse(self, val): print(val) def actionReset(self, val): print(val) def btnRedirect(self, val): print(val) # Radio buttons def radioColor256(self, val): print(val) def radioColor16b(self, val): print(val) def radioModelLow(self, val): print(val) def radioModelFast(self, val): print(val) def radioModelHigh(self, val): print(val) def radioTexFast(self, val): print(val) def radioTexHigh(self, val): print(val) # Check boxes def chkCursor(self, val): print(val) def chkDraw3D(self, val): print(val) def chkFlipVideo(self, val): print(val) def chkFullscreen(self, val): print(val) def chkJoystick(self, val): print(val) def chkMusic(self, val): print(val) def chkSound(self, val): print(val) # Direct3D dropdown selection def comboD3D(self, val): print(val)
... def __init__(self): self.queue = [] class Responses: def __init__(self): pass # Normal buttons def btnBrowse(self, val): ...
0f16fe34654560f8889ad1f5b199cb8bfa2b3846
tests/web/test_status.py
tests/web/test_status.py
from biothings.tests.web import BiothingsTestCase from setup import setup_es # pylint: disable=unused-import class TestStatus(BiothingsTestCase): def test_01_get(self): res = self.request('/status').text assert res == 'OK' def test_02_head(self): self.request('/status', method='HEAD')
from biothings.tests.web import BiothingsTestCase from setup import setup_es # pylint: disable=unused-import class TestStatus(BiothingsTestCase): def test_01_get(self): """ { "code": 200, "status": "yellow", "payload": { "id": "1017", "index": "bts_test", "doc_type": "_all" }, "response": { "_index": "bts_test", "_type": "gene", "_id": "1017", "_version": 1, "found": true, "_source": { ... } } } """ res = self.request('/status').json() assert res['code'] == 200 assert res['response']['found'] def test_02_head(self): self.request('/status', method='HEAD')
Update test case for status handler accordingly
Update test case for status handler accordingly
Python
apache-2.0
biothings/biothings.api,biothings/biothings.api
python
## Code Before: from biothings.tests.web import BiothingsTestCase from setup import setup_es # pylint: disable=unused-import class TestStatus(BiothingsTestCase): def test_01_get(self): res = self.request('/status').text assert res == 'OK' def test_02_head(self): self.request('/status', method='HEAD') ## Instruction: Update test case for status handler accordingly ## Code After: from biothings.tests.web import BiothingsTestCase from setup import setup_es # pylint: disable=unused-import class TestStatus(BiothingsTestCase): def test_01_get(self): """ { "code": 200, "status": "yellow", "payload": { "id": "1017", "index": "bts_test", "doc_type": "_all" }, "response": { "_index": "bts_test", "_type": "gene", "_id": "1017", "_version": 1, "found": true, "_source": { ... } } } """ res = self.request('/status').json() assert res['code'] == 200 assert res['response']['found'] def test_02_head(self): self.request('/status', method='HEAD')
... class TestStatus(BiothingsTestCase): def test_01_get(self): """ { "code": 200, "status": "yellow", "payload": { "id": "1017", "index": "bts_test", "doc_type": "_all" }, "response": { "_index": "bts_test", "_type": "gene", "_id": "1017", "_version": 1, "found": true, "_source": { ... } } } """ res = self.request('/status').json() assert res['code'] == 200 assert res['response']['found'] def test_02_head(self): ...
304b71823aac62adcbf938c23b823f7d0fd369f1
samples/Qt/basic/mythread.h
samples/Qt/basic/mythread.h
class MyThread : public QThread { Q_OBJECT public: MyThread(int id) : threadId(id) {} private: int threadId; protected: void run() { LINFO <<"Writing from a thread " << threadId; LVERBOSE(2) << "This is verbose level 2 logging from thread #" << threadId; // Following line will be logged only once from second running thread (which every runs second into // this line because of interval 2) LWARNING_EVERY_N(2) << "This will be logged only once from thread who every reaches this line first. Currently running from thread #" << threadId; for (int i = 1; i <= 10; ++i) { LVERBOSE_EVERY_N(2, 3) << "Verbose level 3 log every two times. This is at " << i << " from thread #" << threadId; } // Following line will be logged once with every thread because of interval 1 LINFO_EVERY_N(1) << "This interval log will be logged with every thread, this one is from thread #" << threadId; LINFO_IF(threadId == 2) << "This log is only for thread 2 and is ran by thread #" << threadId; std::vector<std::string> myLoggers; easyloggingpp::Loggers::getAllLogIdentifiers(myLoggers); for (unsigned int i = 0; i < myLoggers.size(); ++i) { std::cout << "Logger ID [" << myLoggers.at(i) << "]"; } easyloggingpp::Configurations c; c.parseFromText("*ALL:\n\nFORMAT = %level"); } }; #endif
class MyThread : public QThread { Q_OBJECT public: MyThread(int id) : threadId(id) {} private: int threadId; protected: void run() { LINFO <<"Writing from a thread " << threadId; LVERBOSE(2) << "This is verbose level 2 logging from thread #" << threadId; // Following line will be logged only once from second running thread (which every runs second into // this line because of interval 2) LWARNING_EVERY_N(2) << "This will be logged only once from thread who every reaches this line first. Currently running from thread #" << threadId; for (int i = 1; i <= 10; ++i) { LVERBOSE_EVERY_N(2, 3) << "Verbose level 3 log every two times. This is at " << i << " from thread #" << threadId; } // Following line will be logged once with every thread because of interval 1 LINFO_EVERY_N(1) << "This interval log will be logged with every thread, this one is from thread #" << threadId; LINFO_IF(threadId == 2) << "This log is only for thread 2 and is ran by thread #" << threadId; } }; #endif
Remove logger ids loop from sample
Remove logger ids loop from sample
C
mit
spqr33/easyloggingpp,lisong521/easyloggingpp,blankme/easyloggingpp,lisong521/easyloggingpp,blankme/easyloggingpp,arvidsson/easyloggingpp,simonhang/easyloggingpp,chenmusun/easyloggingpp,utiasASRL/easyloggingpp,dreal-deps/easyloggingpp,blankme/easyloggingpp,lisong521/easyloggingpp,chenmusun/easyloggingpp,simonhang/easyloggingpp,hellowshinobu/easyloggingpp,hellowshinobu/easyloggingpp,arvidsson/easyloggingpp,utiasASRL/easyloggingpp,dreal-deps/easyloggingpp,arvidsson/easyloggingpp,chenmusun/easyloggingpp,spthaolt/easyloggingpp,spqr33/easyloggingpp,simonhang/easyloggingpp,hellowshinobu/easyloggingpp,utiasASRL/easyloggingpp,spthaolt/easyloggingpp,spqr33/easyloggingpp,dreal-deps/easyloggingpp,spthaolt/easyloggingpp
c
## Code Before: class MyThread : public QThread { Q_OBJECT public: MyThread(int id) : threadId(id) {} private: int threadId; protected: void run() { LINFO <<"Writing from a thread " << threadId; LVERBOSE(2) << "This is verbose level 2 logging from thread #" << threadId; // Following line will be logged only once from second running thread (which every runs second into // this line because of interval 2) LWARNING_EVERY_N(2) << "This will be logged only once from thread who every reaches this line first. Currently running from thread #" << threadId; for (int i = 1; i <= 10; ++i) { LVERBOSE_EVERY_N(2, 3) << "Verbose level 3 log every two times. This is at " << i << " from thread #" << threadId; } // Following line will be logged once with every thread because of interval 1 LINFO_EVERY_N(1) << "This interval log will be logged with every thread, this one is from thread #" << threadId; LINFO_IF(threadId == 2) << "This log is only for thread 2 and is ran by thread #" << threadId; std::vector<std::string> myLoggers; easyloggingpp::Loggers::getAllLogIdentifiers(myLoggers); for (unsigned int i = 0; i < myLoggers.size(); ++i) { std::cout << "Logger ID [" << myLoggers.at(i) << "]"; } easyloggingpp::Configurations c; c.parseFromText("*ALL:\n\nFORMAT = %level"); } }; #endif ## Instruction: Remove logger ids loop from sample ## Code After: class MyThread : public QThread { Q_OBJECT public: MyThread(int id) : threadId(id) {} private: int threadId; protected: void run() { LINFO <<"Writing from a thread " << threadId; LVERBOSE(2) << "This is verbose level 2 logging from thread #" << threadId; // Following line will be logged only once from second running thread (which every runs second into // this line because of interval 2) LWARNING_EVERY_N(2) << "This will be logged only once from thread who every reaches this line first. Currently running from thread #" << threadId; for (int i = 1; i <= 10; ++i) { LVERBOSE_EVERY_N(2, 3) << "Verbose level 3 log every two times. This is at " << i << " from thread #" << threadId; } // Following line will be logged once with every thread because of interval 1 LINFO_EVERY_N(1) << "This interval log will be logged with every thread, this one is from thread #" << threadId; LINFO_IF(threadId == 2) << "This log is only for thread 2 and is ran by thread #" << threadId; } }; #endif
# ... existing code ... LINFO_IF(threadId == 2) << "This log is only for thread 2 and is ran by thread #" << threadId; } }; #endif # ... rest of the code ...
586f4068f33412e437d409b90e26a01dc834a43f
integration-tests/gradle/src/test/java/io/quarkus/gradle/devmode/MultiModuleKotlinProjectDevModeTest.java
integration-tests/gradle/src/test/java/io/quarkus/gradle/devmode/MultiModuleKotlinProjectDevModeTest.java
package io.quarkus.gradle.devmode; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; @org.junit.jupiter.api.Tag("failsOnJDK18") public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase { @Override protected String projectDirectoryName() { return "multi-module-kotlin-project"; } @Override protected String[] buildArguments() { return new String[] { "clean", ":web:quarkusDev", "-s" }; } protected void testDevMode() throws Exception { assertThat(getHttpResponse()) .contains("ready") .contains("quarkusmm") .contains("org.acme") .contains("1.0.0-SNAPSHOT"); assertThat(getHttpResponse("/hello")).contains("howdy"); replace("domain/src/main/kotlin/com/example/quarkusmm/domain/CustomerServiceImpl.kt", ImmutableMap.of("return \"howdy\"", "return \"modified\"")); assertUpdatedResponseContains("/hello", "modified"); } }
package io.quarkus.gradle.devmode; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Disabled; import com.google.common.collect.ImmutableMap; @Disabled @org.junit.jupiter.api.Tag("failsOnJDK18") public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase { @Override protected String projectDirectoryName() { return "multi-module-kotlin-project"; } @Override protected String[] buildArguments() { return new String[] { "clean", ":web:quarkusDev", "-s" }; } protected void testDevMode() throws Exception { assertThat(getHttpResponse()) .contains("ready") .contains("quarkusmm") .contains("org.acme") .contains("1.0.0-SNAPSHOT"); assertThat(getHttpResponse("/hello")).contains("howdy"); replace("domain/src/main/kotlin/com/example/quarkusmm/domain/CustomerServiceImpl.kt", ImmutableMap.of("return \"howdy\"", "return \"modified\"")); assertUpdatedResponseContains("/hello", "modified"); } }
Disable failing kotlin-multi-module gradle test
Disable failing kotlin-multi-module gradle test
Java
apache-2.0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
java
## Code Before: package io.quarkus.gradle.devmode; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; @org.junit.jupiter.api.Tag("failsOnJDK18") public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase { @Override protected String projectDirectoryName() { return "multi-module-kotlin-project"; } @Override protected String[] buildArguments() { return new String[] { "clean", ":web:quarkusDev", "-s" }; } protected void testDevMode() throws Exception { assertThat(getHttpResponse()) .contains("ready") .contains("quarkusmm") .contains("org.acme") .contains("1.0.0-SNAPSHOT"); assertThat(getHttpResponse("/hello")).contains("howdy"); replace("domain/src/main/kotlin/com/example/quarkusmm/domain/CustomerServiceImpl.kt", ImmutableMap.of("return \"howdy\"", "return \"modified\"")); assertUpdatedResponseContains("/hello", "modified"); } } ## Instruction: Disable failing kotlin-multi-module gradle test ## Code After: package io.quarkus.gradle.devmode; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Disabled; import com.google.common.collect.ImmutableMap; @Disabled @org.junit.jupiter.api.Tag("failsOnJDK18") public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase { @Override protected String projectDirectoryName() { return "multi-module-kotlin-project"; } @Override protected String[] buildArguments() { return new String[] { "clean", ":web:quarkusDev", "-s" }; } protected void testDevMode() throws Exception { assertThat(getHttpResponse()) .contains("ready") .contains("quarkusmm") .contains("org.acme") .contains("1.0.0-SNAPSHOT"); assertThat(getHttpResponse("/hello")).contains("howdy"); replace("domain/src/main/kotlin/com/example/quarkusmm/domain/CustomerServiceImpl.kt", ImmutableMap.of("return \"howdy\"", "return \"modified\"")); assertUpdatedResponseContains("/hello", "modified"); } }
... import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Disabled; import com.google.common.collect.ImmutableMap; @Disabled @org.junit.jupiter.api.Tag("failsOnJDK18") public class MultiModuleKotlinProjectDevModeTest extends QuarkusDevGradleTestBase { ...
1298e872d2dd203155399fa8c9f4398d88086f12
server/src/test/java/keywhiz/service/resources/StatusResponseTest.java
server/src/test/java/keywhiz/service/resources/StatusResponseTest.java
package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); status.get(); } @Test(expected = InternalServerErrorException.class) public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); status.get(); } }
package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(200); } @Test public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(500); } }
Fix tests to check status code, and not expect exception
Fix tests to check status code, and not expect exception
Java
apache-2.0
square/keywhiz,mcpherrinm/keywhiz,madtrax/keywhiz,madtrax/keywhiz,madtrax/keywhiz,mcpherrinm/keywhiz,mcpherrinm/keywhiz,madtrax/keywhiz,mcpherrinm/keywhiz,square/keywhiz,square/keywhiz
java
## Code Before: package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); status.get(); } @Test(expected = InternalServerErrorException.class) public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); status.get(); } } ## Instruction: Fix tests to check status code, and not expect exception ## Code After: package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(200); } @Test public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(500); } }
// ... existing code ... import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; // ... modified code ... @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(200); } @Test public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(500); } } // ... rest of the code ...
c2cb2ba803ce335eb5fabd972901e90f0c6933b1
app/src/androidTest/kotlin/com/felipecosta/kotlinrxjavasample/di/TestApplicationModule.kt
app/src/androidTest/kotlin/com/felipecosta/kotlinrxjavasample/di/TestApplicationModule.kt
package com.felipecosta.kotlinrxjavasample.di import android.content.Context import android.support.test.InstrumentationRegistry import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class TestApplicationModule { @Singleton @Provides fun providesApplicationContext(): Context = InstrumentationRegistry.getContext().applicationContext }
package com.felipecosta.kotlinrxjavasample.di import android.content.Context import android.support.test.InstrumentationRegistry import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class TestApplicationModule { @Singleton @Provides fun providesApplicationContext(): Context = InstrumentationRegistry.getTargetContext() }
Use the target context in the instrumentation test module
Use the target context in the instrumentation test module
Kotlin
mit
fcostaa/kotlin-rxjava-android,fcostaa/kotlin-rxjava-android
kotlin
## Code Before: package com.felipecosta.kotlinrxjavasample.di import android.content.Context import android.support.test.InstrumentationRegistry import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class TestApplicationModule { @Singleton @Provides fun providesApplicationContext(): Context = InstrumentationRegistry.getContext().applicationContext } ## Instruction: Use the target context in the instrumentation test module ## Code After: package com.felipecosta.kotlinrxjavasample.di import android.content.Context import android.support.test.InstrumentationRegistry import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class TestApplicationModule { @Singleton @Provides fun providesApplicationContext(): Context = InstrumentationRegistry.getTargetContext() }
// ... existing code ... @Singleton @Provides fun providesApplicationContext(): Context = InstrumentationRegistry.getTargetContext() } // ... rest of the code ...
89bb97870875329f6ddbbd6547ac6a6ddf9af0ca
buildSrc/src/main/java/dependencies/Versions.kt
buildSrc/src/main/java/dependencies/Versions.kt
package dependencies object Versions { const val versionName = "2.6.0" const val targetSdk = 28 const val minSdk = 9 const val minSdkWithSupportLibrary = 14 internal const val kotlin = "1.2.71" internal const val junit = "4.12" internal const val robolectric = "3.8" internal const val assertj = "3.11.1" internal const val gson = "2.8.5" internal const val liveData = "2.0.0" internal const val androidGradlePlugin = "3.2.1" internal const val bintrayGradlePlugin = "1.8.4" internal const val androidMavenGradlePlugin = "2.1" internal const val dokkaAndroidGradlePlugin = "0.9.17" internal const val jacoco = "0.8.2" internal const val mockito = "2.23.0" internal const val mockitoKotlin = "1.6.0" internal object AndroidX { internal const val appCompat = "1.0.0" internal const val preference = "1.0.0" } }
package dependencies object Versions { const val versionName = "2.6.0" const val targetSdk = 28 const val minSdk = 9 const val minSdkWithSupportLibrary = 14 internal const val kotlin = "1.3.10" internal const val junit = "4.12" internal const val robolectric = "3.8" internal const val assertj = "3.11.1" internal const val gson = "2.8.5" internal const val liveData = "2.0.0" internal const val androidGradlePlugin = "3.3.0-beta04" internal const val bintrayGradlePlugin = "1.8.4" internal const val androidMavenGradlePlugin = "2.1" internal const val dokkaAndroidGradlePlugin = "0.9.17" internal const val jacoco = "0.8.2" internal const val mockito = "2.23.0" internal const val mockitoKotlin = "1.6.0" internal object AndroidX { internal const val appCompat = "1.0.0" internal const val preference = "1.0.0" } }
Update kotlin and gradle plugin
Update kotlin and gradle plugin
Kotlin
apache-2.0
chibatching/Kotpref
kotlin
## Code Before: package dependencies object Versions { const val versionName = "2.6.0" const val targetSdk = 28 const val minSdk = 9 const val minSdkWithSupportLibrary = 14 internal const val kotlin = "1.2.71" internal const val junit = "4.12" internal const val robolectric = "3.8" internal const val assertj = "3.11.1" internal const val gson = "2.8.5" internal const val liveData = "2.0.0" internal const val androidGradlePlugin = "3.2.1" internal const val bintrayGradlePlugin = "1.8.4" internal const val androidMavenGradlePlugin = "2.1" internal const val dokkaAndroidGradlePlugin = "0.9.17" internal const val jacoco = "0.8.2" internal const val mockito = "2.23.0" internal const val mockitoKotlin = "1.6.0" internal object AndroidX { internal const val appCompat = "1.0.0" internal const val preference = "1.0.0" } } ## Instruction: Update kotlin and gradle plugin ## Code After: package dependencies object Versions { const val versionName = "2.6.0" const val targetSdk = 28 const val minSdk = 9 const val minSdkWithSupportLibrary = 14 internal const val kotlin = "1.3.10" internal const val junit = "4.12" internal const val robolectric = "3.8" internal const val assertj = "3.11.1" internal const val gson = "2.8.5" internal const val liveData = "2.0.0" internal const val androidGradlePlugin = "3.3.0-beta04" internal const val bintrayGradlePlugin = "1.8.4" internal const val androidMavenGradlePlugin = "2.1" internal const val dokkaAndroidGradlePlugin = "0.9.17" internal const val jacoco = "0.8.2" internal const val mockito = "2.23.0" internal const val mockitoKotlin = "1.6.0" internal object AndroidX { internal const val appCompat = "1.0.0" internal const val preference = "1.0.0" } }
# ... existing code ... const val minSdk = 9 const val minSdkWithSupportLibrary = 14 internal const val kotlin = "1.3.10" internal const val junit = "4.12" internal const val robolectric = "3.8" internal const val assertj = "3.11.1" # ... modified code ... internal const val gson = "2.8.5" internal const val liveData = "2.0.0" internal const val androidGradlePlugin = "3.3.0-beta04" internal const val bintrayGradlePlugin = "1.8.4" internal const val androidMavenGradlePlugin = "2.1" internal const val dokkaAndroidGradlePlugin = "0.9.17" # ... rest of the code ...
47db2f3170c843339b9f3ef65965b4e14cff2cf8
org.tigris.subversion.subclipse.core/src/org/tigris/subversion/subclipse/core/ISVNCoreConstants.java
org.tigris.subversion.subclipse.core/src/org/tigris/subversion/subclipse/core/ISVNCoreConstants.java
/******************************************************************************* * Copyright (c) 2004, 2006 Subclipse project and others. * 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: * Subclipse project committers - initial API and implementation ******************************************************************************/ package org.tigris.subversion.subclipse.core; /** * @author Brock Janiczak */ public interface ISVNCoreConstants { String PREF_RECURSIVE_STATUS_UPDATE = "resursive_status_update"; String PREF_SHOW_OUT_OF_DATE_FOLDERS = "show_out_of_date_folders"; String PREF_SHARE_NESTED_PROJECTS = "share_nested_projects"; public final int DEPTH_EMPTY = 0; public final int DEPTH_FILES = 1; public final int DEPTH_IMMEDIATES = 2; public final int DEPTH_INFINITY = 3; public final int DEPTH_UNKNOWN = -2; public final int DEPTH_EXCLUDE = -1; }
/******************************************************************************* * Copyright (c) 2004, 2006 Subclipse project and others. * 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: * Subclipse project committers - initial API and implementation ******************************************************************************/ package org.tigris.subversion.subclipse.core; /** * @author Brock Janiczak */ public interface ISVNCoreConstants { String PREF_RECURSIVE_STATUS_UPDATE = "resursive_status_update"; String PREF_SHOW_OUT_OF_DATE_FOLDERS = "show_out_of_date_folders"; String PREF_SHARE_NESTED_PROJECTS = "share_nested_projects"; public final int DEPTH_UNKNOWN = 0; public final int DEPTH_EXCLUDE = 1; public final int DEPTH_EMPTY = 2; public final int DEPTH_FILES = 3; public final int DEPTH_IMMEDIATES = 4; public final int DEPTH_INFINITY = 5; }
Update the Depth constants to match the changes in client adapter and JavaHL
Update the Depth constants to match the changes in client adapter and JavaHL
Java
epl-1.0
subclipse/subclipse,subclipse/subclipse,subclipse/subclipse
java
## Code Before: /******************************************************************************* * Copyright (c) 2004, 2006 Subclipse project and others. * 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: * Subclipse project committers - initial API and implementation ******************************************************************************/ package org.tigris.subversion.subclipse.core; /** * @author Brock Janiczak */ public interface ISVNCoreConstants { String PREF_RECURSIVE_STATUS_UPDATE = "resursive_status_update"; String PREF_SHOW_OUT_OF_DATE_FOLDERS = "show_out_of_date_folders"; String PREF_SHARE_NESTED_PROJECTS = "share_nested_projects"; public final int DEPTH_EMPTY = 0; public final int DEPTH_FILES = 1; public final int DEPTH_IMMEDIATES = 2; public final int DEPTH_INFINITY = 3; public final int DEPTH_UNKNOWN = -2; public final int DEPTH_EXCLUDE = -1; } ## Instruction: Update the Depth constants to match the changes in client adapter and JavaHL ## Code After: /******************************************************************************* * Copyright (c) 2004, 2006 Subclipse project and others. * 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: * Subclipse project committers - initial API and implementation ******************************************************************************/ package org.tigris.subversion.subclipse.core; /** * @author Brock Janiczak */ public interface ISVNCoreConstants { String PREF_RECURSIVE_STATUS_UPDATE = "resursive_status_update"; String PREF_SHOW_OUT_OF_DATE_FOLDERS = "show_out_of_date_folders"; String PREF_SHARE_NESTED_PROJECTS = "share_nested_projects"; public final int DEPTH_UNKNOWN = 0; public final int DEPTH_EXCLUDE = 1; public final int DEPTH_EMPTY = 2; public final int DEPTH_FILES = 3; public final int DEPTH_IMMEDIATES = 4; public final int DEPTH_INFINITY = 5; }
// ... existing code ... String PREF_SHOW_OUT_OF_DATE_FOLDERS = "show_out_of_date_folders"; String PREF_SHARE_NESTED_PROJECTS = "share_nested_projects"; public final int DEPTH_UNKNOWN = 0; public final int DEPTH_EXCLUDE = 1; public final int DEPTH_EMPTY = 2; public final int DEPTH_FILES = 3; public final int DEPTH_IMMEDIATES = 4; public final int DEPTH_INFINITY = 5; } // ... rest of the code ...
3427b2583c38ed7ec5239c36faa82536f3f95a3b
automata/pda/stack.py
automata/pda/stack.py
"""Classes and methods for working with PDA stacks.""" class PDAStack(object): """A PDA stack.""" def __init__(self, stack, **kwargs): """Initialize the new PDA stack.""" if isinstance(stack, PDAStack): self._init_from_stack_obj(stack) else: self.stack = list(stack) def _init_from_stack_obj(self, stack_obj): """Initialize this Stack as a deep copy of the given Stack.""" self.__init__(stack_obj.stack) def top(self): """Return the symbol at the top of the stack.""" if self.stack: return self.stack[-1] else: return '' def pop(self): """Pop the stack top from the stack.""" self.stack.pop() def replace(self, symbols): """ Replace the top of the stack with the given symbols. The first symbol in the given sequence becomes the new stack top. """ self.stack.pop() self.stack.extend(reversed(symbols)) def copy(self): """Return a deep copy of the stack.""" return self.__class__(self) def __len__(self): """Return the number of symbols on the stack.""" return len(self.stack) def __iter__(self): """Return an interator for the stack.""" return iter(self.stack) def __repr__(self): """Return a string representation of the stack.""" return '{}({})'.format(self.__class__.__name__, self.stack) def __eq__(self, other): """Check if two stacks are equal.""" return self.__dict__ == other.__dict__
"""Classes and methods for working with PDA stacks.""" class PDAStack(object): """A PDA stack.""" def __init__(self, stack): """Initialize the new PDA stack.""" self.stack = list(stack) def top(self): """Return the symbol at the top of the stack.""" if self.stack: return self.stack[-1] else: return '' def pop(self): """Pop the stack top from the stack.""" self.stack.pop() def replace(self, symbols): """ Replace the top of the stack with the given symbols. The first symbol in the given sequence becomes the new stack top. """ self.stack.pop() self.stack.extend(reversed(symbols)) def copy(self): """Return a deep copy of the stack.""" return self.__class__(**self.__dict__) def __len__(self): """Return the number of symbols on the stack.""" return len(self.stack) def __iter__(self): """Return an interator for the stack.""" return iter(self.stack) def __repr__(self): """Return a string representation of the stack.""" return '{}({})'.format(self.__class__.__name__, self.stack) def __eq__(self, other): """Check if two stacks are equal.""" return self.__dict__ == other.__dict__
Remove copy constructor for PDAStack
Remove copy constructor for PDAStack The copy() method is already sufficient.
Python
mit
caleb531/automata
python
## Code Before: """Classes and methods for working with PDA stacks.""" class PDAStack(object): """A PDA stack.""" def __init__(self, stack, **kwargs): """Initialize the new PDA stack.""" if isinstance(stack, PDAStack): self._init_from_stack_obj(stack) else: self.stack = list(stack) def _init_from_stack_obj(self, stack_obj): """Initialize this Stack as a deep copy of the given Stack.""" self.__init__(stack_obj.stack) def top(self): """Return the symbol at the top of the stack.""" if self.stack: return self.stack[-1] else: return '' def pop(self): """Pop the stack top from the stack.""" self.stack.pop() def replace(self, symbols): """ Replace the top of the stack with the given symbols. The first symbol in the given sequence becomes the new stack top. """ self.stack.pop() self.stack.extend(reversed(symbols)) def copy(self): """Return a deep copy of the stack.""" return self.__class__(self) def __len__(self): """Return the number of symbols on the stack.""" return len(self.stack) def __iter__(self): """Return an interator for the stack.""" return iter(self.stack) def __repr__(self): """Return a string representation of the stack.""" return '{}({})'.format(self.__class__.__name__, self.stack) def __eq__(self, other): """Check if two stacks are equal.""" return self.__dict__ == other.__dict__ ## Instruction: Remove copy constructor for PDAStack The copy() method is already sufficient. ## Code After: """Classes and methods for working with PDA stacks.""" class PDAStack(object): """A PDA stack.""" def __init__(self, stack): """Initialize the new PDA stack.""" self.stack = list(stack) def top(self): """Return the symbol at the top of the stack.""" if self.stack: return self.stack[-1] else: return '' def pop(self): """Pop the stack top from the stack.""" self.stack.pop() def replace(self, symbols): """ Replace the top of the stack with the given symbols. The first symbol in the given sequence becomes the new stack top. """ self.stack.pop() self.stack.extend(reversed(symbols)) def copy(self): """Return a deep copy of the stack.""" return self.__class__(**self.__dict__) def __len__(self): """Return the number of symbols on the stack.""" return len(self.stack) def __iter__(self): """Return an interator for the stack.""" return iter(self.stack) def __repr__(self): """Return a string representation of the stack.""" return '{}({})'.format(self.__class__.__name__, self.stack) def __eq__(self, other): """Check if two stacks are equal.""" return self.__dict__ == other.__dict__
# ... existing code ... class PDAStack(object): """A PDA stack.""" def __init__(self, stack): """Initialize the new PDA stack.""" self.stack = list(stack) def top(self): """Return the symbol at the top of the stack.""" # ... modified code ... def copy(self): """Return a deep copy of the stack.""" return self.__class__(**self.__dict__) def __len__(self): """Return the number of symbols on the stack.""" # ... rest of the code ...
f200d98547baef9ac2faa90d72857ffa0e64c721
IPython/nbconvert/exporters/python.py
IPython/nbconvert/exporters/python.py
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import Unicode from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class PythonExporter(TemplateExporter): """ Exports a Python code file. """ file_extension = Unicode( 'py', config=True, help="Extension of the file that should be written to disk") def _raw_mimetype_default(self): return 'application/x-python'
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import Unicode from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class PythonExporter(TemplateExporter): """ Exports a Python code file. """ file_extension = Unicode( 'py', config=True, help="Extension of the file that should be written to disk") def _raw_mimetype_default(self): return 'application/x-python' mime_type = Unicode('text/x-python', config=True, help="MIME type of the result file, for HTTP response headers." )
Add MIME types to nbconvert exporters
Add MIME types to nbconvert exporters
Python
bsd-3-clause
cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets
python
## Code Before: """Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import Unicode from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class PythonExporter(TemplateExporter): """ Exports a Python code file. """ file_extension = Unicode( 'py', config=True, help="Extension of the file that should be written to disk") def _raw_mimetype_default(self): return 'application/x-python' ## Instruction: Add MIME types to nbconvert exporters ## Code After: """Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import Unicode from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class PythonExporter(TemplateExporter): """ Exports a Python code file. """ file_extension = Unicode( 'py', config=True, help="Extension of the file that should be written to disk") def _raw_mimetype_default(self): return 'application/x-python' mime_type = Unicode('text/x-python', config=True, help="MIME type of the result file, for HTTP response headers." )
... def _raw_mimetype_default(self): return 'application/x-python' mime_type = Unicode('text/x-python', config=True, help="MIME type of the result file, for HTTP response headers." ) ...
d1628356c7981748e2446c7b43d33d21cdef7e02
geoengine_partner/geo_partner.py
geoengine_partner/geo_partner.py
from openerp.osv import fields from base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
Use absolute imports on opnerp.addons
[FIX] Use absolute imports on opnerp.addons
Python
agpl-3.0
OCA/geospatial,OCA/geospatial,OCA/geospatial
python
## Code Before: from openerp.osv import fields from base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') } ## Instruction: [FIX] Use absolute imports on opnerp.addons ## Code After: from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
# ... existing code ... from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): # ... rest of the code ...
9ec4906b5fb75cf162d0ab1624f364070c4c63ae
src/main/kotlin/com/visiolink/app/Extensions.kt
src/main/kotlin/com/visiolink/app/Extensions.kt
package com.visiolink.app import groovy.lang.Closure import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) .directory(dir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() return with(process) { waitFor(10, TimeUnit.SECONDS) inputStream.bufferedReader().readText() } } fun String.print(): String { println(this) return this } fun dateFormat(pattern: String, locale: Locale = Locale.getDefault(), block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat = SimpleDateFormat(pattern, locale).apply(block) fun <T> closure(block: () -> T) = object : Closure<T>(null) { fun doCall(vararg args: Any?): T { return block.invoke() } }
package com.visiolink.app import groovy.lang.Closure import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit internal fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) .directory(dir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() return with(process) { waitFor(10, TimeUnit.SECONDS) inputStream.bufferedReader().readText() } } internal fun String.print(): String { println(this) return this } fun dateFormat(pattern: String, locale: Locale = Locale.getDefault(), block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat = SimpleDateFormat(pattern, locale).apply(block) fun <T> closure(block: () -> T) = object : Closure<T>(null) { fun doCall(vararg args: Any?): T { return block.invoke() } }
Make String extension functions internal
Make String extension functions internal
Kotlin
apache-2.0
visiolink-android-dev/visiolink-app-plugin
kotlin
## Code Before: package com.visiolink.app import groovy.lang.Closure import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) .directory(dir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() return with(process) { waitFor(10, TimeUnit.SECONDS) inputStream.bufferedReader().readText() } } fun String.print(): String { println(this) return this } fun dateFormat(pattern: String, locale: Locale = Locale.getDefault(), block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat = SimpleDateFormat(pattern, locale).apply(block) fun <T> closure(block: () -> T) = object : Closure<T>(null) { fun doCall(vararg args: Any?): T { return block.invoke() } } ## Instruction: Make String extension functions internal ## Code After: package com.visiolink.app import groovy.lang.Closure import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit internal fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) .directory(dir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() return with(process) { waitFor(10, TimeUnit.SECONDS) inputStream.bufferedReader().readText() } } internal fun String.print(): String { println(this) return this } fun dateFormat(pattern: String, locale: Locale = Locale.getDefault(), block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat = SimpleDateFormat(pattern, locale).apply(block) fun <T> closure(block: () -> T) = object : Closure<T>(null) { fun doCall(vararg args: Any?): T { return block.invoke() } }
// ... existing code ... import java.util.* import java.util.concurrent.TimeUnit internal fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) // ... modified code ... } } internal fun String.print(): String { println(this) return this } // ... rest of the code ...
e586b8ba3bb896dabe97d65d1b564c749faa4d42
src/ocspdash/web/blueprints/ui.py
src/ocspdash/web/blueprints/ui.py
"""The OCSPdash homepage UI blueprint.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_payload() return render_template('index.html', payload=payload) # @ui.route('/submit', methods=['POST']) # def submit(): # """Show the submit view.""" # location_id = int(request.headers['authorization']) # # location = current_app.manager.get_location_by_id(location_id) # # if not location.activated: # return abort(403, f'Not activated: {location}') # # key = location.pubkey # # try: # verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) # payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) # # except nacl.exceptions.BadSignatureError as e: # return abort(403, f'Bad Signature: {e}') # # decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) # current_app.manager.insert_payload(decoded_payload) # # return '', 204
"""Blueprint for non-API endpoints in OCSPdash.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_payload() return render_template('index.html', payload=payload)
Update docstring and remove unused code from UI blueprint.
Update docstring and remove unused code from UI blueprint.
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
python
## Code Before: """The OCSPdash homepage UI blueprint.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_payload() return render_template('index.html', payload=payload) # @ui.route('/submit', methods=['POST']) # def submit(): # """Show the submit view.""" # location_id = int(request.headers['authorization']) # # location = current_app.manager.get_location_by_id(location_id) # # if not location.activated: # return abort(403, f'Not activated: {location}') # # key = location.pubkey # # try: # verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) # payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) # # except nacl.exceptions.BadSignatureError as e: # return abort(403, f'Bad Signature: {e}') # # decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) # current_app.manager.insert_payload(decoded_payload) # # return '', 204 ## Instruction: Update docstring and remove unused code from UI blueprint. ## Code After: """Blueprint for non-API endpoints in OCSPdash.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_payload() return render_template('index.html', payload=payload)
# ... existing code ... """Blueprint for non-API endpoints in OCSPdash.""" from flask import Blueprint, render_template # ... modified code ... """Show the user the home view.""" payload = manager.get_payload() return render_template('index.html', payload=payload) # ... rest of the code ...
f16add1160e5a76f94be30ea54cea27045c32705
tests/test_blacklist.py
tests/test_blacklist.py
import unittest import config from .. import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == "204" def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == "204" def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == "204" def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == "204" def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_show_items(self): response = self.blacklist.list() assert not response
import unittest import config import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == 204 def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == 204 def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == 204 def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == 204 def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_show_items(self): response = self.blacklist.list() assert not response
Fix unit tests for the blacklist
Fix unit tests for the blacklist
Python
apache-2.0
nToklo/ntokloapi-python
python
## Code Before: import unittest import config from .. import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == "204" def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == "204" def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == "204" def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == "204" def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_show_items(self): response = self.blacklist.list() assert not response ## Instruction: Fix unit tests for the blacklist ## Code After: import unittest import config import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == 204 def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == 204 def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == 204 def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == 204 def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_show_items(self): response = self.blacklist.list() assert not response
... import unittest import config import ntokloapi class BlacklistTest(unittest.TestCase): ... def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == 204 def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == 204 def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == 204 def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == 204 def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_show_items(self): response = self.blacklist.list() ...
1f1e1a78f56e890777ca6f88cc30be7710275aea
blackbelt/deployment.py
blackbelt/deployment.py
from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") check_call(['grunt', 'deploy'])
from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") check_call(['grunt', 'deploy']) check_call(['grunt', 'deploy', '--app=apiary-staging'])
Update deploy and stage with new environ
feat: Update deploy and stage with new environ
Python
mit
apiaryio/black-belt
python
## Code Before: from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") check_call(['grunt', 'deploy']) ## Instruction: feat: Update deploy and stage with new environ ## Code After: from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") check_call(['grunt', 'deploy']) check_call(['grunt', 'deploy', '--app=apiary-staging'])
# ... existing code ... post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") check_call(['grunt', 'deploy']) check_call(['grunt', 'deploy', '--app=apiary-staging']) # ... rest of the code ...
da6f284cf1ffa1397c32167e1e23189ea29e5b2f
IPython/html/widgets/widget_container.py
IPython/html/widgets/widget_container.py
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMWidget): _view_name = Unicode('ContainerView', sync=True) # Child widgets in the container. # Using a tuple here to force reassignment to update the list. # When a proper notifying-list trait exists, that is what should be used here. children = Tuple(sync=True) def __init__(self, **kwargs): super(ContainerWidget, self).__init__(**kwargs) self.on_displayed(ContainerWidget._fire_children_displayed) def _fire_children_displayed(self): for child in self.children: child._handle_displayed() class PopupWidget(ContainerWidget): _view_name = Unicode('PopupView', sync=True) description = Unicode(sync=True) button_text = Unicode(sync=True)
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMWidget): _view_name = Unicode('ContainerView', sync=True) # Child widgets in the container. # Using a tuple here to force reassignment to update the list. # When a proper notifying-list trait exists, that is what should be used here. children = Tuple(sync=True) def __init__(self, children = None, **kwargs): kwargs['children'] = children super(ContainerWidget, self).__init__(**kwargs) self.on_displayed(ContainerWidget._fire_children_displayed) def _fire_children_displayed(self): for child in self.children: child._handle_displayed() class PopupWidget(ContainerWidget): _view_name = Unicode('PopupView', sync=True) description = Unicode(sync=True) button_text = Unicode(sync=True)
Make Container widgets take children as the first positional argument
Make Container widgets take children as the first positional argument This makes creating containers less cumbersome: Container([list, of, children]), rather than Container(children=[list, of, children])
Python
bsd-3-clause
ipython/ipython,ipython/ipython
python
## Code Before: # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMWidget): _view_name = Unicode('ContainerView', sync=True) # Child widgets in the container. # Using a tuple here to force reassignment to update the list. # When a proper notifying-list trait exists, that is what should be used here. children = Tuple(sync=True) def __init__(self, **kwargs): super(ContainerWidget, self).__init__(**kwargs) self.on_displayed(ContainerWidget._fire_children_displayed) def _fire_children_displayed(self): for child in self.children: child._handle_displayed() class PopupWidget(ContainerWidget): _view_name = Unicode('PopupView', sync=True) description = Unicode(sync=True) button_text = Unicode(sync=True) ## Instruction: Make Container widgets take children as the first positional argument This makes creating containers less cumbersome: Container([list, of, children]), rather than Container(children=[list, of, children]) ## Code After: # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMWidget): _view_name = Unicode('ContainerView', sync=True) # Child widgets in the container. # Using a tuple here to force reassignment to update the list. # When a proper notifying-list trait exists, that is what should be used here. children = Tuple(sync=True) def __init__(self, children = None, **kwargs): kwargs['children'] = children super(ContainerWidget, self).__init__(**kwargs) self.on_displayed(ContainerWidget._fire_children_displayed) def _fire_children_displayed(self): for child in self.children: child._handle_displayed() class PopupWidget(ContainerWidget): _view_name = Unicode('PopupView', sync=True) description = Unicode(sync=True) button_text = Unicode(sync=True)
// ... existing code ... # When a proper notifying-list trait exists, that is what should be used here. children = Tuple(sync=True) def __init__(self, children = None, **kwargs): kwargs['children'] = children super(ContainerWidget, self).__init__(**kwargs) self.on_displayed(ContainerWidget._fire_children_displayed) // ... rest of the code ...
d7df3f73b521327a6a7879d47ced1cc8c7a47a2d
tensorbayes/layers/sample.py
tensorbayes/layers/sample.py
import tensorflow as tf def GaussianSample(mean, var, scope): with tf.name_scope(scope): return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var))
import tensorflow as tf def GaussianSample(mean, var, scope): with tf.name_scope(scope): return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var)) def Duplicate(x, n_iw=1, n_mc=1, scope=None): """ Duplication function adds samples according to n_iw and n_mc. This function is specifically for importance weighting and monte carlo sampling. """ with tf.name_scope(scope): sample_shape = x._shape_as_list()[1:] y = tf.reshape(x, [1, 1, -1] + sample_shape) y = tf.tile(y, [n_iw, n_mc, 1] + [1] * len(sample_shape)) y = tf.reshape(y, [-1] + sample_shape) return y
Add importance weighting and monte carlo feature
Add importance weighting and monte carlo feature
Python
mit
RuiShu/tensorbayes
python
## Code Before: import tensorflow as tf def GaussianSample(mean, var, scope): with tf.name_scope(scope): return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var)) ## Instruction: Add importance weighting and monte carlo feature ## Code After: import tensorflow as tf def GaussianSample(mean, var, scope): with tf.name_scope(scope): return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var)) def Duplicate(x, n_iw=1, n_mc=1, scope=None): """ Duplication function adds samples according to n_iw and n_mc. This function is specifically for importance weighting and monte carlo sampling. """ with tf.name_scope(scope): sample_shape = x._shape_as_list()[1:] y = tf.reshape(x, [1, 1, -1] + sample_shape) y = tf.tile(y, [n_iw, n_mc, 1] + [1] * len(sample_shape)) y = tf.reshape(y, [-1] + sample_shape) return y
# ... existing code ... def GaussianSample(mean, var, scope): with tf.name_scope(scope): return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var)) def Duplicate(x, n_iw=1, n_mc=1, scope=None): """ Duplication function adds samples according to n_iw and n_mc. This function is specifically for importance weighting and monte carlo sampling. """ with tf.name_scope(scope): sample_shape = x._shape_as_list()[1:] y = tf.reshape(x, [1, 1, -1] + sample_shape) y = tf.tile(y, [n_iw, n_mc, 1] + [1] * len(sample_shape)) y = tf.reshape(y, [-1] + sample_shape) return y # ... rest of the code ...
0cccd467ac4c0bd8b8110fcfe47f81d73a238aa9
plugins/uptime.py
plugins/uptime.py
import time class Plugin: def __init__(self, vk_bot): self.vk_bot = vk_bot self.vk_bot.add_command('uptime', self.uptime) async def uptime(self, vk_api, sender, message): await self.vk_bot.send_message(sender, 'Total uptime: {} seconds'.format(round(time.time() - self.vk_bot.start_time)))
import time class Plugin: def __init__(self, vk_bot): self.vk_bot = vk_bot self.vk_bot.add_command('uptime', self.uptime) async def uptime(self, vk_api, sender, message): await self.vk_bot.send_message(sender, 'Total uptime: {} seconds'.format(round(time.time() - self.vk_bot.start_time)))
Fix code string length (PEP8)
Fix code string length (PEP8)
Python
mit
roman901/vk_bot
python
## Code Before: import time class Plugin: def __init__(self, vk_bot): self.vk_bot = vk_bot self.vk_bot.add_command('uptime', self.uptime) async def uptime(self, vk_api, sender, message): await self.vk_bot.send_message(sender, 'Total uptime: {} seconds'.format(round(time.time() - self.vk_bot.start_time))) ## Instruction: Fix code string length (PEP8) ## Code After: import time class Plugin: def __init__(self, vk_bot): self.vk_bot = vk_bot self.vk_bot.add_command('uptime', self.uptime) async def uptime(self, vk_api, sender, message): await self.vk_bot.send_message(sender, 'Total uptime: {} seconds'.format(round(time.time() - self.vk_bot.start_time)))
... self.vk_bot.add_command('uptime', self.uptime) async def uptime(self, vk_api, sender, message): await self.vk_bot.send_message(sender, 'Total uptime: {} seconds'.format(round(time.time() - self.vk_bot.start_time))) ...
13c2e3b942e750b9d221f8abb6c49dddf432c0ec
plugin/sharedMountPointPrimaryStorage/src/main/java/org/zstack/storage/primary/smp/BackupStorageKvmUploader.java
plugin/sharedMountPointPrimaryStorage/src/main/java/org/zstack/storage/primary/smp/BackupStorageKvmUploader.java
package org.zstack.storage.primary.smp; import org.zstack.header.core.Completion; /** * Created by xing5 on 2016/3/27. */ public abstract class BackupStorageKvmUploader { public abstract void uploadBits(String bsPath, String psPath, Completion completion); }
package org.zstack.storage.primary.smp; import org.zstack.header.core.ReturnValueCompletion; /** * Created by xing5 on 2016/3/27. */ public abstract class BackupStorageKvmUploader { // When uploading an image from 'psPath' to backup storage, the 'bsPath' // might be allocated by the backup storage and returned by the completion, // instead of being known ahead of time. public abstract void uploadBits(String bsPath, String psPath, ReturnValueCompletion<String> completion); }
Update the method signature of 'uploadBits()'
Update the method signature of 'uploadBits()' Signed-off-by: David Lee <[email protected]>
Java
apache-2.0
AlanJinTS/zstack,AlanJager/zstack,liningone/zstack,hhjuliet/zstack,MaJin1996/zstack,zsyzsyhao/zstack,Alvin-Lau/zstack,AlanJager/zstack,zstackio/zstack,MatheMatrix/zstack,camilesing/zstack,WangXijue/zstack,Alvin-Lau/zstack,zxwing/zstack-1,mingjian2049/zstack,HeathHose/zstack,HeathHose/zstack,AlanJinTS/zstack,AlanJinTS/zstack,MatheMatrix/zstack,HeathHose/zstack,hhjuliet/zstack,zstackio/zstack,zstackorg/zstack,zsyzsyhao/zstack,camilesing/zstack,zxwing/zstack-1,mingjian2049/zstack,WangXijue/zstack,camilesing/zstack,Alvin-Lau/zstack,liningone/zstack,winger007/zstack,MatheMatrix/zstack,WangXijue/zstack,zstackorg/zstack,zstackio/zstack,MaJin1996/zstack,mingjian2049/zstack,zxwing/zstack-1,liningone/zstack,winger007/zstack,AlanJager/zstack
java
## Code Before: package org.zstack.storage.primary.smp; import org.zstack.header.core.Completion; /** * Created by xing5 on 2016/3/27. */ public abstract class BackupStorageKvmUploader { public abstract void uploadBits(String bsPath, String psPath, Completion completion); } ## Instruction: Update the method signature of 'uploadBits()' Signed-off-by: David Lee <[email protected]> ## Code After: package org.zstack.storage.primary.smp; import org.zstack.header.core.ReturnValueCompletion; /** * Created by xing5 on 2016/3/27. */ public abstract class BackupStorageKvmUploader { // When uploading an image from 'psPath' to backup storage, the 'bsPath' // might be allocated by the backup storage and returned by the completion, // instead of being known ahead of time. public abstract void uploadBits(String bsPath, String psPath, ReturnValueCompletion<String> completion); }
# ... existing code ... package org.zstack.storage.primary.smp; import org.zstack.header.core.ReturnValueCompletion; /** * Created by xing5 on 2016/3/27. */ public abstract class BackupStorageKvmUploader { // When uploading an image from 'psPath' to backup storage, the 'bsPath' // might be allocated by the backup storage and returned by the completion, // instead of being known ahead of time. public abstract void uploadBits(String bsPath, String psPath, ReturnValueCompletion<String> completion); } # ... rest of the code ...
48b38ea71a79eaed81a4f83a46bf8bf3db8cfa18
txircd/modules/extra/listmodules.py
txircd/modules/extra/listmodules.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ModulesCommand(ModuleData): implements(IPlugin, IModuleData) name = "ModulesCommand" def actions(self): return [ ("statsruntype-modules", 1, self.listModules) ] def listModules(self): modules = {} for modName in sorted(self.ircd.loadedModules.keys()): modules[modName] = "*" return modules modulesCommand = ModulesCommand()
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ModulesList(ModuleData): implements(IPlugin, IModuleData) name = "ModulesList" def actions(self): return [ ("statsruntype-modules", 1, self.listModules) ] def listModules(self): modules = {} for modName in sorted(self.ircd.loadedModules.keys()): modules[modName] = "*" return modules modulesList = ModulesList()
Rename ModulesCommand to be more appropriate
Rename ModulesCommand to be more appropriate
Python
bsd-3-clause
Heufneutje/txircd
python
## Code Before: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ModulesCommand(ModuleData): implements(IPlugin, IModuleData) name = "ModulesCommand" def actions(self): return [ ("statsruntype-modules", 1, self.listModules) ] def listModules(self): modules = {} for modName in sorted(self.ircd.loadedModules.keys()): modules[modName] = "*" return modules modulesCommand = ModulesCommand() ## Instruction: Rename ModulesCommand to be more appropriate ## Code After: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ModulesList(ModuleData): implements(IPlugin, IModuleData) name = "ModulesList" def actions(self): return [ ("statsruntype-modules", 1, self.listModules) ] def listModules(self): modules = {} for modName in sorted(self.ircd.loadedModules.keys()): modules[modName] = "*" return modules modulesList = ModulesList()
// ... existing code ... from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ModulesList(ModuleData): implements(IPlugin, IModuleData) name = "ModulesList" def actions(self): return [ ("statsruntype-modules", 1, self.listModules) ] // ... modified code ... modules[modName] = "*" return modules modulesList = ModulesList() // ... rest of the code ...
be67ff47938be435f1eb713ed1c9b08f3f98bc5b
number_to_words.py
number_to_words.py
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING)
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) sentence = "" if number is 0: sentence = "zero" return sentence
Add condition to handle the case when `number` is 0
Add condition to handle the case when `number` is 0
Python
mit
ianfieldhouse/number_to_words
python
## Code Before: class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) ## Instruction: Add condition to handle the case when `number` is 0 ## Code After: class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) sentence = "" if number is 0: sentence = "zero" return sentence
// ... existing code ... if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) sentence = "" if number is 0: sentence = "zero" return sentence // ... rest of the code ...
f3fa16aeee901f7ee1438bbc5b12170f82a184bc
project/api/management/commands/song_titles.py
project/api/management/commands/song_titles.py
from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.write("Sending song title report...") wb = Workbook() ws = wb.active fieldnames = [ 'title', ] ws.append(fieldnames) charts = Chart.objects.all().distinct( 'title' ).order_by( 'title' ) for chart in charts: title = chart.title.strip() row = [ title, ] ws.append(row) wb.save('song_title_report.xlsx') message = EmailMessage( subject='Song Title Report', body='Song Title Report Attached', from_email='[email protected]', to=['[email protected]', '[email protected]'] ) message.attach_file('song_title_report.xlsx') result = message.send() if result == 1: self.stdout.write("Sent.") else: self.stdout.write("Error. Not sent.")
from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.write("Sending song title report...") wb = Workbook() ws = wb.active fieldnames = [ 'title', ] ws.append(fieldnames) charts = Chart.objects.all().distinct( 'title' ).order_by( 'title' ) for chart in charts: title = chart.title.strip() row = [ title, ] ws.append(row) wb.save('song_title_report.xlsx') message = EmailMessage( subject='Song Title Report', body='Song Title Report Attached', from_email='[email protected]', to=['[email protected]', ] ) message.attach_file('song_title_report.xlsx') result = message.send() if result == 1: self.stdout.write("Sent.") else: self.stdout.write("Error. Not sent.")
Remove me from song title report send
Remove me from song title report send
Python
bsd-2-clause
dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api
python
## Code Before: from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.write("Sending song title report...") wb = Workbook() ws = wb.active fieldnames = [ 'title', ] ws.append(fieldnames) charts = Chart.objects.all().distinct( 'title' ).order_by( 'title' ) for chart in charts: title = chart.title.strip() row = [ title, ] ws.append(row) wb.save('song_title_report.xlsx') message = EmailMessage( subject='Song Title Report', body='Song Title Report Attached', from_email='[email protected]', to=['[email protected]', '[email protected]'] ) message.attach_file('song_title_report.xlsx') result = message.send() if result == 1: self.stdout.write("Sent.") else: self.stdout.write("Error. Not sent.") ## Instruction: Remove me from song title report send ## Code After: from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from openpyxl import Workbook # First-Party from api.models import Chart class Command(BaseCommand): help = "Command to sync database with BHS ." def handle(self, *args, **options): self.stdout.write("Sending song title report...") wb = Workbook() ws = wb.active fieldnames = [ 'title', ] ws.append(fieldnames) charts = Chart.objects.all().distinct( 'title' ).order_by( 'title' ) for chart in charts: title = chart.title.strip() row = [ title, ] ws.append(row) wb.save('song_title_report.xlsx') message = EmailMessage( subject='Song Title Report', body='Song Title Report Attached', from_email='[email protected]', to=['[email protected]', ] ) message.attach_file('song_title_report.xlsx') result = message.send() if result == 1: self.stdout.write("Sent.") else: self.stdout.write("Error. Not sent.")
... subject='Song Title Report', body='Song Title Report Attached', from_email='[email protected]', to=['[email protected]', ] ) message.attach_file('song_title_report.xlsx') result = message.send() ...
d39a5652fcf904abc26ef2d7165df6d9ecfc68d8
chapter5/Game.h
chapter5/Game.h
class Game { public: static Game *getInstance() { if (!instance) { instance = new Game(); } return instance; } bool init(const char *title, int xPosition, int yPosition, int height, int width, bool fullScreen); void render(); void update(); void handleEvents(); void clean(); bool isRunning() { return running; } SDL_Renderer *getRenderer() const { return renderer; } private: static Game *instance; bool running; SDL_Window *window; SDL_Renderer *renderer; GameStateMachine *gameStateMachine; std::vector<GameObject*> gameObjects; Game() {} ~Game() {} }; typedef Game TheGame; #endif
class Game { public: static Game *getInstance() { if (!instance) { instance = new Game(); } return instance; } bool init(const char *title, int xPosition, int yPosition, int height, int width, bool fullScreen); void render(); void update(); void handleEvents(); void clean(); bool isRunning() { return running; } SDL_Renderer *getRenderer() const { return renderer; } GameStateMachine* getStateMachine() { return gameStateMachine; } private: static Game *instance; bool running; SDL_Window *window; SDL_Renderer *renderer; GameStateMachine *gameStateMachine; std::vector<GameObject*> gameObjects; Game() {} ~Game() {} }; typedef Game TheGame; #endif
Include method to return pointer to object gameStateMachine
Include method to return pointer to object gameStateMachine
C
bsd-2-clause
caiotava/SDLBook
c
## Code Before: class Game { public: static Game *getInstance() { if (!instance) { instance = new Game(); } return instance; } bool init(const char *title, int xPosition, int yPosition, int height, int width, bool fullScreen); void render(); void update(); void handleEvents(); void clean(); bool isRunning() { return running; } SDL_Renderer *getRenderer() const { return renderer; } private: static Game *instance; bool running; SDL_Window *window; SDL_Renderer *renderer; GameStateMachine *gameStateMachine; std::vector<GameObject*> gameObjects; Game() {} ~Game() {} }; typedef Game TheGame; #endif ## Instruction: Include method to return pointer to object gameStateMachine ## Code After: class Game { public: static Game *getInstance() { if (!instance) { instance = new Game(); } return instance; } bool init(const char *title, int xPosition, int yPosition, int height, int width, bool fullScreen); void render(); void update(); void handleEvents(); void clean(); bool isRunning() { return running; } SDL_Renderer *getRenderer() const { return renderer; } GameStateMachine* getStateMachine() { return gameStateMachine; } private: static Game *instance; bool running; SDL_Window *window; SDL_Renderer *renderer; GameStateMachine *gameStateMachine; std::vector<GameObject*> gameObjects; Game() {} ~Game() {} }; typedef Game TheGame; #endif
... bool isRunning() { return running; } SDL_Renderer *getRenderer() const { return renderer; } GameStateMachine* getStateMachine() { return gameStateMachine; } private: static Game *instance; ...
bafe68034e3ef5e9f512bd0468001caf34981c41
include/asm-avr32/byteorder.h
include/asm-avr32/byteorder.h
/* * AVR32 endian-conversion functions. */ #ifndef __ASM_AVR32_BYTEORDER_H #define __ASM_AVR32_BYTEORDER_H #include <asm/types.h> #include <linux/compiler.h> #ifdef __CHECKER__ extern unsigned long __builtin_bswap_32(unsigned long x); extern unsigned short __builtin_bswap_16(unsigned short x); #endif #define __arch__swab32(x) __builtin_bswap_32(x) #define __arch__swab16(x) __builtin_bswap_16(x) #if !defined(__STRICT_ANSI__) || defined(__KERNEL__) # define __BYTEORDER_HAS_U64__ # define __SWAB_64_THRU_32__ #endif #include <linux/byteorder/big_endian.h> #endif /* __ASM_AVR32_BYTEORDER_H */
/* * AVR32 endian-conversion functions. */ #ifndef __ASM_AVR32_BYTEORDER_H #define __ASM_AVR32_BYTEORDER_H #include <asm/types.h> #include <linux/compiler.h> #ifdef __CHECKER__ extern unsigned long __builtin_bswap_32(unsigned long x); extern unsigned short __builtin_bswap_16(unsigned short x); #endif /* * avr32-linux-gcc versions earlier than 4.2 improperly sign-extends * the result. */ #if !(__GNUC__ == 4 && __GNUC_MINOR__ < 2) #define __arch__swab32(x) __builtin_bswap_32(x) #define __arch__swab16(x) __builtin_bswap_16(x) #endif #if !defined(__STRICT_ANSI__) || defined(__KERNEL__) # define __BYTEORDER_HAS_U64__ # define __SWAB_64_THRU_32__ #endif #include <linux/byteorder/big_endian.h> #endif /* __ASM_AVR32_BYTEORDER_H */
Work around byteswap bug in gcc < 4.2
avr32: Work around byteswap bug in gcc < 4.2 gcc versions earlier than 4.2 sign-extends the result of le16_to_cpu() and friends when we implement __arch__swabX() using __builtin_bswap_X(). Disable our arch-specific optimizations when those gcc versions are being used. Signed-off-by: Haavard Skinnemoen <[email protected]>
C
apache-2.0
TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,TeamVee-Kanas/android_kernel_samsung_kanas,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs
c
## Code Before: /* * AVR32 endian-conversion functions. */ #ifndef __ASM_AVR32_BYTEORDER_H #define __ASM_AVR32_BYTEORDER_H #include <asm/types.h> #include <linux/compiler.h> #ifdef __CHECKER__ extern unsigned long __builtin_bswap_32(unsigned long x); extern unsigned short __builtin_bswap_16(unsigned short x); #endif #define __arch__swab32(x) __builtin_bswap_32(x) #define __arch__swab16(x) __builtin_bswap_16(x) #if !defined(__STRICT_ANSI__) || defined(__KERNEL__) # define __BYTEORDER_HAS_U64__ # define __SWAB_64_THRU_32__ #endif #include <linux/byteorder/big_endian.h> #endif /* __ASM_AVR32_BYTEORDER_H */ ## Instruction: avr32: Work around byteswap bug in gcc < 4.2 gcc versions earlier than 4.2 sign-extends the result of le16_to_cpu() and friends when we implement __arch__swabX() using __builtin_bswap_X(). Disable our arch-specific optimizations when those gcc versions are being used. Signed-off-by: Haavard Skinnemoen <[email protected]> ## Code After: /* * AVR32 endian-conversion functions. */ #ifndef __ASM_AVR32_BYTEORDER_H #define __ASM_AVR32_BYTEORDER_H #include <asm/types.h> #include <linux/compiler.h> #ifdef __CHECKER__ extern unsigned long __builtin_bswap_32(unsigned long x); extern unsigned short __builtin_bswap_16(unsigned short x); #endif /* * avr32-linux-gcc versions earlier than 4.2 improperly sign-extends * the result. */ #if !(__GNUC__ == 4 && __GNUC_MINOR__ < 2) #define __arch__swab32(x) __builtin_bswap_32(x) #define __arch__swab16(x) __builtin_bswap_16(x) #endif #if !defined(__STRICT_ANSI__) || defined(__KERNEL__) # define __BYTEORDER_HAS_U64__ # define __SWAB_64_THRU_32__ #endif #include <linux/byteorder/big_endian.h> #endif /* __ASM_AVR32_BYTEORDER_H */
// ... existing code ... extern unsigned short __builtin_bswap_16(unsigned short x); #endif /* * avr32-linux-gcc versions earlier than 4.2 improperly sign-extends * the result. */ #if !(__GNUC__ == 4 && __GNUC_MINOR__ < 2) #define __arch__swab32(x) __builtin_bswap_32(x) #define __arch__swab16(x) __builtin_bswap_16(x) #endif #if !defined(__STRICT_ANSI__) || defined(__KERNEL__) # define __BYTEORDER_HAS_U64__ // ... rest of the code ...
9aa673593baa67d6e7fc861015041cfb6b69c6c3
bin/list_winconf.py
bin/list_winconf.py
def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': main()
def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': # HACK HACK HACK # Put Python script dir at the end, as script and module clash :-( import sys sys.path = sys.path[1:] + [sys.path[0]] main()
Fix import of common module
Fix import of common module
Python
mit
sebbrochet/ranwinconf
python
## Code Before: def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': main() ## Instruction: Fix import of common module ## Code After: def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': # HACK HACK HACK # Put Python script dir at the end, as script and module clash :-( import sys sys.path = sys.path[1:] + [sys.path[0]] main()
// ... existing code ... if __name__ == '__main__': # HACK HACK HACK # Put Python script dir at the end, as script and module clash :-( import sys sys.path = sys.path[1:] + [sys.path[0]] main() // ... rest of the code ...
a6d0f99e13f60f3033ed9e8f27c9ee481190258f
STS/wlogs/src/main/java/io/khasang/wlogs/controller/AppController.java
STS/wlogs/src/main/java/io/khasang/wlogs/controller/AppController.java
package io.khasang.wlogs.controller; import io.khasang.wlogs.model.InsertDataTable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to our best wLogs!"); model.addAttribute("tagline", "The one and only amazing logs system!"); return "welcome"; } @RequestMapping("/backup") public String backup(Model model) { model.addAttribute("backup", "Success"); return "backup"; } @RequestMapping("/admin") public String admin(Model model) { model.addAttribute("admin", "You are number 1!"); return "admin"; } @RequestMapping("/createtable") public String crateTable(Model model) { InsertDataTable sql = new InsertDataTable(); model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } }
package io.khasang.wlogs.controller; import io.khasang.wlogs.model.InsertDataTable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to our best wLogs!"); model.addAttribute("tagline", "The one and only amazing logs system!"); return "welcome"; } @RequestMapping("/backup") public String backup(Model model) { model.addAttribute("backup", "Success"); return "backup"; } @RequestMapping("/admin") public String admin(Model model) { model.addAttribute("admin", "You are number 1!"); return "admin"; } @RequestMapping("/createtable") public String crateTable(Model model) { InsertDataTable sql = new InsertDataTable(); model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } @RequestMapping("/mainmenu") public String mainMenu(Model model) { return "mainmenu"; } }
Add menu jsp and controller function
Add menu jsp and controller function
Java
mit
khasang-incubator/JavaWeb20160124-Team1,khasang-incubator/JavaWeb20160124-Team1,khasang-incubator/JavaWeb20160124-Team1
java
## Code Before: package io.khasang.wlogs.controller; import io.khasang.wlogs.model.InsertDataTable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to our best wLogs!"); model.addAttribute("tagline", "The one and only amazing logs system!"); return "welcome"; } @RequestMapping("/backup") public String backup(Model model) { model.addAttribute("backup", "Success"); return "backup"; } @RequestMapping("/admin") public String admin(Model model) { model.addAttribute("admin", "You are number 1!"); return "admin"; } @RequestMapping("/createtable") public String crateTable(Model model) { InsertDataTable sql = new InsertDataTable(); model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } } ## Instruction: Add menu jsp and controller function ## Code After: package io.khasang.wlogs.controller; import io.khasang.wlogs.model.InsertDataTable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to our best wLogs!"); model.addAttribute("tagline", "The one and only amazing logs system!"); return "welcome"; } @RequestMapping("/backup") public String backup(Model model) { model.addAttribute("backup", "Success"); return "backup"; } @RequestMapping("/admin") public String admin(Model model) { model.addAttribute("admin", "You are number 1!"); return "admin"; } @RequestMapping("/createtable") public String crateTable(Model model) { InsertDataTable sql = new InsertDataTable(); model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } @RequestMapping("/mainmenu") public String mainMenu(Model model) { return "mainmenu"; } }
# ... existing code ... model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } @RequestMapping("/mainmenu") public String mainMenu(Model model) { return "mainmenu"; } } # ... rest of the code ...
d1be7f345529594ba25ed5d0f22e544735a64404
qubs_data_centre/urls.py
qubs_data_centre/urls.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin admin.site.site_header = 'QUBS Data Centre Admin' urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ]
Add a custom admin site header.
Add a custom admin site header.
Python
apache-2.0
qubs/climate-data-api,qubs/climate-data-api,qubs/data-centre,qubs/data-centre
python
## Code Before: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ] ## Instruction: Add a custom admin site header. ## Code After: from django.conf.urls import url, include from django.contrib import admin admin.site.site_header = 'QUBS Data Centre Admin' urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^admin/', admin.site.urls), ]
... from django.conf.urls import url, include from django.contrib import admin admin.site.site_header = 'QUBS Data Centre Admin' urlpatterns = [ url(r'^api/', include('api.urls')), ...
6d54cbe4eb1e946bdc96dc4701dd6d5ab164c63e
oshino/agents/subprocess_agent.py
oshino/agents/subprocess_agent.py
import asyncio from . import Agent from asyncio.subprocess import PIPE class SubprocessAgent(Agent): @property def script(self): return self._data["script"] def is_valid(self): return "script" in self._data async def process(self, event_fn): logger = self.get_logger() proc = await asyncio.create_subprocess_shell(self.script) exitcode = await proc.wait() state = "ok" if exitcode == 0 else "failure" event_fn(service=self.prefix, state=state, metric_f=1.0, description="Exit code: {0}".format(exitcode) )
import asyncio from . import Agent from asyncio.subprocess import PIPE class SubprocessAgent(Agent): @property def script(self): return self._data["script"] def is_valid(self): return "script" in self._data async def process(self, event_fn): logger = self.get_logger() proc = await asyncio.create_subprocess_shell(self.script) exitcode = await proc.wait() state = "ok" if exitcode == 0 else "failure" event_fn(service=self.prefix + "shell", state=state, metric_f=1.0, description="Exit code: {0}".format(exitcode) )
Add postfix for subprocess metric
Add postfix for subprocess metric
Python
mit
CodersOfTheNight/oshino
python
## Code Before: import asyncio from . import Agent from asyncio.subprocess import PIPE class SubprocessAgent(Agent): @property def script(self): return self._data["script"] def is_valid(self): return "script" in self._data async def process(self, event_fn): logger = self.get_logger() proc = await asyncio.create_subprocess_shell(self.script) exitcode = await proc.wait() state = "ok" if exitcode == 0 else "failure" event_fn(service=self.prefix, state=state, metric_f=1.0, description="Exit code: {0}".format(exitcode) ) ## Instruction: Add postfix for subprocess metric ## Code After: import asyncio from . import Agent from asyncio.subprocess import PIPE class SubprocessAgent(Agent): @property def script(self): return self._data["script"] def is_valid(self): return "script" in self._data async def process(self, event_fn): logger = self.get_logger() proc = await asyncio.create_subprocess_shell(self.script) exitcode = await proc.wait() state = "ok" if exitcode == 0 else "failure" event_fn(service=self.prefix + "shell", state=state, metric_f=1.0, description="Exit code: {0}".format(exitcode) )
// ... existing code ... proc = await asyncio.create_subprocess_shell(self.script) exitcode = await proc.wait() state = "ok" if exitcode == 0 else "failure" event_fn(service=self.prefix + "shell", state=state, metric_f=1.0, description="Exit code: {0}".format(exitcode) // ... rest of the code ...
a372416f846ab3b20b97c87f43bf1827a9b60136
setup.py
setup.py
from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='[email protected]', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs)
from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='[email protected]', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
Implement PEP 246 compliant environment markers
Implement PEP 246 compliant environment markers
Python
mit
remcohaszing/python-syringe
python
## Code Before: from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='[email protected]', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs) ## Instruction: Implement PEP 246 compliant environment markers ## Code After: from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='[email protected]', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
// ... existing code ... try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: // ... modified code ... description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True) // ... rest of the code ...
8f330d4d07ed548a9cab348895124f5f5d92a6e8
dask_ndmeasure/_test_utils.py
dask_ndmeasure/_test_utils.py
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a = a[...] b = b[...] a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
Handle scalar values in _assert_eq_nan
Handle scalar values in _assert_eq_nan Add some special handling in `_assert_eq_nan` to handle having scalar values passed in. Basically ensure that everything provided is an array. This is a no-op for arrays, but converts scalars into 0-D arrays. By doing this, we are able to use the same `nan` handling code. Also convert the 0-D arrays back to scalars. This means a 0-D array will be treated as a scalar in the end. However Dask doesn't really have a way to differentiate the two. So this is fine.
Python
bsd-3-clause
dask-image/dask-ndmeasure
python
## Code Before: from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs) ## Instruction: Handle scalar values in _assert_eq_nan Add some special handling in `_assert_eq_nan` to handle having scalar values passed in. Basically ensure that everything provided is an array. This is a no-op for arrays, but converts scalars into 0-D arrays. By doing this, we are able to use the same `nan` handling code. Also convert the 0-D arrays back to scalars. This means a 0-D array will be treated as a scalar in the end. However Dask doesn't really have a way to differentiate the two. So this is fine. ## Code After: from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a = a[...] b = b[...] a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
# ... existing code ... a = a.copy() b = b.copy() a = a[...] b = b[...] a_nan = (a != a) b_nan = (b != b) # ... rest of the code ...
945e2def0a106541583907101060a234e6846d27
sources/bioformats/large_image_source_bioformats/girder_source.py
sources/bioformats/large_image_source_bioformats/girder_source.py
import cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats'
import cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats' def mayHaveAdjacentFiles(self, largeImageFile): # bioformats uses extensions to determine how to open a file, so this # needs to be set for all file formats. return True
Fix reading from hashed file names.
Fix reading from hashed file names. Bioformats expects file extensions to exist, so flag that we should always appear as actual, fully-pathed files.
Python
apache-2.0
girder/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image,DigitalSlideArchive/large_image,DigitalSlideArchive/large_image
python
## Code Before: import cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats' ## Instruction: Fix reading from hashed file names. Bioformats expects file extensions to exist, so flag that we should always appear as actual, fully-pathed files. ## Code After: import cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats' def mayHaveAdjacentFiles(self, largeImageFile): # bioformats uses extensions to determine how to open a file, so this # needs to be set for all file formats. return True
... cacheName = 'tilesource' name = 'bioformats' def mayHaveAdjacentFiles(self, largeImageFile): # bioformats uses extensions to determine how to open a file, so this # needs to be set for all file formats. return True ...
01c2b4d9b34750f69f0084b89db98bbb396aa70f
samples/android-app/src/androidMain/kotlin/com/example/splitties/preferences/ui/PreferencesBottomSheetDialogFragment.kt
samples/android-app/src/androidMain/kotlin/com/example/splitties/preferences/ui/PreferencesBottomSheetDialogFragment.kt
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package com.example.splitties.preferences.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.coroutines.launch import splitties.lifecycle.coroutines.lifecycleScope class PreferencesBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = SamplePreferencesUi(requireContext()).apply { viewLifecycleOwner.lifecycleScope.launch { run() } }.root }
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package com.example.splitties.preferences.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.coroutines.launch import splitties.lifecycle.coroutines.lifecycleScope class PreferencesBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = SamplePreferencesUi(inflater.context).apply { viewLifecycleOwner.lifecycleScope.launch { run() } }.root }
Use LayoutInflater context in DialogFragment
Use LayoutInflater context in DialogFragment
Kotlin
apache-2.0
LouisCAD/Splitties,LouisCAD/Splitties,LouisCAD/Splitties
kotlin
## Code Before: /* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package com.example.splitties.preferences.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.coroutines.launch import splitties.lifecycle.coroutines.lifecycleScope class PreferencesBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = SamplePreferencesUi(requireContext()).apply { viewLifecycleOwner.lifecycleScope.launch { run() } }.root } ## Instruction: Use LayoutInflater context in DialogFragment ## Code After: /* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package com.example.splitties.preferences.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.coroutines.launch import splitties.lifecycle.coroutines.lifecycleScope class PreferencesBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = SamplePreferencesUi(inflater.context).apply { viewLifecycleOwner.lifecycleScope.launch { run() } }.root }
... inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = SamplePreferencesUi(inflater.context).apply { viewLifecycleOwner.lifecycleScope.launch { run() } }.root } ...
3738df68d89e8eb0743378ecb89659e44cbb999d
troposphere/qldb.py
troposphere/qldb.py
from . import AWSObject from troposphere import Tags from .validators import boolean class Ledger(AWSObject): resource_type = "AWS::QLDB::Ledger" props = { 'DeletionProtection': (boolean, False), 'Name': (basestring, False), 'PermissionsMode': (basestring, True), 'Tags': (Tags, False), }
from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import boolean class Ledger(AWSObject): resource_type = "AWS::QLDB::Ledger" props = { 'DeletionProtection': (boolean, False), 'Name': (basestring, False), 'PermissionsMode': (basestring, True), 'Tags': (Tags, False), } class KinesisConfiguration(AWSProperty): props = { 'AggregationEnabled': (boolean, False), 'StreamArn': (basestring, False), } class Stream(AWSObject): resource_type = "AWS::QLDB::Stream" props = { 'ExclusiveEndTime': (basestring, False), 'InclusiveStartTime': (basestring, True), 'KinesisConfiguration': (KinesisConfiguration, True), 'LedgerName': (basestring, True), 'RoleArn': (basestring, True), 'StreamName': (basestring, True), 'Tags': (Tags, False), }
Add AWS::QLDB::Stream per 2020-07-08 update
Add AWS::QLDB::Stream per 2020-07-08 update
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
python
## Code Before: from . import AWSObject from troposphere import Tags from .validators import boolean class Ledger(AWSObject): resource_type = "AWS::QLDB::Ledger" props = { 'DeletionProtection': (boolean, False), 'Name': (basestring, False), 'PermissionsMode': (basestring, True), 'Tags': (Tags, False), } ## Instruction: Add AWS::QLDB::Stream per 2020-07-08 update ## Code After: from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import boolean class Ledger(AWSObject): resource_type = "AWS::QLDB::Ledger" props = { 'DeletionProtection': (boolean, False), 'Name': (basestring, False), 'PermissionsMode': (basestring, True), 'Tags': (Tags, False), } class KinesisConfiguration(AWSProperty): props = { 'AggregationEnabled': (boolean, False), 'StreamArn': (basestring, False), } class Stream(AWSObject): resource_type = "AWS::QLDB::Stream" props = { 'ExclusiveEndTime': (basestring, False), 'InclusiveStartTime': (basestring, True), 'KinesisConfiguration': (KinesisConfiguration, True), 'LedgerName': (basestring, True), 'RoleArn': (basestring, True), 'StreamName': (basestring, True), 'Tags': (Tags, False), }
# ... existing code ... from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import boolean # ... modified code ... 'PermissionsMode': (basestring, True), 'Tags': (Tags, False), } class KinesisConfiguration(AWSProperty): props = { 'AggregationEnabled': (boolean, False), 'StreamArn': (basestring, False), } class Stream(AWSObject): resource_type = "AWS::QLDB::Stream" props = { 'ExclusiveEndTime': (basestring, False), 'InclusiveStartTime': (basestring, True), 'KinesisConfiguration': (KinesisConfiguration, True), 'LedgerName': (basestring, True), 'RoleArn': (basestring, True), 'StreamName': (basestring, True), 'Tags': (Tags, False), } # ... rest of the code ...
a789e8bf574973259c0461b99fb9a486abed6e23
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
Fix a bug that would add updated control ip address instead of replace
Fix a bug that would add updated control ip address instead of replace
Python
apache-2.0
jcshen007/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack
python
## Code Before: from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag ## Instruction: Fix a bug that would add updated control ip address instead of replace ## Code After: from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
# ... existing code ... ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag # ... rest of the code ...
6a5ffc12a16c0795716d1a316f051541e674fd75
irrigator_pro/notifications/models.py
irrigator_pro/notifications/models.py
from django.db import models from django.contrib.auth.models import User from common.models import Audit, Comment from farms.models import CropSeason, Field ######################################################## ### NotificationsRule ### ### Connect notification info with a Field, CropSeason ######################################################## class NotificationsRule(Comment, Audit): # from Comment: comment # from Audit: cdate, cuser, mdate, muser NOTIFICATION_TYPE_VALUES = ['SMS', 'Email'] LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None'] field_list = models.ManyToManyField(Field) recipients = models.ManyToManyField(User) level = models.CharField(max_length = 15) notification_type = models.CharField(max_length = 15)
from django.db import models from django.contrib.auth.models import User from common.models import Audit, Comment from farms.models import CropSeason, Field ######################################################## ### NotificationsRule ### ### Connect notification info with a Field, CropSeason ######################################################## class NotificationsRule(Comment, Audit): # from Comment: comment # from Audit: cdate, cuser, mdate, muser NOTIFICATION_TYPE_VALUES = ['Email', 'SMS'] LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None'] field_list = models.ManyToManyField(Field) recipients = models.ManyToManyField(User) level = models.CharField(max_length = 15) notification_type = models.CharField(max_length = 15)
Change order of notification types so that email is shown first and becomes the default
Change order of notification types so that email is shown first and becomes the default
Python
mit
warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro
python
## Code Before: from django.db import models from django.contrib.auth.models import User from common.models import Audit, Comment from farms.models import CropSeason, Field ######################################################## ### NotificationsRule ### ### Connect notification info with a Field, CropSeason ######################################################## class NotificationsRule(Comment, Audit): # from Comment: comment # from Audit: cdate, cuser, mdate, muser NOTIFICATION_TYPE_VALUES = ['SMS', 'Email'] LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None'] field_list = models.ManyToManyField(Field) recipients = models.ManyToManyField(User) level = models.CharField(max_length = 15) notification_type = models.CharField(max_length = 15) ## Instruction: Change order of notification types so that email is shown first and becomes the default ## Code After: from django.db import models from django.contrib.auth.models import User from common.models import Audit, Comment from farms.models import CropSeason, Field ######################################################## ### NotificationsRule ### ### Connect notification info with a Field, CropSeason ######################################################## class NotificationsRule(Comment, Audit): # from Comment: comment # from Audit: cdate, cuser, mdate, muser NOTIFICATION_TYPE_VALUES = ['Email', 'SMS'] LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None'] field_list = models.ManyToManyField(Field) recipients = models.ManyToManyField(User) level = models.CharField(max_length = 15) notification_type = models.CharField(max_length = 15)
# ... existing code ... # from Comment: comment # from Audit: cdate, cuser, mdate, muser NOTIFICATION_TYPE_VALUES = ['Email', 'SMS'] LEVEL_CHOICES = ['Daily', 'Any Flag', 'Irrigate Today', 'None'] field_list = models.ManyToManyField(Field) # ... rest of the code ...
1f1b6757f82ef2ad384c2360f22935abbbc09531
setup.py
setup.py
from setuptools import setup setup( name='Certificator', version='0.1.0', long_description=__doc__, packages=['certificator'], include_package_data=True, zip_safe=False, setup_requires=[ 'nose>=1.0' ], tests_require=[ 'nose>=1.2.1', 'coverage==3.6', 'Flask-Testing==0.4', ], install_requires=[ 'Flask==0.10.1', 'Flask-Login==0.2.5', 'Flask-SQLAlchemy==0.16', 'Flask-Script==0.5.3', 'Flask-BrowserId==0.0.1', 'Jinja2==2.6', 'MarkupSafe==0.18', 'SQLAlchemy==0.8.1', 'Werkzeug==0.8.3', 'argparse==1.2.1', 'itsdangerous==0.22', 'requests==1.2.3', 'twill==0.9', 'wsgiref==0.1.2', ], entry_points={ 'console_scripts': [ 'certificator-server = certificator.main:main', ], } )
from setuptools import setup setup( name='Certificator', version='0.1.0', long_description=__doc__, packages=['certificator'], include_package_data=True, zip_safe=False, setup_requires=[ 'nose>=1.0' ], tests_require=[ 'nose>=1.2.1', 'coverage==3.6', 'Flask-Testing==0.4', ], install_requires=[ 'Flask==0.10.1', 'Flask-Login==0.2.5', 'Flask-SQLAlchemy==0.16', 'Flask-Script==0.5.3', 'Flask-BrowserId==0.0.2', 'Jinja2==2.7', 'MarkupSafe==0.18', 'SQLAlchemy==0.8.1', 'Werkzeug==0.8.3', 'argparse==1.2.1', 'itsdangerous==0.22', 'requests==1.2.3', 'twill==0.9', 'wsgiref==0.1.2', ], dependency_links=[ 'http://github.com/cnelsonsic/flask-browserid/tarball/fix_setup_py#egg=Flask-BrowserId-0.0.2', ], entry_points={ 'console_scripts': [ 'certificator-server = certificator.main:main', ], } )
Use my own fork of flask-browserid until it gets merged
Use my own fork of flask-browserid until it gets merged
Python
agpl-3.0
cnelsonsic/Certificator
python
## Code Before: from setuptools import setup setup( name='Certificator', version='0.1.0', long_description=__doc__, packages=['certificator'], include_package_data=True, zip_safe=False, setup_requires=[ 'nose>=1.0' ], tests_require=[ 'nose>=1.2.1', 'coverage==3.6', 'Flask-Testing==0.4', ], install_requires=[ 'Flask==0.10.1', 'Flask-Login==0.2.5', 'Flask-SQLAlchemy==0.16', 'Flask-Script==0.5.3', 'Flask-BrowserId==0.0.1', 'Jinja2==2.6', 'MarkupSafe==0.18', 'SQLAlchemy==0.8.1', 'Werkzeug==0.8.3', 'argparse==1.2.1', 'itsdangerous==0.22', 'requests==1.2.3', 'twill==0.9', 'wsgiref==0.1.2', ], entry_points={ 'console_scripts': [ 'certificator-server = certificator.main:main', ], } ) ## Instruction: Use my own fork of flask-browserid until it gets merged ## Code After: from setuptools import setup setup( name='Certificator', version='0.1.0', long_description=__doc__, packages=['certificator'], include_package_data=True, zip_safe=False, setup_requires=[ 'nose>=1.0' ], tests_require=[ 'nose>=1.2.1', 'coverage==3.6', 'Flask-Testing==0.4', ], install_requires=[ 'Flask==0.10.1', 'Flask-Login==0.2.5', 'Flask-SQLAlchemy==0.16', 'Flask-Script==0.5.3', 'Flask-BrowserId==0.0.2', 'Jinja2==2.7', 'MarkupSafe==0.18', 'SQLAlchemy==0.8.1', 'Werkzeug==0.8.3', 'argparse==1.2.1', 'itsdangerous==0.22', 'requests==1.2.3', 'twill==0.9', 'wsgiref==0.1.2', ], dependency_links=[ 'http://github.com/cnelsonsic/flask-browserid/tarball/fix_setup_py#egg=Flask-BrowserId-0.0.2', ], entry_points={ 'console_scripts': [ 'certificator-server = certificator.main:main', ], } )
// ... existing code ... 'Flask-Login==0.2.5', 'Flask-SQLAlchemy==0.16', 'Flask-Script==0.5.3', 'Flask-BrowserId==0.0.2', 'Jinja2==2.7', 'MarkupSafe==0.18', 'SQLAlchemy==0.8.1', 'Werkzeug==0.8.3', // ... modified code ... 'twill==0.9', 'wsgiref==0.1.2', ], dependency_links=[ 'http://github.com/cnelsonsic/flask-browserid/tarball/fix_setup_py#egg=Flask-BrowserId-0.0.2', ], entry_points={ 'console_scripts': [ 'certificator-server = certificator.main:main', // ... rest of the code ...
f213984ad3dfd8922578346baeeb97d60fab742a
cinje/inline/use.py
cinje/inline/use.py
from ..util import pypy, ensure_buffer PREFIX = '_buffer.extend(' if pypy else '__w(' class Use(object): """Consume the result of calling another template function, extending the local buffer. This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead. Syntax: : use <name-constant> [<arguments>] The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol. """ priority = 25 def match(self, context, line): """Match code lines prefixed with a "use" keyword.""" return line.kind == 'code' and line.partitioned[0] == "use" def __call__(self, context): """Wrap the expression in a `_buffer.extend()` call.""" input = context.input declaration = input.next() parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments. name, _, args = parts.partition(' ') for i in ensure_buffer(context): yield i yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))") context.flag.add('dirty')
from ..util import py, pypy, ensure_buffer PREFIX = '_buffer.extend(' if pypy else '__w(' class Use(object): """Consume the result of calling another template function, extending the local buffer. This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead. Syntax: : use <name-constant> [<arguments>] The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol. """ priority = 25 def match(self, context, line): """Match code lines prefixed with a "use" keyword.""" return line.kind == 'code' and line.partitioned[0] == "use" def __call__(self, context): """Wrap the expression in a `_buffer.extend()` call.""" input = context.input declaration = input.next() parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments. name, _, args = parts.partition(' ') for i in ensure_buffer(context): yield i name = name.rstrip() args = args.lstrip() if 'buffer' in context.flag: yield declaration.clone(line=PREFIX + name + "(" + args + "))") context.flag.add('dirty') return if py == 3: # We can use the more efficient "yield from" syntax. Wewt! yield declaration.clone(line="yield from " + name + "(" + args + ")") else: yield declaration.clone(line="for _chunk in " + name + "(" + args + "):") yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
Handle buffering and Python 3 "yield from" optimization.
Handle buffering and Python 3 "yield from" optimization.
Python
mit
marrow/cinje
python
## Code Before: from ..util import pypy, ensure_buffer PREFIX = '_buffer.extend(' if pypy else '__w(' class Use(object): """Consume the result of calling another template function, extending the local buffer. This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead. Syntax: : use <name-constant> [<arguments>] The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol. """ priority = 25 def match(self, context, line): """Match code lines prefixed with a "use" keyword.""" return line.kind == 'code' and line.partitioned[0] == "use" def __call__(self, context): """Wrap the expression in a `_buffer.extend()` call.""" input = context.input declaration = input.next() parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments. name, _, args = parts.partition(' ') for i in ensure_buffer(context): yield i yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))") context.flag.add('dirty') ## Instruction: Handle buffering and Python 3 "yield from" optimization. ## Code After: from ..util import py, pypy, ensure_buffer PREFIX = '_buffer.extend(' if pypy else '__w(' class Use(object): """Consume the result of calling another template function, extending the local buffer. This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead. Syntax: : use <name-constant> [<arguments>] The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol. """ priority = 25 def match(self, context, line): """Match code lines prefixed with a "use" keyword.""" return line.kind == 'code' and line.partitioned[0] == "use" def __call__(self, context): """Wrap the expression in a `_buffer.extend()` call.""" input = context.input declaration = input.next() parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments. name, _, args = parts.partition(' ') for i in ensure_buffer(context): yield i name = name.rstrip() args = args.lstrip() if 'buffer' in context.flag: yield declaration.clone(line=PREFIX + name + "(" + args + "))") context.flag.add('dirty') return if py == 3: # We can use the more efficient "yield from" syntax. Wewt! yield declaration.clone(line="yield from " + name + "(" + args + ")") else: yield declaration.clone(line="for _chunk in " + name + "(" + args + "):") yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
# ... existing code ... from ..util import py, pypy, ensure_buffer PREFIX = '_buffer.extend(' if pypy else '__w(' # ... modified code ... for i in ensure_buffer(context): yield i name = name.rstrip() args = args.lstrip() if 'buffer' in context.flag: yield declaration.clone(line=PREFIX + name + "(" + args + "))") context.flag.add('dirty') return if py == 3: # We can use the more efficient "yield from" syntax. Wewt! yield declaration.clone(line="yield from " + name + "(" + args + ")") else: yield declaration.clone(line="for _chunk in " + name + "(" + args + "):") yield declaration.clone(line="yield _chunk", scope=context.scope + 1) # ... rest of the code ...
573055a80ef19f2b743ef3bfc08c40e8738c5bb1
libtree/utils.py
libtree/utils.py
import collections from copy import deepcopy def recursive_dict_merge(left, right, first_run=True): """ Merge ``right`` into ``left`` and return a new dictionary. """ if first_run is True: left = deepcopy(left) for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): recursive_dict_merge(left[key], right[key], False) else: left[key] = right[key] else: left[key] = right[key] return left def vectorize_nodes(*nodes): if len(nodes) == 1 and isinstance(nodes[0], collections.Iterable): nodes = nodes[0] ret = [] parents = {node.parent: node for node in nodes} last_parent = None for _ in range(len(parents)): node = parents[last_parent] ret.append(node) last_parent = node.id return ret
import collections from copy import deepcopy def recursive_dict_merge(left, right, create_copy=True): """ Merge ``right`` into ``left`` and return a new dictionary. """ if create_copy is True: left = deepcopy(left) for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): recursive_dict_merge(left[key], right[key], False) else: left[key] = right[key] else: left[key] = right[key] return left def vectorize_nodes(*nodes): if len(nodes) == 1 and isinstance(nodes[0], collections.Iterable): nodes = nodes[0] ret = [] parents = {node.parent: node for node in nodes} last_parent = None for _ in range(len(parents)): node = parents[last_parent] ret.append(node) last_parent = node.id return ret
Rename 'first_run' -> 'create_copy' in recursive_dict_merge()
Rename 'first_run' -> 'create_copy' in recursive_dict_merge()
Python
mit
conceptsandtraining/libtree
python
## Code Before: import collections from copy import deepcopy def recursive_dict_merge(left, right, first_run=True): """ Merge ``right`` into ``left`` and return a new dictionary. """ if first_run is True: left = deepcopy(left) for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): recursive_dict_merge(left[key], right[key], False) else: left[key] = right[key] else: left[key] = right[key] return left def vectorize_nodes(*nodes): if len(nodes) == 1 and isinstance(nodes[0], collections.Iterable): nodes = nodes[0] ret = [] parents = {node.parent: node for node in nodes} last_parent = None for _ in range(len(parents)): node = parents[last_parent] ret.append(node) last_parent = node.id return ret ## Instruction: Rename 'first_run' -> 'create_copy' in recursive_dict_merge() ## Code After: import collections from copy import deepcopy def recursive_dict_merge(left, right, create_copy=True): """ Merge ``right`` into ``left`` and return a new dictionary. """ if create_copy is True: left = deepcopy(left) for key in right: if key in left: if isinstance(left[key], dict) and isinstance(right[key], dict): recursive_dict_merge(left[key], right[key], False) else: left[key] = right[key] else: left[key] = right[key] return left def vectorize_nodes(*nodes): if len(nodes) == 1 and isinstance(nodes[0], collections.Iterable): nodes = nodes[0] ret = [] parents = {node.parent: node for node in nodes} last_parent = None for _ in range(len(parents)): node = parents[last_parent] ret.append(node) last_parent = node.id return ret
# ... existing code ... from copy import deepcopy def recursive_dict_merge(left, right, create_copy=True): """ Merge ``right`` into ``left`` and return a new dictionary. """ if create_copy is True: left = deepcopy(left) for key in right: # ... rest of the code ...
7e11e57ee4f9fc1dc3c967c9b2d26038a7727f72
wqflask/wqflask/database.py
wqflask/wqflask/database.py
import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base def read_from_pyfile(pyfile, setting): orig_sys_path = sys.path[:] sys.path.insert(0, os.path.dirname(pyfile)) module = importlib.import_module(os.path.basename(pyfile).strip(".py")) sys.path = orig_sys_path[:] return module.__dict__.get(setting) def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
Delete unused function and imports.
Delete unused function and imports. * wqflask/wqflask/database.py: Remove unused sqlalchemy imports. (read_from_pyfile): Delete it.
Python
agpl-3.0
genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2
python
## Code Before: import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base def read_from_pyfile(pyfile, setting): orig_sys_path = sys.path[:] sys.path.insert(0, os.path.dirname(pyfile)) module = importlib.import_module(os.path.basename(pyfile).strip(".py")) sys.path = orig_sys_path[:] return module.__dict__.get(setting) def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port) ## Instruction: Delete unused function and imports. * wqflask/wqflask/database.py: Remove unused sqlalchemy imports. (read_from_pyfile): Delete it. ## Code After: import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
// ... existing code ... import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" // ... rest of the code ...
04939189efdc55164af8dc04223c7733664f091f
valohai_cli/cli_utils.py
valohai_cli/cli_utils.py
import click def prompt_from_list(options, prompt, nonlist_validator=None): for i, option in enumerate(options, 1): click.echo('{number} {name} {description}'.format( number=click.style('[%3d]' % i, fg='cyan'), name=option['name'], description=( click.style('(%s)' % option['description'], dim=True) if option.get('description') else '' ), )) while True: answer = click.prompt(prompt) if answer.isdigit() and (1 <= int(answer) <= len(options)): return options[int(answer) - 1] if nonlist_validator: retval = nonlist_validator(answer) return retval click.secho('Sorry, try again.') continue
import click def prompt_from_list(options, prompt, nonlist_validator=None): for i, option in enumerate(options, 1): click.echo('{number} {name} {description}'.format( number=click.style('[%3d]' % i, fg='cyan'), name=option['name'], description=( click.style('(%s)' % option['description'], dim=True) if option.get('description') else '' ), )) while True: answer = click.prompt(prompt) if answer.isdigit() and (1 <= int(answer) <= len(options)): return options[int(answer) - 1] if nonlist_validator: retval = nonlist_validator(answer) if retval: return retval click.secho('Sorry, try again.') continue
Fix `prompt_from_list` misbehaving with nonlist_validator
Fix `prompt_from_list` misbehaving with nonlist_validator
Python
mit
valohai/valohai-cli
python
## Code Before: import click def prompt_from_list(options, prompt, nonlist_validator=None): for i, option in enumerate(options, 1): click.echo('{number} {name} {description}'.format( number=click.style('[%3d]' % i, fg='cyan'), name=option['name'], description=( click.style('(%s)' % option['description'], dim=True) if option.get('description') else '' ), )) while True: answer = click.prompt(prompt) if answer.isdigit() and (1 <= int(answer) <= len(options)): return options[int(answer) - 1] if nonlist_validator: retval = nonlist_validator(answer) return retval click.secho('Sorry, try again.') continue ## Instruction: Fix `prompt_from_list` misbehaving with nonlist_validator ## Code After: import click def prompt_from_list(options, prompt, nonlist_validator=None): for i, option in enumerate(options, 1): click.echo('{number} {name} {description}'.format( number=click.style('[%3d]' % i, fg='cyan'), name=option['name'], description=( click.style('(%s)' % option['description'], dim=True) if option.get('description') else '' ), )) while True: answer = click.prompt(prompt) if answer.isdigit() and (1 <= int(answer) <= len(options)): return options[int(answer) - 1] if nonlist_validator: retval = nonlist_validator(answer) if retval: return retval click.secho('Sorry, try again.') continue
# ... existing code ... return options[int(answer) - 1] if nonlist_validator: retval = nonlist_validator(answer) if retval: return retval click.secho('Sorry, try again.') continue # ... rest of the code ...
45aaeef14a06f927c8ebcd31a36c97f180087a1f
include/rapidcheck/Classify.h
include/rapidcheck/Classify.h
/// Tags the current test case if the specified condition is true. If any tags /// are specified after the condition, those will be used. Otherwise, a string /// version of the condition itself will be used as the tag. #define RC_CLASSIFY(condition, ...) \ do { \ if (condition) { \ detail::classify(#condition, {__VA_ARGS__}); \ } \ } while (false) /// Tags the current test case with the given values which will be converted to /// strings. #define RC_TAG(...) detail::tag({__VA_ARGS__}) #include "Classify.hpp"
/// Tags the current test case if the specified condition is true. If any tags /// are specified after the condition, those will be used. Otherwise, a string /// version of the condition itself will be used as the tag. #define RC_CLASSIFY(condition, ...) \ do { \ if (condition) { \ ::rc::detail::classify(#condition, {__VA_ARGS__}); \ } \ } while (false) /// Tags the current test case with the given values which will be converted to /// strings. #define RC_TAG(...) ::rc::detail::tag({__VA_ARGS__}) #include "Classify.hpp"
Fix missing namespace qualification in classify macros
Fix missing namespace qualification in classify macros
C
bsd-2-clause
emil-e/rapidcheck,unapiedra/rapidfuzz,emil-e/rapidcheck,emil-e/rapidcheck,unapiedra/rapidfuzz,tm604/rapidcheck,whoshuu/rapidcheck,unapiedra/rapidfuzz,tm604/rapidcheck,whoshuu/rapidcheck,whoshuu/rapidcheck,tm604/rapidcheck
c
## Code Before: /// Tags the current test case if the specified condition is true. If any tags /// are specified after the condition, those will be used. Otherwise, a string /// version of the condition itself will be used as the tag. #define RC_CLASSIFY(condition, ...) \ do { \ if (condition) { \ detail::classify(#condition, {__VA_ARGS__}); \ } \ } while (false) /// Tags the current test case with the given values which will be converted to /// strings. #define RC_TAG(...) detail::tag({__VA_ARGS__}) #include "Classify.hpp" ## Instruction: Fix missing namespace qualification in classify macros ## Code After: /// Tags the current test case if the specified condition is true. If any tags /// are specified after the condition, those will be used. Otherwise, a string /// version of the condition itself will be used as the tag. #define RC_CLASSIFY(condition, ...) \ do { \ if (condition) { \ ::rc::detail::classify(#condition, {__VA_ARGS__}); \ } \ } while (false) /// Tags the current test case with the given values which will be converted to /// strings. #define RC_TAG(...) ::rc::detail::tag({__VA_ARGS__}) #include "Classify.hpp"
// ... existing code ... #define RC_CLASSIFY(condition, ...) \ do { \ if (condition) { \ ::rc::detail::classify(#condition, {__VA_ARGS__}); \ } \ } while (false) /// Tags the current test case with the given values which will be converted to /// strings. #define RC_TAG(...) ::rc::detail::tag({__VA_ARGS__}) #include "Classify.hpp" // ... rest of the code ...
c99883b2325dc0e78ea4aa11e37df51b4432ebb6
openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/domain/jpa/JpaOrganizationalUnitImpl_.java
openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/domain/jpa/JpaOrganizationalUnitImpl_.java
package org.openregistry.core.domain.jpa; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(JpaOrganizationalUnitImpl.class) public abstract class JpaOrganizationalUnitImpl_ { public static volatile SingularAttribute<JpaOrganizationalUnitImpl, Long> id; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaCampusImpl> campus; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaTypeImpl> organizationalUnitType; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> localCode; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> name; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaOrganizationalUnitImpl> organizationalUnit; }
package org.openregistry.core.domain.jpa; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(JpaOrganizationalUnitImpl.class) public abstract class JpaOrganizationalUnitImpl_ { public static volatile SingularAttribute<JpaOrganizationalUnitImpl, Long> id; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaCampusImpl> campus; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaTypeImpl> organizationalUnitType; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> localCode; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> name; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaOrganizationalUnitImpl> organizationalUnit; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> RBHS; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> PHI; }
Add PHI and RBHS flags to DRD_ Organizational_Units
Add PHI and RBHS flags to DRD_ Organizational_Units
Java
apache-2.0
Rutgers-IDM/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,sheliu/openregistry
java
## Code Before: package org.openregistry.core.domain.jpa; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(JpaOrganizationalUnitImpl.class) public abstract class JpaOrganizationalUnitImpl_ { public static volatile SingularAttribute<JpaOrganizationalUnitImpl, Long> id; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaCampusImpl> campus; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaTypeImpl> organizationalUnitType; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> localCode; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> name; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaOrganizationalUnitImpl> organizationalUnit; } ## Instruction: Add PHI and RBHS flags to DRD_ Organizational_Units ## Code After: package org.openregistry.core.domain.jpa; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(JpaOrganizationalUnitImpl.class) public abstract class JpaOrganizationalUnitImpl_ { public static volatile SingularAttribute<JpaOrganizationalUnitImpl, Long> id; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaCampusImpl> campus; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaTypeImpl> organizationalUnitType; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> localCode; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> name; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaOrganizationalUnitImpl> organizationalUnit; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> RBHS; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> PHI; }
# ... existing code ... public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> localCode; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> name; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, JpaOrganizationalUnitImpl> organizationalUnit; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> RBHS; public static volatile SingularAttribute<JpaOrganizationalUnitImpl, String> PHI; } # ... rest of the code ...
7f611e99d36089bc6836042ba8aec2df02a56f3a
pymemcache/test/test_serde.py
pymemcache/test/test_serde.py
from unittest import TestCase from pymemcache.serde import (python_memcache_serializer, python_memcache_deserializer) import pytest import six @pytest.mark.unit() class TestSerde(TestCase): def check(self, value): serialized, flags = python_memcache_serializer(b'key', value) # pymemcache stores values as byte strings, so we immediately the value # if needed so deserialized works as it would with a real server if not isinstance(serialized, six.binary_type): serialized = six.text_type(serialized).encode('ascii') deserialized = python_memcache_deserializer(b'key', serialized, flags) assert deserialized == value def test_bytes(self): self.check(b'value') def test_unicode(self): self.check(u'value') def test_int(self): self.check(1) def test_long(self): self.check(123123123123123123123) def test_pickleable(self): self.check({'a': 'dict'})
from unittest import TestCase from pymemcache.serde import (python_memcache_serializer, python_memcache_deserializer, FLAG_PICKLE, FLAG_INTEGER, FLAG_LONG, FLAG_TEXT) import pytest import six @pytest.mark.unit() class TestSerde(TestCase): def check(self, value, expected_flags=0): serialized, flags = python_memcache_serializer(b'key', value) assert flags == expected_flags # pymemcache stores values as byte strings, so we immediately the value # if needed so deserialized works as it would with a real server if not isinstance(serialized, six.binary_type): serialized = six.text_type(serialized).encode('ascii') deserialized = python_memcache_deserializer(b'key', serialized, flags) assert deserialized == value def test_bytes(self): self.check(b'value') def test_unicode(self): self.check(u'value', FLAG_TEXT) def test_int(self): self.check(1, FLAG_INTEGER) def test_long(self): # long only exists with Python 2, so we're just testing for another # integer with Python 3 if six.PY2: expected_flags = FLAG_LONG else: expected_flags = FLAG_INTEGER self.check(123123123123123123123, expected_flags) def test_pickleable(self): self.check({'a': 'dict'}, FLAG_PICKLE)
Test for expected flags with serde tests
Test for expected flags with serde tests
Python
apache-2.0
bwalks/pymemcache,sontek/pymemcache,pinterest/pymemcache,ewdurbin/pymemcache,pinterest/pymemcache,sontek/pymemcache
python
## Code Before: from unittest import TestCase from pymemcache.serde import (python_memcache_serializer, python_memcache_deserializer) import pytest import six @pytest.mark.unit() class TestSerde(TestCase): def check(self, value): serialized, flags = python_memcache_serializer(b'key', value) # pymemcache stores values as byte strings, so we immediately the value # if needed so deserialized works as it would with a real server if not isinstance(serialized, six.binary_type): serialized = six.text_type(serialized).encode('ascii') deserialized = python_memcache_deserializer(b'key', serialized, flags) assert deserialized == value def test_bytes(self): self.check(b'value') def test_unicode(self): self.check(u'value') def test_int(self): self.check(1) def test_long(self): self.check(123123123123123123123) def test_pickleable(self): self.check({'a': 'dict'}) ## Instruction: Test for expected flags with serde tests ## Code After: from unittest import TestCase from pymemcache.serde import (python_memcache_serializer, python_memcache_deserializer, FLAG_PICKLE, FLAG_INTEGER, FLAG_LONG, FLAG_TEXT) import pytest import six @pytest.mark.unit() class TestSerde(TestCase): def check(self, value, expected_flags=0): serialized, flags = python_memcache_serializer(b'key', value) assert flags == expected_flags # pymemcache stores values as byte strings, so we immediately the value # if needed so deserialized works as it would with a real server if not isinstance(serialized, six.binary_type): serialized = six.text_type(serialized).encode('ascii') deserialized = python_memcache_deserializer(b'key', serialized, flags) assert deserialized == value def test_bytes(self): self.check(b'value') def test_unicode(self): self.check(u'value', FLAG_TEXT) def test_int(self): self.check(1, FLAG_INTEGER) def test_long(self): # long only exists with Python 2, so we're just testing for another # integer with Python 3 if six.PY2: expected_flags = FLAG_LONG else: expected_flags = FLAG_INTEGER self.check(123123123123123123123, expected_flags) def test_pickleable(self): self.check({'a': 'dict'}, FLAG_PICKLE)
... from unittest import TestCase from pymemcache.serde import (python_memcache_serializer, python_memcache_deserializer, FLAG_PICKLE, FLAG_INTEGER, FLAG_LONG, FLAG_TEXT) import pytest import six ... @pytest.mark.unit() class TestSerde(TestCase): def check(self, value, expected_flags=0): serialized, flags = python_memcache_serializer(b'key', value) assert flags == expected_flags # pymemcache stores values as byte strings, so we immediately the value # if needed so deserialized works as it would with a real server ... self.check(b'value') def test_unicode(self): self.check(u'value', FLAG_TEXT) def test_int(self): self.check(1, FLAG_INTEGER) def test_long(self): # long only exists with Python 2, so we're just testing for another # integer with Python 3 if six.PY2: expected_flags = FLAG_LONG else: expected_flags = FLAG_INTEGER self.check(123123123123123123123, expected_flags) def test_pickleable(self): self.check({'a': 'dict'}, FLAG_PICKLE) ...
32ac109aec82210ccfa617b438a844b0f300157c
comics/core/context_processors.py
comics/core/context_processors.py
from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
Add search_enabled to site settings context processor
Add search_enabled to site settings context processor
Python
agpl-3.0
jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics
python
## Code Before: from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics} ## Instruction: Add search_enabled to site settings context processor ## Code After: from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
// ... existing code ... 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): // ... rest of the code ...
76080b428060d5fc293ff8e120d26debfec6f149
lib/Cell_Segmentation.java
lib/Cell_Segmentation.java
import ij.*; import ij.gui.*; import ij.process.*; import ij.plugin.frame.*; import ij.plugin.filter.*; import java.awt.*; public class Cell_Segmentation implements PlugInFilter { // External public ImagePlus imp; public RoiManager roiMgr; public int setup(String arg, ImagePlus imp) { this.imp = imp; // Open ROI Manager roiMgr = RoiManager.getInstance(); if (roiMgr == null) roiMgr = new RoiManager(); return DOES_ALL; } public void run(ImageProcessor ip) { // Put this line to validate ip.invert(); } }
import ij.*; import ij.gui.*; import ij.process.*; import ij.plugin.frame.*; import ij.plugin.filter.*; import java.awt.*; public class Cell_Segmentation implements PlugInFilter { // External public RoiManager roiMgr; public ImagePlus imp; public ImageProcessor ip; public int setup(String arg, ImagePlus imp) { // Open ROI Manager roiMgr = RoiManager.getInstance(); if (roiMgr == null) roiMgr = new RoiManager(); return DOES_ALL; } public void run(ImageProcessor ip) { // Create a copy in Gray8 format create_gray8_copy(ip); } public void create_gray8_copy(ImageProcessor _ip) { ip = _ip.convertToByte(true); imp = new ImagePlus("Cell Segmentation", ip); imp.show(); imp.updateAndDraw(); } }
Create a copy in Gray8 format
Create a copy in Gray8 format
Java
mit
aidistan/ij-fibersize
java
## Code Before: import ij.*; import ij.gui.*; import ij.process.*; import ij.plugin.frame.*; import ij.plugin.filter.*; import java.awt.*; public class Cell_Segmentation implements PlugInFilter { // External public ImagePlus imp; public RoiManager roiMgr; public int setup(String arg, ImagePlus imp) { this.imp = imp; // Open ROI Manager roiMgr = RoiManager.getInstance(); if (roiMgr == null) roiMgr = new RoiManager(); return DOES_ALL; } public void run(ImageProcessor ip) { // Put this line to validate ip.invert(); } } ## Instruction: Create a copy in Gray8 format ## Code After: import ij.*; import ij.gui.*; import ij.process.*; import ij.plugin.frame.*; import ij.plugin.filter.*; import java.awt.*; public class Cell_Segmentation implements PlugInFilter { // External public RoiManager roiMgr; public ImagePlus imp; public ImageProcessor ip; public int setup(String arg, ImagePlus imp) { // Open ROI Manager roiMgr = RoiManager.getInstance(); if (roiMgr == null) roiMgr = new RoiManager(); return DOES_ALL; } public void run(ImageProcessor ip) { // Create a copy in Gray8 format create_gray8_copy(ip); } public void create_gray8_copy(ImageProcessor _ip) { ip = _ip.convertToByte(true); imp = new ImagePlus("Cell Segmentation", ip); imp.show(); imp.updateAndDraw(); } }
// ... existing code ... public class Cell_Segmentation implements PlugInFilter { // External public RoiManager roiMgr; public ImagePlus imp; public ImageProcessor ip; public int setup(String arg, ImagePlus imp) { // Open ROI Manager roiMgr = RoiManager.getInstance(); if (roiMgr == null) roiMgr = new RoiManager(); return DOES_ALL; } public void run(ImageProcessor ip) { // Create a copy in Gray8 format create_gray8_copy(ip); } public void create_gray8_copy(ImageProcessor _ip) { ip = _ip.convertToByte(true); imp = new ImagePlus("Cell Segmentation", ip); imp.show(); imp.updateAndDraw(); } } // ... rest of the code ...
7674437d752be0791688533dd1409fa083672bb2
genes/java/config.py
genes/java/config.py
def config(): return { 'is-oracle': True, 'version': 'oracle-java8', }
from collections import namedtuple JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version']) def config(): return JavaConfig( is_oracle=True, version='oracle-java8', )
Switch from dictionary to namedtuple
Switch from dictionary to namedtuple
Python
mit
hatchery/Genepool2,hatchery/genepool
python
## Code Before: def config(): return { 'is-oracle': True, 'version': 'oracle-java8', } ## Instruction: Switch from dictionary to namedtuple ## Code After: from collections import namedtuple JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version']) def config(): return JavaConfig( is_oracle=True, version='oracle-java8', )
// ... existing code ... from collections import namedtuple JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version']) def config(): return JavaConfig( is_oracle=True, version='oracle-java8', ) // ... rest of the code ...
2d5e47b5a7f425042352e0fbc9930222ec001188
app/src/main/java/com/pr0gramm/app/ui/base/AsyncLifecycleTransformer.java
app/src/main/java/com/pr0gramm/app/ui/base/AsyncLifecycleTransformer.java
package com.pr0gramm.app.ui.base; import android.support.annotation.NonNull; import com.pr0gramm.app.util.BackgroundScheduler; import com.trello.rxlifecycle.LifecycleTransformer; import rx.Completable; import rx.Observable; import rx.Single; import rx.android.schedulers.AndroidSchedulers; /** */ class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> { private final LifecycleTransformer<T> transformer; AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) { this.transformer = transformer; } @NonNull @Override public <U> Single.Transformer<U, U> forSingle() { return single -> single.toObservable().compose((Observable.Transformer) this).toSingle(); } @NonNull @Override public Completable.Transformer forCompletable() { return completable -> completable.<T>toObservable().compose(this).toCompletable(); } @Override public Observable<T> call(Observable<T> observable) { return observable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer); } }
package com.pr0gramm.app.ui.base; import android.support.annotation.NonNull; import com.pr0gramm.app.util.BackgroundScheduler; import com.trello.rxlifecycle.LifecycleTransformer; import rx.Completable; import rx.Observable; import rx.Single; import rx.android.schedulers.AndroidSchedulers; /** */ class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> { private final LifecycleTransformer<T> transformer; AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) { this.transformer = transformer; } @NonNull @Override public <U> Single.Transformer<U, U> forSingle() { return single -> single .subscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forSingle()); } @NonNull @Override public Completable.Transformer forCompletable() { return completable -> completable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forCompletable()); } @Override public Observable<T> call(Observable<T> observable) { return observable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer); } }
Remove redundant single -> observable -> single transformation
Remove redundant single -> observable -> single transformation
Java
mit
mopsalarm/Pr0,mopsalarm/Pr0,mopsalarm/Pr0
java
## Code Before: package com.pr0gramm.app.ui.base; import android.support.annotation.NonNull; import com.pr0gramm.app.util.BackgroundScheduler; import com.trello.rxlifecycle.LifecycleTransformer; import rx.Completable; import rx.Observable; import rx.Single; import rx.android.schedulers.AndroidSchedulers; /** */ class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> { private final LifecycleTransformer<T> transformer; AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) { this.transformer = transformer; } @NonNull @Override public <U> Single.Transformer<U, U> forSingle() { return single -> single.toObservable().compose((Observable.Transformer) this).toSingle(); } @NonNull @Override public Completable.Transformer forCompletable() { return completable -> completable.<T>toObservable().compose(this).toCompletable(); } @Override public Observable<T> call(Observable<T> observable) { return observable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer); } } ## Instruction: Remove redundant single -> observable -> single transformation ## Code After: package com.pr0gramm.app.ui.base; import android.support.annotation.NonNull; import com.pr0gramm.app.util.BackgroundScheduler; import com.trello.rxlifecycle.LifecycleTransformer; import rx.Completable; import rx.Observable; import rx.Single; import rx.android.schedulers.AndroidSchedulers; /** */ class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> { private final LifecycleTransformer<T> transformer; AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) { this.transformer = transformer; } @NonNull @Override public <U> Single.Transformer<U, U> forSingle() { return single -> single .subscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forSingle()); } @NonNull @Override public Completable.Transformer forCompletable() { return completable -> completable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forCompletable()); } @Override public Observable<T> call(Observable<T> observable) { return observable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer); } }
# ... existing code ... @NonNull @Override public <U> Single.Transformer<U, U> forSingle() { return single -> single .subscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forSingle()); } @NonNull @Override public Completable.Transformer forCompletable() { return completable -> completable .subscribeOn(BackgroundScheduler.instance()) .unsubscribeOn(BackgroundScheduler.instance()) .observeOn(AndroidSchedulers.mainThread()) .compose(transformer.forCompletable()); } @Override # ... rest of the code ...
058cee7b5a3efcf6b6bd02a314f1223153cc797f
tools/TreeBest/fasta_header_converter.py
tools/TreeBest/fasta_header_converter.py
import json import optparse transcript_species_dict = dict() sequence_dict = dict() def readgene(gene): for transcript in gene['Transcript']: transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "") def read_fasta(fp): for line in fp: line = line.rstrip() if line.startswith(">"): name = line.replace(">", "") print ">" + name + "_" + transcript_species_dict[name] else: print line parser = optparse.OptionParser() parser.add_option('-j', '--json', dest="input_gene_filename", help='Gene Tree from Ensembl in JSON format') parser.add_option('-f', '--fasta', dest="input_fasta_filename", help='Gene Tree from Ensembl in JSON format') options, args = parser.parse_args() if options.input_gene_filename is None: raise Exception('-j option must be specified') if options.input_fasta_filename is None: raise Exception('-f option must be specified') with open(options.input_gene_filename) as data_file: data = json.load(data_file) for gene_dict in data.values(): readgene(gene_dict) with open(options.input_fasta_filename) as fp: read_fasta(fp)
from __future__ import print_function import json import optparse def read_gene_info(gene_info): transcript_species_dict = dict() for gene_dict in gene_info.values(): for transcript in gene_dict['Transcript']: transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "") return transcript_species_dict parser = optparse.OptionParser() parser.add_option('-j', '--json', dest="input_gene_filename", help='Gene feature information in JSON format') parser.add_option('-f', '--fasta', dest="input_fasta_filename", help='Sequences in FASTA format') options, args = parser.parse_args() if options.input_gene_filename is None: raise Exception('-j option must be specified') if options.input_fasta_filename is None: raise Exception('-f option must be specified') with open(options.input_gene_filename) as json_fh: gene_info = json.load(json_fh) transcript_species_dict = read_gene_info(gene_info) with open(options.input_fasta_filename) as fasta_fh: for line in fasta_fh: line = line.rstrip() if line.startswith(">"): name = line[1:].lstrip() print(">" + name + "_" + transcript_species_dict[name]) else: print(line)
Use print() for Python3. No global variables. Optimisations
Use print() for Python3. No global variables. Optimisations
Python
mit
TGAC/earlham-galaxytools,PerlaTroncosoRey/tgac-galaxytools,TGAC/tgac-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,wjurkowski/earlham-galaxytools,anilthanki/tgac-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,TGAC/tgac-galaxytools
python
## Code Before: import json import optparse transcript_species_dict = dict() sequence_dict = dict() def readgene(gene): for transcript in gene['Transcript']: transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "") def read_fasta(fp): for line in fp: line = line.rstrip() if line.startswith(">"): name = line.replace(">", "") print ">" + name + "_" + transcript_species_dict[name] else: print line parser = optparse.OptionParser() parser.add_option('-j', '--json', dest="input_gene_filename", help='Gene Tree from Ensembl in JSON format') parser.add_option('-f', '--fasta', dest="input_fasta_filename", help='Gene Tree from Ensembl in JSON format') options, args = parser.parse_args() if options.input_gene_filename is None: raise Exception('-j option must be specified') if options.input_fasta_filename is None: raise Exception('-f option must be specified') with open(options.input_gene_filename) as data_file: data = json.load(data_file) for gene_dict in data.values(): readgene(gene_dict) with open(options.input_fasta_filename) as fp: read_fasta(fp) ## Instruction: Use print() for Python3. No global variables. Optimisations ## Code After: from __future__ import print_function import json import optparse def read_gene_info(gene_info): transcript_species_dict = dict() for gene_dict in gene_info.values(): for transcript in gene_dict['Transcript']: transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "") return transcript_species_dict parser = optparse.OptionParser() parser.add_option('-j', '--json', dest="input_gene_filename", help='Gene feature information in JSON format') parser.add_option('-f', '--fasta', dest="input_fasta_filename", help='Sequences in FASTA format') options, args = parser.parse_args() if options.input_gene_filename is None: raise Exception('-j option must be specified') if options.input_fasta_filename is None: raise Exception('-f option must be specified') with open(options.input_gene_filename) as json_fh: gene_info = json.load(json_fh) transcript_species_dict = read_gene_info(gene_info) with open(options.input_fasta_filename) as fasta_fh: for line in fasta_fh: line = line.rstrip() if line.startswith(">"): name = line[1:].lstrip() print(">" + name + "_" + transcript_species_dict[name]) else: print(line)
# ... existing code ... from __future__ import print_function import json import optparse def read_gene_info(gene_info): transcript_species_dict = dict() for gene_dict in gene_info.values(): for transcript in gene_dict['Transcript']: transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "") return transcript_species_dict parser = optparse.OptionParser() parser.add_option('-j', '--json', dest="input_gene_filename", help='Gene feature information in JSON format') parser.add_option('-f', '--fasta', dest="input_fasta_filename", help='Sequences in FASTA format') options, args = parser.parse_args() if options.input_gene_filename is None: # ... modified code ... if options.input_fasta_filename is None: raise Exception('-f option must be specified') with open(options.input_gene_filename) as json_fh: gene_info = json.load(json_fh) transcript_species_dict = read_gene_info(gene_info) with open(options.input_fasta_filename) as fasta_fh: for line in fasta_fh: line = line.rstrip() if line.startswith(">"): name = line[1:].lstrip() print(">" + name + "_" + transcript_species_dict[name]) else: print(line) # ... rest of the code ...
1ff53eade7c02a92f5f09c371b766e7b176a90a1
speyer/ingest/gerrit.py
speyer/ingest/gerrit.py
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
Allow connecting to unknown hosts but warn
Allow connecting to unknown hosts but warn
Python
apache-2.0
locke105/streaming-python-testdrive
python
## Code Before: from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event ## Instruction: Allow connecting to unknown hosts but warn ## Code After: from __future__ import print_function import select import paramiko class GerritEvents(object): def __init__(self, userid, host, key=None): self.userid = userid self.host = host self.port = 29418 self.key = key def _read_events(self, stream, use_poll=False): if not use_poll: yield stream.readline().strip() poller = select.poll() poller.register(stream.channel) while True: for fd, event in poller.poll(): if fd == stream.channel.fileno(): if event == select.POLLIN: yield stream.readline().strip() else: raise Exception('Non-POLLIN event on stdout!') @property def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, 'port': self.port, 'username': self.userid } if self.key: connargs['pkey'] = self.key client.connect(**connargs) stdin, stdout, stderr = client.exec_command('gerrit stream-events') for event in self._read_events(stdout, use_poll=True): yield event
... def events(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) connargs = { 'hostname': self.host, ...
506dae52ca998d262e93ec5998d831ba26357e39
scheduler/src/main/java/org/apache/mesos/elasticsearch/scheduler/state/StatePath.java
scheduler/src/main/java/org/apache/mesos/elasticsearch/scheduler/state/StatePath.java
package org.apache.mesos.elasticsearch.scheduler.state; import org.apache.log4j.Logger; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private static final Logger LOGGER = Logger.getLogger(StatePath.class); private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } public void rm(String key) throws IOException { key = key.replace(" ", ""); zkState.delete(key); } }
package org.apache.mesos.elasticsearch.scheduler.state; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } /** * Remove a zNode or zFolder. * * @param key the path to remove. * @throws IOException If unable to remove */ public void rm(String key) throws IOException { zkState.delete(key); } }
Add comments. Remove space removal.
Review: Add comments. Remove space removal.
Java
apache-2.0
mesos/elasticsearch,mesos/elasticsearch,mesos/elasticsearch,mesos/elasticsearch
java
## Code Before: package org.apache.mesos.elasticsearch.scheduler.state; import org.apache.log4j.Logger; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private static final Logger LOGGER = Logger.getLogger(StatePath.class); private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } public void rm(String key) throws IOException { key = key.replace(" ", ""); zkState.delete(key); } } ## Instruction: Review: Add comments. Remove space removal. ## Code After: package org.apache.mesos.elasticsearch.scheduler.state; import java.io.IOException; import java.security.InvalidParameterException; /** * Path utilities */ public class StatePath { private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; } /** * Creates the zNode if it does not exist. Will create parent directories. * @param key the zNode path */ public void mkdir(String key) throws IOException { key = key.replace(" ", ""); if (key.endsWith("/") && !key.equals("/")) { throw new InvalidParameterException("Trailing slash not allowed in zookeeper path"); } String[] split = key.split("/"); StringBuilder builder = new StringBuilder(); for (String s : split) { builder.append(s); if (!s.isEmpty() && !exists(builder.toString())) { zkState.set(builder.toString(), null); } builder.append("/"); } } public Boolean exists(String key) throws IOException { Boolean exists = true; Object value = zkState.get(key); if (value == null) { exists = false; } return exists; } /** * Remove a zNode or zFolder. * * @param key the path to remove. * @throws IOException If unable to remove */ public void rm(String key) throws IOException { zkState.delete(key); } }
... package org.apache.mesos.elasticsearch.scheduler.state; import java.io.IOException; import java.security.InvalidParameterException; ... * Path utilities */ public class StatePath { private SerializableState zkState; public StatePath(SerializableState zkState) { this.zkState = zkState; ... return exists; } /** * Remove a zNode or zFolder. * * @param key the path to remove. * @throws IOException If unable to remove */ public void rm(String key) throws IOException { zkState.delete(key); } } ...
38bc8c8599d4165485ada8ca0b55dafd547385c4
runserver.py
runserver.py
import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options))
import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
Allow to run objgraph before exiting
Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.
Python
apache-2.0
open-io/oio-swift,open-io/oio-swift
python
## Code Before: import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options)) ## Instruction: Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences. ## Code After: import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
# ... existing code ... import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res) # ... rest of the code ...
0b8e99a6c7ecf5b35c61ce4eed1b2eec3110d41d
runtests.py
runtests.py
import os import sys # Force this to happen before loading django try: os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings" test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, test_dir) except ImportError: pass else: import django from django.conf import settings from django.test.utils import get_runner def runtests(): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(["tinymce"]) sys.exit(bool(failures)) if __name__ == "__main__": runtests()
import argparse import os import sys # Force this to happen before loading django try: os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings" test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, test_dir) except ImportError: pass else: import django from django.conf import settings from django.test.utils import get_runner def runtests(verbosity=1, failfast=False): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(interactive=True, verbosity=verbosity, failfast=failfast) failures = test_runner.run_tests(["tinymce"]) sys.exit(bool(failures)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the django-tinymce test suite.") parser.add_argument( "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help="Verbosity level; 0=minimal output, 1=normal output, 2=all output", ) parser.add_argument( "--failfast", action="store_true", help="Stop running the test suite after first failed test.", ) options = parser.parse_args() runtests(verbosity=options.verbosity, failfast=options.failfast)
Add ability to run tests with verbosity and failfast options
Add ability to run tests with verbosity and failfast options
Python
mit
aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce
python
## Code Before: import os import sys # Force this to happen before loading django try: os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings" test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, test_dir) except ImportError: pass else: import django from django.conf import settings from django.test.utils import get_runner def runtests(): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(["tinymce"]) sys.exit(bool(failures)) if __name__ == "__main__": runtests() ## Instruction: Add ability to run tests with verbosity and failfast options ## Code After: import argparse import os import sys # Force this to happen before loading django try: os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings" test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, test_dir) except ImportError: pass else: import django from django.conf import settings from django.test.utils import get_runner def runtests(verbosity=1, failfast=False): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(interactive=True, verbosity=verbosity, failfast=failfast) failures = test_runner.run_tests(["tinymce"]) sys.exit(bool(failures)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the django-tinymce test suite.") parser.add_argument( "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help="Verbosity level; 0=minimal output, 1=normal output, 2=all output", ) parser.add_argument( "--failfast", action="store_true", help="Stop running the test suite after first failed test.", ) options = parser.parse_args() runtests(verbosity=options.verbosity, failfast=options.failfast)
# ... existing code ... import argparse import os import sys # ... modified code ... from django.test.utils import get_runner def runtests(verbosity=1, failfast=False): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(interactive=True, verbosity=verbosity, failfast=failfast) failures = test_runner.run_tests(["tinymce"]) sys.exit(bool(failures)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the django-tinymce test suite.") parser.add_argument( "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help="Verbosity level; 0=minimal output, 1=normal output, 2=all output", ) parser.add_argument( "--failfast", action="store_true", help="Stop running the test suite after first failed test.", ) options = parser.parse_args() runtests(verbosity=options.verbosity, failfast=options.failfast) # ... rest of the code ...
3c99ef3f99c3f3188e8afbd7fdbe984877363865
allure-report/allure-report-data/src/main/java/ru/yandex/qatools/allure/data/utils/AllureReportUtils.java
allure-report/allure-report-data/src/main/java/ru/yandex/qatools/allure/data/utils/AllureReportUtils.java
package ru.yandex.qatools.allure.data.utils; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; import ru.yandex.qatools.allure.data.ReportGenerationException; import java.io.*; /** * @author Dmitry Baev [email protected] * Date: 31.10.13 */ public final class AllureReportUtils { private AllureReportUtils() { } public static void serialize(final File directory, String name, Object obj) { try { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); mapper.getSerializationConfig().with(ai); mapper.writerWithDefaultPrettyPrinter().writeValue(new File(directory, name), obj); } catch (IOException e) { throw new ReportGenerationException(e); } } }
package ru.yandex.qatools.allure.data.utils; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; import ru.yandex.qatools.allure.data.ReportGenerationException; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Dmitry Baev [email protected] * Date: 31.10.13 */ public final class AllureReportUtils { private AllureReportUtils() { } public static void serialize(final File directory, String name, Object obj) { try { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); mapper.getSerializationConfig().with(annotatoinInspector); OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8); mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj); } catch (IOException e) { throw new ReportGenerationException(e); } } }
Use UTF-8 while write testcases json
Use UTF-8 while write testcases json
Java
apache-2.0
allure-framework/allure1,allure-framework/allure1,allure-framework/allure-core,allure-framework/allure-core,wuhuizuo/allure-core,wuhuizuo/allure-core,wuhuizuo/allure-core,allure-framework/allure-core,wuhuizuo/allure-core,allure-framework/allure-core,allure-framework/allure1,allure-framework/allure1
java
## Code Before: package ru.yandex.qatools.allure.data.utils; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; import ru.yandex.qatools.allure.data.ReportGenerationException; import java.io.*; /** * @author Dmitry Baev [email protected] * Date: 31.10.13 */ public final class AllureReportUtils { private AllureReportUtils() { } public static void serialize(final File directory, String name, Object obj) { try { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); mapper.getSerializationConfig().with(ai); mapper.writerWithDefaultPrettyPrinter().writeValue(new File(directory, name), obj); } catch (IOException e) { throw new ReportGenerationException(e); } } } ## Instruction: Use UTF-8 while write testcases json ## Code After: package ru.yandex.qatools.allure.data.utils; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; import ru.yandex.qatools.allure.data.ReportGenerationException; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Dmitry Baev [email protected] * Date: 31.10.13 */ public final class AllureReportUtils { private AllureReportUtils() { } public static void serialize(final File directory, String name, Object obj) { try { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); mapper.getSerializationConfig().with(annotatoinInspector); OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8); mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj); } catch (IOException e) { throw new ReportGenerationException(e); } } }
# ... existing code ... import ru.yandex.qatools.allure.data.ReportGenerationException; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Dmitry Baev [email protected] # ... modified code ... public static void serialize(final File directory, String name, Object obj) { try { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); mapper.getSerializationConfig().with(annotatoinInspector); OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8); mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj); } catch (IOException e) { throw new ReportGenerationException(e); } # ... rest of the code ...
b4ed6bc8f28f89ed53426f16ee0f37f077503dbe
odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java
odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java
package org.springframework.ldap.odm.test.utils; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; public class CompilerInterface { // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { ProcessBuilder pb = new ProcessBuilder( new String[] { "javac", "-cp", "."+File.pathSeparatorChar+"target"+File.separatorChar+"classes"+ File.pathSeparatorChar+System.getProperty("java.class.path"), directory+File.separatorChar+file }); pb.redirectErrorStream(true); Process proc = pb.start(); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); char[] buf = new char[1024]; int count; StringBuilder builder = new StringBuilder(); while ((count = isr.read(buf)) > 0) { builder.append(buf, 0, count); } boolean ok = proc.waitFor() == 0; if (!ok) { throw new RuntimeException(builder.toString()); } } }
package org.springframework.ldap.odm.test.utils; import java.io.File; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class CompilerInterface { // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { File toCompile = new File(directory, file); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile)); compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); fileManager.close(); } }
Use JavaCompiler in tests isntead of manually finding "javac"
Use JavaCompiler in tests isntead of manually finding "javac"
Java
apache-2.0
rwinch/spring-ldap,eddumelendez/spring-ldap,ChunPIG/spring-ldap,vitorgv/spring-ldap,eddumelendez/spring-ldap,vitorgv/spring-ldap,ChunPIG/spring-ldap,jaune162/spring-ldap,likaiwalkman/spring-ldap,wilkinsona/spring-ldap,fzilic/spring-ldap,wilkinsona/spring-ldap,eddumelendez/spring-ldap,rwinch/spring-ldap,thomasdarimont/spring-ldap,wilkinsona/spring-ldap,ChunPIG/spring-ldap,eddumelendez/spring-ldap,fzilic/spring-ldap,jaune162/spring-ldap,fzilic/spring-ldap,n8rogers/spring-ldap,spring-projects/spring-ldap,n8rogers/spring-ldap,vitorgv/spring-ldap,zion64/spring-ldap,zion64/spring-ldap,rwinch/spring-ldap,n8rogers/spring-ldap,zion64/spring-ldap,likaiwalkman/spring-ldap,fzilic/spring-ldap,likaiwalkman/spring-ldap,likaiwalkman/spring-ldap,thomasdarimont/spring-ldap,spring-projects/spring-ldap,rwinch/spring-ldap,spring-projects/spring-ldap,n8rogers/spring-ldap,likaiwalkman/spring-ldap,thomasdarimont/spring-ldap,fzilic/spring-ldap,wilkinsona/spring-ldap,n8rogers/spring-ldap,spring-projects/spring-ldap,zion64/spring-ldap,jaune162/spring-ldap,jaune162/spring-ldap,spring-projects/spring-ldap,ChunPIG/spring-ldap,rwinch/spring-ldap,vitorgv/spring-ldap,wilkinsona/spring-ldap,rwinch/spring-ldap,jaune162/spring-ldap,thomasdarimont/spring-ldap,likaiwalkman/spring-ldap,vitorgv/spring-ldap,eddumelendez/spring-ldap,jaune162/spring-ldap,eddumelendez/spring-ldap,n8rogers/spring-ldap,ChunPIG/spring-ldap,ChunPIG/spring-ldap,zion64/spring-ldap,thomasdarimont/spring-ldap,fzilic/spring-ldap,thomasdarimont/spring-ldap
java
## Code Before: package org.springframework.ldap.odm.test.utils; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; public class CompilerInterface { // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { ProcessBuilder pb = new ProcessBuilder( new String[] { "javac", "-cp", "."+File.pathSeparatorChar+"target"+File.separatorChar+"classes"+ File.pathSeparatorChar+System.getProperty("java.class.path"), directory+File.separatorChar+file }); pb.redirectErrorStream(true); Process proc = pb.start(); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); char[] buf = new char[1024]; int count; StringBuilder builder = new StringBuilder(); while ((count = isr.read(buf)) > 0) { builder.append(buf, 0, count); } boolean ok = proc.waitFor() == 0; if (!ok) { throw new RuntimeException(builder.toString()); } } } ## Instruction: Use JavaCompiler in tests isntead of manually finding "javac" ## Code After: package org.springframework.ldap.odm.test.utils; import java.io.File; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class CompilerInterface { // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { File toCompile = new File(directory, file); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile)); compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); fileManager.close(); } }
... package org.springframework.ldap.odm.test.utils; import java.io.File; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class CompilerInterface { // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { File toCompile = new File(directory, file); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile)); compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); fileManager.close(); } } ...
001a50b236e60358cf1fbe371d6d20ea72003ceb
noms.py
noms.py
from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
Add some basic error handling and remove tuples.
Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.
Python
mit
brotatos/noms
python
## Code Before: from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1]) ## Instruction: Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal. ## Code After: from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
// ... existing code ... from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' // ... modified code ... for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) // ... rest of the code ...
af52a3967568a3d5af838e695d5fcdd825f585cf
numba2/runtime/tests/test_ffi.py
numba2/runtime/tests/test_ffi.py
from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): raise unittest.SkipTest @jit def f(): p = ffi.malloc(2, types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main()
from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): @jit def f(): p = ffi.malloc(cast(2, types.int64), types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main()
Insert explicit cast to malloc implementation
Insert explicit cast to malloc implementation
Python
bsd-2-clause
flypy/flypy,flypy/flypy
python
## Code Before: from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): raise unittest.SkipTest @jit def f(): p = ffi.malloc(2, types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main() ## Instruction: Insert explicit cast to malloc implementation ## Code After: from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): @jit def f(): p = ffi.malloc(cast(2, types.int64), types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main()
... import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ ... class TestFFI(unittest.TestCase): def test_malloc(self): @jit def f(): p = ffi.malloc(cast(2, types.int64), types.int32) p[0] = 4 p[1] = 5 return p ...
d58576bc658f1433351c0cf9ac0225537e17f472
cobe/brain.py
cobe/brain.py
import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, TokenNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass
import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass
Remove unused import of TokenNormalizer
Remove unused import of TokenNormalizer Fixes the build
Python
mit
wodim/cobe-ng,LeMagnesium/cobe,pteichman/cobe,tiagochiavericosta/cobe,meska/cobe,pteichman/cobe,LeMagnesium/cobe,wodim/cobe-ng,tiagochiavericosta/cobe,DarkMio/cobe,meska/cobe,DarkMio/cobe
python
## Code Before: import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, TokenNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass ## Instruction: Remove unused import of TokenNormalizer Fixes the build ## Code After: import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass
// ... existing code ... import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher // ... rest of the code ...
d613ca02bef0572d7581c843eb5466443410decf
test_settings.py
test_settings.py
import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" INSTALLED_APPS = ( 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" # Default Django middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangae.tasks.middleware.task_environment_middleware', ] INSTALLED_APPS = ( 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
Set default Django middleware in test settings
Set default Django middleware in test settings
Python
bsd-3-clause
potatolondon/djangae,potatolondon/djangae
python
## Code Before: import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" INSTALLED_APPS = ( 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ] ## Instruction: Set default Django middleware in test settings ## Code After: import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" # Default Django middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangae.tasks.middleware.task_environment_middleware', ] INSTALLED_APPS = ( 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
... BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" # Default Django middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangae.tasks.middleware.task_environment_middleware', ] INSTALLED_APPS = ( 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup ...
801c370ce88b3b2689da5890ebf09bae533089f4
tob-api/tob_api/hyperledger_indy.py
tob-api/tob_api/hyperledger_indy.py
import os import platform def config(): genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") return { "genesis_txn_path": genesis_txn_path, }
import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, }
Add support for downloading the genesis transaction file.
Add support for downloading the genesis transaction file.
Python
apache-2.0
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook
python
## Code Before: import os import platform def config(): genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") return { "genesis_txn_path": genesis_txn_path, } ## Instruction: Add support for downloading the genesis transaction file. ## Code After: import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, }
... import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, } ...
0dc72761a3b4b17098633df27fdbb70058afe311
geotrek/signage/migrations/0013_auto_20200423_1255.py
geotrek/signage/migrations/0013_auto_20200423_1255.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]), migrations.RemoveField( model_name='blade', name='deleted', ), migrations.RemoveField( model_name='blade', name='structure', ), migrations.RemoveField( model_name='line', name='structure', ), migrations.AlterField( model_name='line', name='blade', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='signage.Blade', verbose_name='Blade'), ), ]
from django.db import migrations, models import django.db.models.deletion def delete_force(apps, schema_editor): # We can't import Infrastructure models directly as it may be a newer # version than this migration expects. We use the historical version. Blade = apps.get_model('signage', 'Blade') for blade in Blade.objects.filter(deleted=True): blade.delete() class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.AlterField( model_name='line', name='blade', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='signage.Blade', verbose_name='Blade'), ), migrations.RunPython(delete_force), migrations.RemoveField( model_name='blade', name='deleted', ), migrations.RemoveField( model_name='blade', name='structure', ), migrations.RemoveField( model_name='line', name='structure', ), ]
Change order migration, user runpython instead
Change order migration, user runpython instead
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin
python
## Code Before: from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]), migrations.RemoveField( model_name='blade', name='deleted', ), migrations.RemoveField( model_name='blade', name='structure', ), migrations.RemoveField( model_name='line', name='structure', ), migrations.AlterField( model_name='line', name='blade', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='signage.Blade', verbose_name='Blade'), ), ] ## Instruction: Change order migration, user runpython instead ## Code After: from django.db import migrations, models import django.db.models.deletion def delete_force(apps, schema_editor): # We can't import Infrastructure models directly as it may be a newer # version than this migration expects. We use the historical version. Blade = apps.get_model('signage', 'Blade') for blade in Blade.objects.filter(deleted=True): blade.delete() class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.AlterField( model_name='line', name='blade', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='signage.Blade', verbose_name='Blade'), ), migrations.RunPython(delete_force), migrations.RemoveField( model_name='blade', name='deleted', ), migrations.RemoveField( model_name='blade', name='structure', ), migrations.RemoveField( model_name='line', name='structure', ), ]
# ... existing code ... from django.db import migrations, models import django.db.models.deletion def delete_force(apps, schema_editor): # We can't import Infrastructure models directly as it may be a newer # version than this migration expects. We use the historical version. Blade = apps.get_model('signage', 'Blade') for blade in Blade.objects.filter(deleted=True): blade.delete() class Migration(migrations.Migration): # ... modified code ... ] operations = [ migrations.AlterField( model_name='line', name='blade', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='signage.Blade', verbose_name='Blade'), ), migrations.RunPython(delete_force), migrations.RemoveField( model_name='blade', name='deleted', ... model_name='line', name='structure', ), ] # ... rest of the code ...
b0c2262bb50fb51bcc2f5eadb86b353cc9eb38a3
bin/Bullet.py
bin/Bullet.py
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(x=self._x, y=self._y, thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback)
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback) def hit(self): self.destroy()
Add bullet hit function to destroy self.
Add bullet hit function to destroy self.
Python
mit
emreeroglu/DummyShip
python
## Code Before: from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(x=self._x, y=self._y, thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback) ## Instruction: Add bullet hit function to destroy self. ## Code After: from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback) def hit(self): self.destroy()
// ... existing code ... def set_y(self, value): self._y += value for callback in self._observers: callback(thing=self) y = property(get_y, set_y) // ... modified code ... def bind_to(self, callback): self._observers.append(callback) def hit(self): self.destroy() // ... rest of the code ...
edad01902f8c9d23da106c538d118e28da286821
lesion/lifio.py
lesion/lifio.py
import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '256M', '64k', and '2G'. Expect to need a lot. """ jv.start_vm(class_path=bf.JARS, max_heap_size=max_heap_size) def done(): """Kill the JVM. Once killed, it cannot be restarted. Notes ----- See the python-javabridge documentation for more information. """ jv.kill_vm()
import numpy as np import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '256M', '64k', and '2G'. Expect to need a lot. """ jv.start_vm(class_path=bf.JARS, max_heap_size=max_heap_size) def done(): """Kill the JVM. Once killed, it cannot be restarted. Notes ----- See the python-javabridge documentation for more information. """ jv.kill_vm() def lif_metadata_string_size(filename): """Get the length in bytes of the metadata string of a LIF file. Parameters ---------- filename : string Path to the LIF file. Returns ------- length : int The length in bytes of the metadata string. Notes ----- This is based on code by Lee Kamentsky. [1] References ---------- [1] https://github.com/CellProfiler/python-bioformats/issues/8 """ with open(filename, 'rb') as fd: fd.read(9) length = np.frombuffer(fd.read(4), "<i4")[0] return length
Add function to determine metadata length
Add function to determine metadata length
Python
bsd-3-clause
jni/lesion
python
## Code Before: import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '256M', '64k', and '2G'. Expect to need a lot. """ jv.start_vm(class_path=bf.JARS, max_heap_size=max_heap_size) def done(): """Kill the JVM. Once killed, it cannot be restarted. Notes ----- See the python-javabridge documentation for more information. """ jv.kill_vm() ## Instruction: Add function to determine metadata length ## Code After: import numpy as np import javabridge as jv import bioformats as bf def start(max_heap_size='8G'): """Start the Java Virtual Machine, enabling bioformats IO. Parameters ---------- max_heap_size : string, optional The maximum memory usage by the virtual machine. Valid strings include '256M', '64k', and '2G'. Expect to need a lot. """ jv.start_vm(class_path=bf.JARS, max_heap_size=max_heap_size) def done(): """Kill the JVM. Once killed, it cannot be restarted. Notes ----- See the python-javabridge documentation for more information. """ jv.kill_vm() def lif_metadata_string_size(filename): """Get the length in bytes of the metadata string of a LIF file. Parameters ---------- filename : string Path to the LIF file. Returns ------- length : int The length in bytes of the metadata string. Notes ----- This is based on code by Lee Kamentsky. [1] References ---------- [1] https://github.com/CellProfiler/python-bioformats/issues/8 """ with open(filename, 'rb') as fd: fd.read(9) length = np.frombuffer(fd.read(4), "<i4")[0] return length
... import numpy as np import javabridge as jv import bioformats as bf ... See the python-javabridge documentation for more information. """ jv.kill_vm() def lif_metadata_string_size(filename): """Get the length in bytes of the metadata string of a LIF file. Parameters ---------- filename : string Path to the LIF file. Returns ------- length : int The length in bytes of the metadata string. Notes ----- This is based on code by Lee Kamentsky. [1] References ---------- [1] https://github.com/CellProfiler/python-bioformats/issues/8 """ with open(filename, 'rb') as fd: fd.read(9) length = np.frombuffer(fd.read(4), "<i4")[0] return length ...
be6f28f28b57e912df6c276060bc38e7912a2262
C/mwt.c
C/mwt.c
int main (int argc, char *argv[]){ if(argc != 3){ printf("Number of parameters should be 2 (filename, cardinality)."); exit(1); } //open file and get file length FILE *file; file = fopen(argv[1],"r"); if(file == NULL){ printf("File couldn't be opened."); exit(1); } fseek(file, 0, SEEK_END); int fileLength = ftell(file); fseek(file, 0, SEEK_SET); //save data from file to array char inputStream[fileLength]; //printf("length: %d \n", fileLength); int i = 0; int character; while((character = fgetc(file)) != EOF){ inputStream[i] = character; i++; } /*int j; for(j=0; j < fileLength; j++){ char a = inputStream[j]; printf("Znak: %c \n", a); }*/ fclose(file); }
int main (int argc, char *argv[]){ if(argc != 3){ printf("Number of parameters should be 2 (filename, arity)."); exit(1); } int alphabet[128] = {0}; int arity = atoi(argv[2]); int treeLayers = ceil(7/log2(arity)); printf("Number of layers: %d \n", treeLayers); //open file and get file length FILE *file; file = fopen(argv[1],"r"); if(file == NULL){ printf("File couldn't be opened."); exit(1); } fseek(file, 0, SEEK_END); int fileLength = ftell(file); fseek(file, 0, SEEK_SET); //save data from file to array char inputStream[fileLength]; printf("length: %d \n", fileLength); int i = 0; int character; int numOfChar = 0; while((character = fgetc(file)) != EOF){ inputStream[i] = character; if(alphabet[character]==0){ alphabet[character]=1; numOfChar++; } i++; } char charOfAlphabet[numOfChar]; int j; int k = 0; for (j = 0; j < 128; j++){ if(alphabet[j]==1){ charOfAlphabet[k] = j; k++; } } //for(j=0; j < fileLength; j++){ // int a = inputStream[j]; //printf("Znak: %d \n", a); //} fclose(file); }
Define alphabet and number of tree layers
Define alphabet and number of tree layers
C
mit
marijanaSpajic/multiary_wavelet_tree,marijanaSpajic/multiary_wavelet_tree,marijanaSpajic/multiary_wavelet_tree,marijanaSpajic/multiary_wavelet_tree,marijanaSpajic/multiary_wavelet_tree,marijanaSpajic/multiary_wavelet_tree
c
## Code Before: int main (int argc, char *argv[]){ if(argc != 3){ printf("Number of parameters should be 2 (filename, cardinality)."); exit(1); } //open file and get file length FILE *file; file = fopen(argv[1],"r"); if(file == NULL){ printf("File couldn't be opened."); exit(1); } fseek(file, 0, SEEK_END); int fileLength = ftell(file); fseek(file, 0, SEEK_SET); //save data from file to array char inputStream[fileLength]; //printf("length: %d \n", fileLength); int i = 0; int character; while((character = fgetc(file)) != EOF){ inputStream[i] = character; i++; } /*int j; for(j=0; j < fileLength; j++){ char a = inputStream[j]; printf("Znak: %c \n", a); }*/ fclose(file); } ## Instruction: Define alphabet and number of tree layers ## Code After: int main (int argc, char *argv[]){ if(argc != 3){ printf("Number of parameters should be 2 (filename, arity)."); exit(1); } int alphabet[128] = {0}; int arity = atoi(argv[2]); int treeLayers = ceil(7/log2(arity)); printf("Number of layers: %d \n", treeLayers); //open file and get file length FILE *file; file = fopen(argv[1],"r"); if(file == NULL){ printf("File couldn't be opened."); exit(1); } fseek(file, 0, SEEK_END); int fileLength = ftell(file); fseek(file, 0, SEEK_SET); //save data from file to array char inputStream[fileLength]; printf("length: %d \n", fileLength); int i = 0; int character; int numOfChar = 0; while((character = fgetc(file)) != EOF){ inputStream[i] = character; if(alphabet[character]==0){ alphabet[character]=1; numOfChar++; } i++; } char charOfAlphabet[numOfChar]; int j; int k = 0; for (j = 0; j < 128; j++){ if(alphabet[j]==1){ charOfAlphabet[k] = j; k++; } } //for(j=0; j < fileLength; j++){ // int a = inputStream[j]; //printf("Znak: %d \n", a); //} fclose(file); }
// ... existing code ... int main (int argc, char *argv[]){ if(argc != 3){ printf("Number of parameters should be 2 (filename, arity)."); exit(1); } int alphabet[128] = {0}; int arity = atoi(argv[2]); int treeLayers = ceil(7/log2(arity)); printf("Number of layers: %d \n", treeLayers); //open file and get file length FILE *file; // ... modified code ... //save data from file to array char inputStream[fileLength]; printf("length: %d \n", fileLength); int i = 0; int character; int numOfChar = 0; while((character = fgetc(file)) != EOF){ inputStream[i] = character; if(alphabet[character]==0){ alphabet[character]=1; numOfChar++; } i++; } char charOfAlphabet[numOfChar]; int j; int k = 0; for (j = 0; j < 128; j++){ if(alphabet[j]==1){ charOfAlphabet[k] = j; k++; } } //for(j=0; j < fileLength; j++){ // int a = inputStream[j]; //printf("Znak: %d \n", a); //} fclose(file); } // ... rest of the code ...
bdedbef5a8326705523cd3a7113cadb15d4a59ec
ckanext/wirecloudview/tests/test_plugin.py
ckanext/wirecloudview/tests/test_plugin.py
"""Tests for plugin.py.""" import ckanext.wirecloudview.plugin as plugin from mock import MagicMock, patch class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name")
import unittest from mock import MagicMock, patch import ckanext.wirecloudview.plugin as plugin class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name")
Fix unittest import and add copyright headers
Fix unittest import and add copyright headers
Python
agpl-3.0
conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view
python
## Code Before: """Tests for plugin.py.""" import ckanext.wirecloudview.plugin as plugin from mock import MagicMock, patch class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name") ## Instruction: Fix unittest import and add copyright headers ## Code After: import unittest from mock import MagicMock, patch import ckanext.wirecloudview.plugin as plugin class DataRequestPluginTest(unittest.TestCase): def test_process_dashboardid_should_strip(self): self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name") def test_process_dashboardid_should_leave_untouched_valid_dashboard_ids(self): self.assertEqual(plugin.process_dashboardid(self, "owner/name", context), "onwer/name")
... import unittest from mock import MagicMock, patch import ckanext.wirecloudview.plugin as plugin class DataRequestPluginTest(unittest.TestCase): ...
2414355d059055816e1720db4e190c70fef04396
src/main/kotlin/com/nibado/projects/advent/y2020/Day13.kt
src/main/kotlin/com/nibado/projects/advent/y2020/Day13.kt
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day13 : Day { private val lines = resourceLines(2020, 13) private val timeStamp = lines.first().toInt() private val busIds = lines.last().split(",").toList() override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() } .map { it to timeStamp - (timeStamp % it) + it } .minBy { it.second - timeStamp }!! .let { it.first * (it.second - timeStamp) } override fun part2(): Long { val busses = busIds.mapIndexed { i, id -> id to i } .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b } var subList = busses.take(2) var time = 0L var increment = subList.first().first.toLong() while(true) { time += increment if(subList.all { (time + it.second) % it.first == 0L }) { if(subList.size == busses.size) { break } else { increment = subList.map { it.first.toLong() }.reduce { a, b -> a * b } subList = busses.take(subList.size + 1) } } } return time } }
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day13 : Day { private val lines = resourceLines(2020, 13) private val timeStamp = lines.first().toInt() private val busIds = lines.last().split(",").toList() override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() } .map { it to timeStamp - (timeStamp % it) + it } .minBy { it.second - timeStamp }!! .let { it.first * (it.second - timeStamp) } override fun part2(): Long { val busses = busIds.mapIndexed { i, id -> id to i } .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b } var time = 0L var increment = 1L for((id, i) in busses) { while((time + i) % id != 0L) { time += increment } increment *= id } return time } }
Refactor Day 13 part 2
Refactor Day 13 part 2
Kotlin
mit
nielsutrecht/adventofcode,nielsutrecht/adventofcode,nielsutrecht/adventofcode
kotlin
## Code Before: package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day13 : Day { private val lines = resourceLines(2020, 13) private val timeStamp = lines.first().toInt() private val busIds = lines.last().split(",").toList() override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() } .map { it to timeStamp - (timeStamp % it) + it } .minBy { it.second - timeStamp }!! .let { it.first * (it.second - timeStamp) } override fun part2(): Long { val busses = busIds.mapIndexed { i, id -> id to i } .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b } var subList = busses.take(2) var time = 0L var increment = subList.first().first.toLong() while(true) { time += increment if(subList.all { (time + it.second) % it.first == 0L }) { if(subList.size == busses.size) { break } else { increment = subList.map { it.first.toLong() }.reduce { a, b -> a * b } subList = busses.take(subList.size + 1) } } } return time } } ## Instruction: Refactor Day 13 part 2 ## Code After: package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day13 : Day { private val lines = resourceLines(2020, 13) private val timeStamp = lines.first().toInt() private val busIds = lines.last().split(",").toList() override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() } .map { it to timeStamp - (timeStamp % it) + it } .minBy { it.second - timeStamp }!! .let { it.first * (it.second - timeStamp) } override fun part2(): Long { val busses = busIds.mapIndexed { i, id -> id to i } .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b } var time = 0L var increment = 1L for((id, i) in busses) { while((time + i) % id != 0L) { time += increment } increment *= id } return time } }
... val busses = busIds.mapIndexed { i, id -> id to i } .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b } var time = 0L var increment = 1L for((id, i) in busses) { while((time + i) % id != 0L) { time += increment } increment *= id } return time ...
b74971eaf180c14fef68142bffc689b1bc7340f4
approvaltests/Namer.py
approvaltests/Namer.py
import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return self.Directory + "\\" + self.ClassName + "." + self.MethodName
import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return os.path.join(self.Directory, self.ClassName + "." + self.MethodName)
Create approval file path that works on Linux and Windows.
Create approval file path that works on Linux and Windows.
Python
apache-2.0
approvals/ApprovalTests.Python,approvals/ApprovalTests.Python,approvals/ApprovalTests.Python,tdpreece/ApprovalTests.Python
python
## Code Before: import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return self.Directory + "\\" + self.ClassName + "." + self.MethodName ## Instruction: Create approval file path that works on Linux and Windows. ## Code After: import inspect import os class Namer(object): ClassName = '' MethodName = '' Directory = '' def setForStack(self, caller): stackFrame = caller[self.frame] self.MethodName = stackFrame[3] self.ClassName = stackFrame[0].f_globals["__name__"] self.Directory = os.path.dirname(stackFrame[1]) def __init__(self, frame=1): self.frame = frame self.setForStack(inspect.stack(1)) def getClassName(self): return self.ClassName def getMethodName(self): return self.MethodName def getDirectory(self): return self.Directory def get_basename(self): return os.path.join(self.Directory, self.ClassName + "." + self.MethodName)
# ... existing code ... return self.Directory def get_basename(self): return os.path.join(self.Directory, self.ClassName + "." + self.MethodName) # ... rest of the code ...
ac44332d53736f1ac3e067eecf1064bcef038b3a
core/platform/transactions/django_transaction_services.py
core/platform/transactions/django_transaction_services.py
"""Provides a seam for transaction services.""" __author__ = 'Sean Lip' def run_in_transaction(fn, *args, **kwargs): """Run a function in a transaction.""" # TODO(sll): Actually run the function in a transaction. return fn(*args, **kwargs)
"""Provides a seam for transaction services.""" __author__ = 'Sean Lip' from django.db import transaction def run_in_transaction(fn, *args, **kwargs): """Run a function in a transaction.""" with transaction.commit_on_success(): return fn(*args, **kwargs)
Add transaction support for django models.
Add transaction support for django models.
Python
apache-2.0
oulan/oppia,directorlive/oppia,google-code-export/oppia,oulan/oppia,michaelWagner/oppia,edallison/oppia,terrameijar/oppia,Dev4X/oppia,amitdeutsch/oppia,zgchizi/oppia-uc,virajprabhu/oppia,won0089/oppia,sunu/oppia,mit0110/oppia,sanyaade-teachings/oppia,kennho/oppia,BenHenning/oppia,CMDann/oppia,whygee/oppia,gale320/oppia,kevinlee12/oppia,won0089/oppia,bjvoth/oppia,kaffeel/oppia,won0089/oppia,cleophasmashiri/oppia,danieljjh/oppia,openhatch/oh-missions-oppia-beta,nagyistoce/oppia,kaffeel/oppia,mit0110/oppia,kevinlee12/oppia,kennho/oppia,rackstar17/oppia,toooooper/oppia,won0089/oppia,jestapinski/oppia,Dev4X/oppia,mit0110/oppia,BenHenning/oppia,sdulal/oppia,sanyaade-teachings/oppia,himanshu-dixit/oppia,leandrotoledo/oppia,kevinlee12/oppia,edallison/oppia,toooooper/oppia,souravbadami/oppia,openhatch/oh-missions-oppia-beta,google-code-export/oppia,aldeka/oppia,MaximLich/oppia,kingctan/oppia,oppia/oppia,google-code-export/oppia,AllanYangZhou/oppia,sunu/oppia,sdulal/oppia,sbhowmik89/oppia,sunu/oppia,danieljjh/oppia,Cgruppo/oppia,nagyistoce/oppia,terrameijar/oppia,toooooper/oppia,souravbadami/oppia,mindpin/mindpin_oppia,fernandopinhati/oppia,bjvoth/oppia,danieljjh/oppia,felipecocco/oppia,Atlas-Sailed-Co/oppia,miyucy/oppia,kaffeel/oppia,Atlas-Sailed-Co/oppia,nagyistoce/oppia,aldeka/oppia,dippatel1994/oppia,Cgruppo/oppia,leandrotoledo/oppia,leandrotoledo/oppia,mindpin/mindpin_oppia,raju249/oppia,BenHenning/oppia,kennho/oppia,raju249/oppia,dippatel1994/oppia,VictoriaRoux/oppia,oppia/oppia,mindpin/mindpin_oppia,wangsai/oppia,virajprabhu/oppia,miyucy/oppia,VictoriaRoux/oppia,fernandopinhati/oppia,infinyte/oppia,infinyte/oppia,anthkris/oppia,Dev4X/oppia,MaximLich/oppia,CMDann/oppia,brianrodri/oppia,jestapinski/oppia,kingctan/oppia,amitdeutsch/oppia,brylie/oppia,brianrodri/oppia,MAKOSCAFEE/oppia,nagyistoce/oppia,fernandopinhati/oppia,mindpin/mindpin_oppia,whygee/oppia,Atlas-Sailed-Co/oppia,amitdeutsch/oppia,MAKOSCAFEE/oppia,whygee/oppia,infinyte/oppia,danieljjh/oppia,Cgruppo/oppia,directorlive/oppia,CMDann/oppia,asandyz/oppia,gale320/oppia,souravbadami/oppia,cleophasmashiri/oppia,virajprabhu/oppia,brylie/oppia,cleophasmashiri/oppia,amgowano/oppia,sarahfo/oppia,bjvoth/oppia,sunu/oh-missions-oppia-beta,dippatel1994/oppia,prasanna08/oppia,brylie/oppia,himanshu-dixit/oppia,edallison/oppia,mit0110/oppia,zgchizi/oppia-uc,DewarM/oppia,anthkris/oppia,infinyte/oppia,DewarM/oppia,edallison/oppia,cleophasmashiri/oppia,himanshu-dixit/oppia,sanyaade-teachings/oppia,dippatel1994/oppia,sarahfo/oppia,michaelWagner/oppia,amgowano/oppia,bjvoth/oppia,sanyaade-teachings/oppia,amgowano/oppia,kevinlee12/oppia,shaz13/oppia,oulan/oppia,sbhowmik89/oppia,kevinlee12/oppia,zgchizi/oppia-uc,felipecocco/oppia,wangsai/oppia,openhatch/oh-missions-oppia-beta,BenHenning/oppia,MAKOSCAFEE/oppia,rackstar17/oppia,michaelWagner/oppia,sdulal/oppia,leandrotoledo/oppia,oppia/oppia,gale320/oppia,shaz13/oppia,sanyaade-teachings/oppia,virajprabhu/oppia,prasanna08/oppia,amitdeutsch/oppia,kingctan/oppia,himanshu-dixit/oppia,rackstar17/oppia,sunu/oppia,MAKOSCAFEE/oppia,oppia/oppia,felipecocco/oppia,hazmatzo/oppia,sunu/oppia,VictoriaRoux/oppia,aldeka/oppia,directorlive/oppia,sdulal/oppia,shaz13/oppia,wangsai/oppia,toooooper/oppia,oulan/oppia,bjvoth/oppia,aldeka/oppia,zgchizi/oppia-uc,jestapinski/oppia,danieljjh/oppia,Dev4X/oppia,anthkris/oppia,Atlas-Sailed-Co/oppia,kaffeel/oppia,oppia/oppia,BenHenning/oppia,asandyz/oppia,DewarM/oppia,CMDann/oppia,won0089/oppia,VictoriaRoux/oppia,miyucy/oppia,sunu/oh-missions-oppia-beta,kennho/oppia,wangsai/oppia,fernandopinhati/oppia,oulan/oppia,terrameijar/oppia,Cgruppo/oppia,shaz13/oppia,brylie/oppia,anthkris/oppia,miyucy/oppia,souravbadami/oppia,mit0110/oppia,sarahfo/oppia,kingctan/oppia,felipecocco/oppia,openhatch/oh-missions-oppia-beta,hazmatzo/oppia,anggorodewanto/oppia,amitdeutsch/oppia,felipecocco/oppia,prasanna08/oppia,dippatel1994/oppia,sarahfo/oppia,kennho/oppia,CMDann/oppia,terrameijar/oppia,fernandopinhati/oppia,prasanna08/oppia,google-code-export/oppia,gale320/oppia,hazmatzo/oppia,leandrotoledo/oppia,sdulal/oppia,brylie/oppia,toooooper/oppia,hazmatzo/oppia,anggorodewanto/oppia,Cgruppo/oppia,gale320/oppia,sunu/oh-missions-oppia-beta,kingctan/oppia,anggorodewanto/oppia,brianrodri/oppia,MaximLich/oppia,AllanYangZhou/oppia,raju249/oppia,anggorodewanto/oppia,sbhowmik89/oppia,asandyz/oppia,sunu/oh-missions-oppia-beta,brianrodri/oppia,DewarM/oppia,hazmatzo/oppia,sbhowmik89/oppia,asandyz/oppia,asandyz/oppia,sbhowmik89/oppia,AllanYangZhou/oppia,directorlive/oppia,DewarM/oppia,whygee/oppia,Atlas-Sailed-Co/oppia,jestapinski/oppia,wangsai/oppia,amgowano/oppia,infinyte/oppia,prasanna08/oppia,brianrodri/oppia,google-code-export/oppia,raju249/oppia,VictoriaRoux/oppia,sarahfo/oppia,virajprabhu/oppia,whygee/oppia,michaelWagner/oppia,MaximLich/oppia,souravbadami/oppia,kaffeel/oppia,Dev4X/oppia,michaelWagner/oppia,rackstar17/oppia,directorlive/oppia,AllanYangZhou/oppia,cleophasmashiri/oppia,nagyistoce/oppia
python
## Code Before: """Provides a seam for transaction services.""" __author__ = 'Sean Lip' def run_in_transaction(fn, *args, **kwargs): """Run a function in a transaction.""" # TODO(sll): Actually run the function in a transaction. return fn(*args, **kwargs) ## Instruction: Add transaction support for django models. ## Code After: """Provides a seam for transaction services.""" __author__ = 'Sean Lip' from django.db import transaction def run_in_transaction(fn, *args, **kwargs): """Run a function in a transaction.""" with transaction.commit_on_success(): return fn(*args, **kwargs)
# ... existing code ... __author__ = 'Sean Lip' from django.db import transaction def run_in_transaction(fn, *args, **kwargs): """Run a function in a transaction.""" with transaction.commit_on_success(): return fn(*args, **kwargs) # ... rest of the code ...
630c823706e28e66306828d6c3001b6e3773ce90
ui/players/models.py
ui/players/models.py
from django.db import models from django.contrib.auth.models import User class Player(models.Model): user = models.OneToOneField(User) class Avatar(models.Model): player = models.ForeignKey(User) code = models.TextField()
from django.db import models from django.contrib.auth.models import User class Player(models.Model): user = models.OneToOneField(User) code = models.TextField() class Avatar(models.Model): player = models.ForeignKey(User)
Move code into player (if only for now)
Move code into player (if only for now)
Python
agpl-3.0
Spycho/aimmo,Spycho/aimmo,Spycho/aimmo,Spycho/aimmo
python
## Code Before: from django.db import models from django.contrib.auth.models import User class Player(models.Model): user = models.OneToOneField(User) class Avatar(models.Model): player = models.ForeignKey(User) code = models.TextField() ## Instruction: Move code into player (if only for now) ## Code After: from django.db import models from django.contrib.auth.models import User class Player(models.Model): user = models.OneToOneField(User) code = models.TextField() class Avatar(models.Model): player = models.ForeignKey(User)
// ... existing code ... class Player(models.Model): user = models.OneToOneField(User) code = models.TextField() class Avatar(models.Model): player = models.ForeignKey(User) // ... rest of the code ...
ec771b7186065443e282be84fbeda5897caba913
buildbot_travis/steps/base.py
buildbot_travis/steps/base.py
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step which can be tuned by changing settings in .travis.yml """ @defer.inlineCallbacks def getStepConfig(self): config = TravisYml() struct = self.build.getProperty(".travis.yml", None) if struct: config.parse(struct) defer.returnValue(config) log = self.addLog(".travis.yml") cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"]) cmd.useLog(log, False, "stdio") yield self.runCommand(cmd) self.cmd = None if cmd.rc != 0: raise buildstep.BuildStepFailed() config = TravisYml() config.parse(log.getText()) self.build.setProperty(".travis.yml", config.config, ".VCS") defer.returnValue(config)
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step which can be tuned by changing settings in .travis.yml """ @defer.inlineCallbacks def getStepConfig(self): log = self.addLog(".travis.yml") cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"]) cmd.useLog(log, False, "stdio") yield self.runCommand(cmd) self.cmd = None if cmd.rc != 0: raise buildstep.BuildStepFailed() config = TravisYml() config.parse(log.getText()) defer.returnValue(config)
Revert "Save .travis.yml into build properties"
Revert "Save .travis.yml into build properties" The data is > 1024 so no dice. This reverts commit 10960fd1465afb8de92e8fd35b1affca4f950e27.
Python
unknown
tardyp/buildbot_travis,tardyp/buildbot_travis,isotoma/buildbot_travis,tardyp/buildbot_travis,buildbot/buildbot_travis,buildbot/buildbot_travis,buildbot/buildbot_travis,tardyp/buildbot_travis,isotoma/buildbot_travis
python
## Code Before: from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step which can be tuned by changing settings in .travis.yml """ @defer.inlineCallbacks def getStepConfig(self): config = TravisYml() struct = self.build.getProperty(".travis.yml", None) if struct: config.parse(struct) defer.returnValue(config) log = self.addLog(".travis.yml") cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"]) cmd.useLog(log, False, "stdio") yield self.runCommand(cmd) self.cmd = None if cmd.rc != 0: raise buildstep.BuildStepFailed() config = TravisYml() config.parse(log.getText()) self.build.setProperty(".travis.yml", config.config, ".VCS") defer.returnValue(config) ## Instruction: Revert "Save .travis.yml into build properties" The data is > 1024 so no dice. This reverts commit 10960fd1465afb8de92e8fd35b1affca4f950e27. ## Code After: from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step which can be tuned by changing settings in .travis.yml """ @defer.inlineCallbacks def getStepConfig(self): log = self.addLog(".travis.yml") cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"]) cmd.useLog(log, False, "stdio") yield self.runCommand(cmd) self.cmd = None if cmd.rc != 0: raise buildstep.BuildStepFailed() config = TravisYml() config.parse(log.getText()) defer.returnValue(config)
... @defer.inlineCallbacks def getStepConfig(self): log = self.addLog(".travis.yml") cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"]) cmd.useLog(log, False, "stdio") ... config = TravisYml() config.parse(log.getText()) defer.returnValue(config) ...
db90ca4e9d32cd1c42654cccbe2350fa90421dbb
src/test/java/org/codehaus/plexus/util/ContextMapAdapterTest.java
src/test/java/org/codehaus/plexus/util/ContextMapAdapterTest.java
package org.codehaus.plexus.util; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.io.StringReader; import java.io.StringWriter; import org.codehaus.plexus.context.DefaultContext; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. * Please see www.junitdoclet.org, www.gnu.org and www.objectfab.de for * informations about the tool, the licence and the authors. */ public class ContextMapAdapterTest extends TestCase { public ContextMapAdapterTest( String name ) { super( name ); } public void testInterpolation() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "occupation", "exotic dancer" ); ContextMapAdapter adapter = new ContextMapAdapter( context ); assertEquals( "jason", (String) adapter.get( "name" ) ); assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); assertNull( adapter.get( "foo") ); } }
package org.codehaus.plexus.util; import java.io.StringReader; import java.io.StringWriter; import junit.framework.TestCase; import org.codehaus.plexus.context.DefaultContext; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. * Please see www.junitdoclet.org, www.gnu.org and www.objectfab.de for * informations about the tool, the licence and the authors. */ public class ContextMapAdapterTest extends TestCase { public ContextMapAdapterTest( String name ) { super( name ); } public void testInterpolation() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "occupation", "exotic dancer" ); ContextMapAdapter adapter = new ContextMapAdapter( context ); assertEquals( "jason", (String) adapter.get( "name" ) ); assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); assertNull( adapter.get( "foo") ); } public void testInterpolationWithContext() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "noun", "asshole" ); String foo = "${name} is an ${noun}. ${not.interpolated}"; InterpolationFilterReader reader = new InterpolationFilterReader( new StringReader( foo ), new ContextMapAdapter( context ) ); StringWriter writer = new StringWriter(); IOUtil.copy( reader, writer ); String bar = writer.toString(); assertEquals( "jason is an asshole. ${not.interpolated}", bar ); } }
Add test from InterpolationFilterReaderTest, removing circular dependency.
Add test from InterpolationFilterReaderTest, removing circular dependency.
Java
apache-2.0
codehaus-plexus/plexus-utils,codehaus-plexus/plexus-utils,codehaus-plexus/plexus-utils
java
## Code Before: package org.codehaus.plexus.util; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.io.StringReader; import java.io.StringWriter; import org.codehaus.plexus.context.DefaultContext; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. * Please see www.junitdoclet.org, www.gnu.org and www.objectfab.de for * informations about the tool, the licence and the authors. */ public class ContextMapAdapterTest extends TestCase { public ContextMapAdapterTest( String name ) { super( name ); } public void testInterpolation() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "occupation", "exotic dancer" ); ContextMapAdapter adapter = new ContextMapAdapter( context ); assertEquals( "jason", (String) adapter.get( "name" ) ); assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); assertNull( adapter.get( "foo") ); } } ## Instruction: Add test from InterpolationFilterReaderTest, removing circular dependency. ## Code After: package org.codehaus.plexus.util; import java.io.StringReader; import java.io.StringWriter; import junit.framework.TestCase; import org.codehaus.plexus.context.DefaultContext; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. * Please see www.junitdoclet.org, www.gnu.org and www.objectfab.de for * informations about the tool, the licence and the authors. */ public class ContextMapAdapterTest extends TestCase { public ContextMapAdapterTest( String name ) { super( name ); } public void testInterpolation() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "occupation", "exotic dancer" ); ContextMapAdapter adapter = new ContextMapAdapter( context ); assertEquals( "jason", (String) adapter.get( "name" ) ); assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); assertNull( adapter.get( "foo") ); } public void testInterpolationWithContext() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "noun", "asshole" ); String foo = "${name} is an ${noun}. ${not.interpolated}"; InterpolationFilterReader reader = new InterpolationFilterReader( new StringReader( foo ), new ContextMapAdapter( context ) ); StringWriter writer = new StringWriter(); IOUtil.copy( reader, writer ); String bar = writer.toString(); assertEquals( "jason is an asshole. ${not.interpolated}", bar ); } }
// ... existing code ... package org.codehaus.plexus.util; import java.io.StringReader; import java.io.StringWriter; import junit.framework.TestCase; import org.codehaus.plexus.context.DefaultContext; // ... modified code ... assertNull( adapter.get( "foo") ); } public void testInterpolationWithContext() throws Exception { DefaultContext context = new DefaultContext(); context.put( "name", "jason" ); context.put( "noun", "asshole" ); String foo = "${name} is an ${noun}. ${not.interpolated}"; InterpolationFilterReader reader = new InterpolationFilterReader( new StringReader( foo ), new ContextMapAdapter( context ) ); StringWriter writer = new StringWriter(); IOUtil.copy( reader, writer ); String bar = writer.toString(); assertEquals( "jason is an asshole. ${not.interpolated}", bar ); } } // ... rest of the code ...
01847fee7faefbe50f9f7d77198f9dd0ace6c861
src/test/java/com/skraylabs/poker/ApplicationTest.java
src/test/java/com/skraylabs/poker/ApplicationTest.java
package com.skraylabs.poker; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class ApplicationTest { /** * Output stream from Application.main() for test verification. */ private ByteArrayOutputStream output; /** * Temporary reference to System.out */ private PrintStream console; @Before public void setUp() throws Exception { output = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(output)); } @After public void tearDown() throws Exception { System.setOut(console); } @Test public void testShowUsageForTooFewArguments() { // Exercise Application.main(); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_FEW_ARGS), containsString(Application.MSG_USAGE))); } @Test public void testShowUsageForTooManyArguments() { // Exercise Application.main("1", "2"); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_MANY_ARGS), containsString(Application.MSG_USAGE))); } }
package com.skraylabs.poker; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class ApplicationTest { /** * Output stream from Application.main() for test verification. */ private ByteArrayOutputStream output; /** * Temporary reference to System.out */ private PrintStream console; /** * Set up test fixture. */ @Before public void setUp() throws Exception { output = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(output)); } /** * Tear down test fixture. */ @After public void tearDown() throws Exception { System.setOut(console); } @Test public void testShowUsageForTooFewArguments() { // Exercise Application.main(); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_FEW_ARGS), containsString(Application.MSG_USAGE))); } @Test public void testShowUsageForTooManyArguments() { // Exercise Application.main("1", "2"); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_MANY_ARGS), containsString(Application.MSG_USAGE))); } }
Add some javadoc to test fixture code.
Add some javadoc to test fixture code. To make checkstyle happy.
Java
mit
AbeSkray/poker-calculator
java
## Code Before: package com.skraylabs.poker; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class ApplicationTest { /** * Output stream from Application.main() for test verification. */ private ByteArrayOutputStream output; /** * Temporary reference to System.out */ private PrintStream console; @Before public void setUp() throws Exception { output = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(output)); } @After public void tearDown() throws Exception { System.setOut(console); } @Test public void testShowUsageForTooFewArguments() { // Exercise Application.main(); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_FEW_ARGS), containsString(Application.MSG_USAGE))); } @Test public void testShowUsageForTooManyArguments() { // Exercise Application.main("1", "2"); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_MANY_ARGS), containsString(Application.MSG_USAGE))); } } ## Instruction: Add some javadoc to test fixture code. To make checkstyle happy. ## Code After: package com.skraylabs.poker; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class ApplicationTest { /** * Output stream from Application.main() for test verification. */ private ByteArrayOutputStream output; /** * Temporary reference to System.out */ private PrintStream console; /** * Set up test fixture. */ @Before public void setUp() throws Exception { output = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(output)); } /** * Tear down test fixture. */ @After public void tearDown() throws Exception { System.setOut(console); } @Test public void testShowUsageForTooFewArguments() { // Exercise Application.main(); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_FEW_ARGS), containsString(Application.MSG_USAGE))); } @Test public void testShowUsageForTooManyArguments() { // Exercise Application.main("1", "2"); // Verify String outputString = output.toString(); assertThat(outputString, allOf(containsString(Application.MSG_TOO_MANY_ARGS), containsString(Application.MSG_USAGE))); } }
... */ private PrintStream console; /** * Set up test fixture. */ @Before public void setUp() throws Exception { output = new ByteArrayOutputStream(); ... System.setOut(new PrintStream(output)); } /** * Tear down test fixture. */ @After public void tearDown() throws Exception { System.setOut(console); ...