commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
3.52k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 7
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 17
3.24k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6af918668cddf30c12a10fe46bc174e110bf04c3 | red_api.py | red_api.py | import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
})[:limit]
return list(tweets) | import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets) | Use bson's JSON util to handle ObjectIds in a JSON context | Use bson's JSON util to handle ObjectIds in a JSON context
| Python | mit | AnSavvides/redjohn,AnSavvides/redjohn | import os
+ from pymongo import DESCENDING
from pymongo import MongoClient
+ from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
- })[:limit]
+ }).sort('entry_time', DESCENDING)[:limit]
- return list(tweets)
+ return dumps(tweets) | Use bson's JSON util to handle ObjectIds in a JSON context | ## Code Before:
import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
})[:limit]
return list(tweets)
## Instruction:
Use bson's JSON util to handle ObjectIds in a JSON context
## Code After:
import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets) | // ... existing code ...
import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
// ... modified code ...
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets)
// ... rest of the code ... |
8eb0b7fcd6ffb81d6b0fc69cb31c7625550583d7 | targetrupypy.py | targetrupypy.py | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "rupypy-c"
return entry_point, None
def jitpolicy(driver):
return JitPolicy() | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "./bin/topaz"
return entry_point, None
def jitpolicy(driver):
return JitPolicy()
| Move towards a normal bin directory. | Move towards a normal bin directory.
| Python | bsd-3-clause | babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,kachick/topaz,kachick/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,kachick/topaz,topazproject/topaz,topazproject/topaz,topazproject/topaz | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
- driver.exe_name = "rupypy-c"
+ driver.exe_name = "./bin/topaz"
return entry_point, None
+
def jitpolicy(driver):
return JitPolicy()
+ | Move towards a normal bin directory. | ## Code Before:
from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "rupypy-c"
return entry_point, None
def jitpolicy(driver):
return JitPolicy()
## Instruction:
Move towards a normal bin directory.
## Code After:
from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "./bin/topaz"
return entry_point, None
def jitpolicy(driver):
return JitPolicy()
| // ... existing code ...
def target(driver, args):
driver.exe_name = "./bin/topaz"
return entry_point, None
def jitpolicy(driver):
// ... rest of the code ... |
2cc8a541814cc353e7b60767afd2128dce38918a | tests/test_plugins/test_plugin/server.py | tests/test_plugins/test_plugin/server.py |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
|
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| Fix failing python style test | Fix failing python style test
| Python | apache-2.0 | jbeezley/girder,jcfr/girder,RafaelPalomar/girder,opadron/girder,Kitware/girder,essamjoubori/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,adsorensen/girder,data-exp-lab/girder,jcfr/girder,girder/girder,opadron/girder,Xarthisius/girder,data-exp-lab/girder,jcfr/girder,kotfic/girder,manthey/girder,msmolens/girder,salamb/girder,sutartmelson/girder,adsorensen/girder,essamjoubori/girder,data-exp-lab/girder,essamjoubori/girder,chrismattmann/girder,kotfic/girder,opadron/girder,kotfic/girder,Xarthisius/girder,jcfr/girder,data-exp-lab/girder,girder/girder,opadron/girder,girder/girder,manthey/girder,salamb/girder,salamb/girder,adsorensen/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,msmolens/girder,msmolens/girder,chrismattmann/girder,essamjoubori/girder,essamjoubori/girder,Kitware/girder,jcfr/girder,Xarthisius/girder,chrismattmann/girder,RafaelPalomar/girder,adsorensen/girder,jbeezley/girder,chrismattmann/girder,sutartmelson/girder,sutartmelson/girder,RafaelPalomar/girder,RafaelPalomar/girder,kotfic/girder,sutartmelson/girder,Xarthisius/girder,Kitware/girder,jbeezley/girder,salamb/girder,manthey/girder,msmolens/girder,chrismattmann/girder,girder/girder,salamb/girder,manthey/girder,sutartmelson/girder,Kitware/girder,opadron/girder,msmolens/girder |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
- info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
+ info['serverRoot'], info['serverRoot'].girder = (
+ CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| Fix failing python style test | ## Code Before:
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
## Instruction:
Fix failing python style test
## Code After:
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| ...
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
... |
5cca245f84a87f503c8e16577b7dba635d689a26 | opencc/__main__.py | opencc/__main__.py | from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<file>',
help='Configuration file')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a configuration file.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function
import argparse
import sys
import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<conversion>',
help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a conversion.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| Add support for Python 2.6 and 2.7 | Add support for Python 2.6 and 2.7
Remove the following error when using Python 2.6 and 2.7.
TypeError: 'encoding' is an invalid keyword argument for this function
Python 3 operation is unchanged
| Python | apache-2.0 | yichen0831/opencc-python | from __future__ import print_function
import argparse
import sys
+ import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
- parser.add_argument('-c', '--config', metavar='<file>',
+ parser.add_argument('-c', '--config', metavar='<conversion>',
- help='Configuration file')
+ help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
- print("Please specify a configuration file.", file=sys.stderr)
+ print("Please specify a conversion.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
- with open(args.input if args.input else 0, encoding=args.in_enc) as f:
+ with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
- with open(args.output if args.output else 1, 'w',
+ with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| Add support for Python 2.6 and 2.7 | ## Code Before:
from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<file>',
help='Configuration file')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a configuration file.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
## Instruction:
Add support for Python 2.6 and 2.7
## Code After:
from __future__ import print_function
import argparse
import sys
import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<conversion>',
help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a conversion.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| // ... existing code ...
import argparse
import sys
import io
from opencc import OpenCC
// ... modified code ...
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<conversion>',
help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
...
if args.config is None:
print("Please specify a conversion.", file=sys.stderr)
return 1
...
cc = OpenCC(args.config)
with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
// ... rest of the code ... |
6f0a35372d625f923b9093194540cf0b0e9f054d | platformio_api/__init__.py | platformio_api/__init__.py |
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "[email protected]"
__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014-2015 Ivan Kravets"
config = dict(
SQLALCHEMY_DATABASE_URI=None,
GITHUB_LOGIN=None,
GITHUB_PASSWORD=None,
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*10,
LOGGING=dict(version=1)
)
assert "PIOAPI_CONFIG_PATH" in os.environ
with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f:
config.update(json.load(f))
# configure logging for packages
logging.basicConfig()
logging.config.dictConfig(config['LOGGING'])
# setup time zone to UTC globally
os.environ['TZ'] = "+00:00"
tzset()
|
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "[email protected]"
__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014-2015 Ivan Kravets"
config = dict(
SQLALCHEMY_DATABASE_URI=None,
GITHUB_LOGIN=None,
GITHUB_PASSWORD=None,
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb
LOGGING=dict(version=1)
)
assert "PIOAPI_CONFIG_PATH" in os.environ
with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f:
config.update(json.load(f))
# configure logging for packages
logging.basicConfig()
logging.config.dictConfig(config['LOGGING'])
# setup time zone to UTC globally
os.environ['TZ'] = "+00:00"
tzset()
| Increase repo size to 20Mb | Increase repo size to 20Mb
| Python | apache-2.0 | orgkhnargh/platformio-api,platformio/platformio-api |
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "[email protected]"
__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014-2015 Ivan Kravets"
config = dict(
SQLALCHEMY_DATABASE_URI=None,
GITHUB_LOGIN=None,
GITHUB_PASSWORD=None,
DL_PIO_DIR=None,
DL_PIO_URL=None,
- MAX_DLFILE_SIZE=1024*1024*10,
+ MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb
LOGGING=dict(version=1)
)
assert "PIOAPI_CONFIG_PATH" in os.environ
with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f:
config.update(json.load(f))
# configure logging for packages
logging.basicConfig()
logging.config.dictConfig(config['LOGGING'])
# setup time zone to UTC globally
os.environ['TZ'] = "+00:00"
tzset()
| Increase repo size to 20Mb | ## Code Before:
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "[email protected]"
__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014-2015 Ivan Kravets"
config = dict(
SQLALCHEMY_DATABASE_URI=None,
GITHUB_LOGIN=None,
GITHUB_PASSWORD=None,
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*10,
LOGGING=dict(version=1)
)
assert "PIOAPI_CONFIG_PATH" in os.environ
with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f:
config.update(json.load(f))
# configure logging for packages
logging.basicConfig()
logging.config.dictConfig(config['LOGGING'])
# setup time zone to UTC globally
os.environ['TZ'] = "+00:00"
tzset()
## Instruction:
Increase repo size to 20Mb
## Code After:
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "[email protected]"
__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014-2015 Ivan Kravets"
config = dict(
SQLALCHEMY_DATABASE_URI=None,
GITHUB_LOGIN=None,
GITHUB_PASSWORD=None,
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb
LOGGING=dict(version=1)
)
assert "PIOAPI_CONFIG_PATH" in os.environ
with open(os.environ.get("PIOAPI_CONFIG_PATH")) as f:
config.update(json.load(f))
# configure logging for packages
logging.basicConfig()
logging.config.dictConfig(config['LOGGING'])
# setup time zone to UTC globally
os.environ['TZ'] = "+00:00"
tzset()
| # ... existing code ...
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb
LOGGING=dict(version=1)
)
# ... rest of the code ... |
7a057ba74a5914f8d7f8db3646feb5cb06a74cef | ml/pytorch/image_classification/image_classifier.py | ml/pytorch/image_classification/image_classifier.py | import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A pytorch network module that will computer a forward pass
n_classes: number of output classes.
"""
self.history = []
self.n_classes = n_classes
self.net = net
# LOSS FUNCTION
if n_classes <= 2:
# Binary classification
self.loss_func = torch.nn.BCEWithLogitsLoss(weight=None)
else:
# multiclass classification
self.loss_func = torch.nn.CrossEntropyLoss(weight=None) # on logits
#self.loss_func = torch.nn.NLLLoss(weight=None) #on LogSoftmax() outputs
# OPTIMIZER
self.optimizer = None
| import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A pytorch network module that will computer a forward pass
n_classes: number of output classes.
"""
self.history = []
self.n_classes = n_classes
self.net = net
# LOSS FUNCTION
if n_classes <= 2:
# Binary classification
self.loss_func = torch.nn.BCEWithLogitsLoss(weight=None)
else:
# multiclass classification
self.loss_func = torch.nn.CrossEntropyLoss(weight=None) # on logits
#self.loss_func = torch.nn.NLLLoss(weight=None) #on LogSoftmax() outputs
# OPTIMIZER
self.optimizer = None
def set_optimizer(self, opt_func=torch.optim.Adam, **kwargs):
"""
Args:
opt_func: (function class) the optimization function creator to use
**kwargs: The keyword arguments to pass to opt_func
eg: lr=1e-3, weight_decay=0
"""
self.opt_func = opt_func
self.opt_args = kwargs
self.optimizer = opt_func(self.net.parameters(), **kwargs)
| Add set_optimizer method to pytorch ImageClassifier class | FEAT: Add set_optimizer method to pytorch ImageClassifier class
| Python | apache-2.0 | ronrest/convenience_py,ronrest/convenience_py | import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A pytorch network module that will computer a forward pass
n_classes: number of output classes.
"""
self.history = []
self.n_classes = n_classes
self.net = net
# LOSS FUNCTION
if n_classes <= 2:
# Binary classification
self.loss_func = torch.nn.BCEWithLogitsLoss(weight=None)
else:
# multiclass classification
self.loss_func = torch.nn.CrossEntropyLoss(weight=None) # on logits
#self.loss_func = torch.nn.NLLLoss(weight=None) #on LogSoftmax() outputs
# OPTIMIZER
self.optimizer = None
+ def set_optimizer(self, opt_func=torch.optim.Adam, **kwargs):
+ """
+ Args:
+ opt_func: (function class) the optimization function creator to use
+ **kwargs: The keyword arguments to pass to opt_func
+ eg: lr=1e-3, weight_decay=0
+ """
+ self.opt_func = opt_func
+ self.opt_args = kwargs
+ self.optimizer = opt_func(self.net.parameters(), **kwargs)
+ | Add set_optimizer method to pytorch ImageClassifier class | ## Code Before:
import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A pytorch network module that will computer a forward pass
n_classes: number of output classes.
"""
self.history = []
self.n_classes = n_classes
self.net = net
# LOSS FUNCTION
if n_classes <= 2:
# Binary classification
self.loss_func = torch.nn.BCEWithLogitsLoss(weight=None)
else:
# multiclass classification
self.loss_func = torch.nn.CrossEntropyLoss(weight=None) # on logits
#self.loss_func = torch.nn.NLLLoss(weight=None) #on LogSoftmax() outputs
# OPTIMIZER
self.optimizer = None
## Instruction:
Add set_optimizer method to pytorch ImageClassifier class
## Code After:
import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A pytorch network module that will computer a forward pass
n_classes: number of output classes.
"""
self.history = []
self.n_classes = n_classes
self.net = net
# LOSS FUNCTION
if n_classes <= 2:
# Binary classification
self.loss_func = torch.nn.BCEWithLogitsLoss(weight=None)
else:
# multiclass classification
self.loss_func = torch.nn.CrossEntropyLoss(weight=None) # on logits
#self.loss_func = torch.nn.NLLLoss(weight=None) #on LogSoftmax() outputs
# OPTIMIZER
self.optimizer = None
def set_optimizer(self, opt_func=torch.optim.Adam, **kwargs):
"""
Args:
opt_func: (function class) the optimization function creator to use
**kwargs: The keyword arguments to pass to opt_func
eg: lr=1e-3, weight_decay=0
"""
self.opt_func = opt_func
self.opt_args = kwargs
self.optimizer = opt_func(self.net.parameters(), **kwargs)
| # ... existing code ...
self.optimizer = None
def set_optimizer(self, opt_func=torch.optim.Adam, **kwargs):
"""
Args:
opt_func: (function class) the optimization function creator to use
**kwargs: The keyword arguments to pass to opt_func
eg: lr=1e-3, weight_decay=0
"""
self.opt_func = opt_func
self.opt_args = kwargs
self.optimizer = opt_func(self.net.parameters(), **kwargs)
# ... rest of the code ... |
6d72a1d3b4bd2e1a11e2fb9744353e5d2d9c8863 | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]),
Extension("ccomp", ["ccomp.pyx"])])
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
def cext(name):
return Extension(name, [name + ".pyx"],
include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [cext('lulu_base'), cext('ccomp')])
| Add NumPy includes dir for Cython builds. | Add NumPy includes dir for Cython builds.
| Python | bsd-3-clause | stefanv/lulu | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
+ import numpy
+
+ def cext(name):
+ return Extension(name, [name + ".pyx"],
+ include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
+ ext_modules = [cext('lulu_base'), cext('ccomp')])
- ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]),
- Extension("ccomp", ["ccomp.pyx"])])
+ | Add NumPy includes dir for Cython builds. | ## Code Before:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]),
Extension("ccomp", ["ccomp.pyx"])])
## Instruction:
Add NumPy includes dir for Cython builds.
## Code After:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
def cext(name):
return Extension(name, [name + ".pyx"],
include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [cext('lulu_base'), cext('ccomp')])
| // ... existing code ...
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
def cext(name):
return Extension(name, [name + ".pyx"],
include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [cext('lulu_base'), cext('ccomp')])
// ... rest of the code ... |
bf41f23d71491050dc79a2975b26ffe210b45505 | examples/test_contains_selector.py | examples/test_contains_selector.py | from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_text("Math Work", "#ctitle")
self.click('a:contains("Next")')
self.assert_text("Drone Fishing", "#ctitle")
| from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
self.assert_element('div div:contains("Drone Fishing")')
| Update an example that uses the ":contains()" selector | Update an example that uses the ":contains()" selector
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
- self.assert_text("Math Work", "#ctitle")
+ self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
- self.assert_text("Drone Fishing", "#ctitle")
+ self.assert_element('div div:contains("Drone Fishing")')
| Update an example that uses the ":contains()" selector | ## Code Before:
from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_text("Math Work", "#ctitle")
self.click('a:contains("Next")')
self.assert_text("Drone Fishing", "#ctitle")
## Instruction:
Update an example that uses the ":contains()" selector
## Code After:
from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
self.assert_element('div div:contains("Drone Fishing")')
| // ... existing code ...
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
self.assert_element('div div:contains("Drone Fishing")')
// ... rest of the code ... |
047483d9897e75f8284c39e8477a285763da7b37 | heufybot/modules/util/commandhandler.py | heufybot/modules/util/commandhandler.py | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessage),
("message-user", 1, self.handlePrivateMessage) ]
def handleChannelMessage(self, server, channel, user, messageBody):
message = {
"server": server,
"source": channel.name,
"channel": channel,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def handlePrivateMessage(self, server, user, messageBody):
message = {
"server": server,
"source": user.nick,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
if not message["body"].startswith(commandPrefix):
return # We don't need to be handling things that aren't bot commands
params = message["body"].split()
message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
del params[0]
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
commandHandler = CommandHandler()
| from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessage),
("message-user", 1, self.handlePrivateMessage) ]
def handleChannelMessage(self, server, channel, user, messageBody):
message = {
"server": server,
"source": channel.name,
"channel": channel,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def handlePrivateMessage(self, server, user, messageBody):
message = {
"server": server,
"source": user.nick,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
botNick = self.bot.servers[message["server"]].nick.lower()
params = message["body"].split()
if message["body"].startswith(commandPrefix):
message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
del params[0]
elif message["body"].lower().startswith(botNick):
message["command"] = params[1]
del params[0:2]
else:
return # We don't need to be handling things that aren't bot commands
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
commandHandler = CommandHandler()
| Make the bot respond to its name | Make the bot respond to its name
Implements GH-7
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessage),
("message-user", 1, self.handlePrivateMessage) ]
def handleChannelMessage(self, server, channel, user, messageBody):
message = {
"server": server,
"source": channel.name,
"channel": channel,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def handlePrivateMessage(self, server, user, messageBody):
message = {
"server": server,
"source": user.nick,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
+ botNick = self.bot.servers[message["server"]].nick.lower()
+ params = message["body"].split()
+
- if not message["body"].startswith(commandPrefix):
+ if message["body"].startswith(commandPrefix):
+ message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
+ del params[0]
+ elif message["body"].lower().startswith(botNick):
+ message["command"] = params[1]
+ del params[0:2]
+ else:
return # We don't need to be handling things that aren't bot commands
- params = message["body"].split()
- message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
- del params[0]
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
commandHandler = CommandHandler()
| Make the bot respond to its name | ## Code Before:
from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessage),
("message-user", 1, self.handlePrivateMessage) ]
def handleChannelMessage(self, server, channel, user, messageBody):
message = {
"server": server,
"source": channel.name,
"channel": channel,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def handlePrivateMessage(self, server, user, messageBody):
message = {
"server": server,
"source": user.nick,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
if not message["body"].startswith(commandPrefix):
return # We don't need to be handling things that aren't bot commands
params = message["body"].split()
message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
del params[0]
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
commandHandler = CommandHandler()
## Instruction:
Make the bot respond to its name
## Code After:
from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessage),
("message-user", 1, self.handlePrivateMessage) ]
def handleChannelMessage(self, server, channel, user, messageBody):
message = {
"server": server,
"source": channel.name,
"channel": channel,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def handlePrivateMessage(self, server, user, messageBody):
message = {
"server": server,
"source": user.nick,
"user": user,
"body": messageBody
}
self._handleCommand(message)
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
botNick = self.bot.servers[message["server"]].nick.lower()
params = message["body"].split()
if message["body"].startswith(commandPrefix):
message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
del params[0]
elif message["body"].lower().startswith(botNick):
message["command"] = params[1]
del params[0:2]
else:
return # We don't need to be handling things that aren't bot commands
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
commandHandler = CommandHandler()
| ...
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
botNick = self.bot.servers[message["server"]].nick.lower()
params = message["body"].split()
if message["body"].startswith(commandPrefix):
message["command"] = params[0][params[0].index(commandPrefix) + len(commandPrefix):]
del params[0]
elif message["body"].lower().startswith(botNick):
message["command"] = params[1]
del params[0:2]
else:
return # We don't need to be handling things that aren't bot commands
message["params"] = params
self.bot.moduleHandler.runProcessingAction("botmessage", message)
... |
262a8fe3651a4ad368fd6594cba0669267c2d225 | run_deploy_job_wr.py | run_deploy_job_wr.py | import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.format(
revision_build, job_name, build_number)
s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg')
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
revision_build,
job_name,
]
command.extend(sys.argv[2:])
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
'artifacts': {'artifacts': [
'artifacts/machine*/*log*',
'artifacts/*.jenv',
]},
'bucket': 'juju-qa-data',
}, config_file)
config_file.flush()
subprocess.check_call([
'workspace-run', config_file.name, sys.argv[1], prefix,
'--s3-config', s3_config, '-v',
])
if __name__ == '__main__':
main()
| import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.format(
revision_build, job_name, build_number)
s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg')
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
revision_build,
job_name,
]
command.extend(sys.argv[2:])
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
'artifacts': {'artifacts': [
'artifacts/machine*/*log*',
'artifacts/*.jenv',
'artifacts/*.json',
]},
'bucket': 'juju-qa-data',
}, config_file)
config_file.flush()
subprocess.check_call([
'workspace-run', config_file.name, sys.argv[1], prefix,
'--s3-config', s3_config, '-v',
])
if __name__ == '__main__':
main()
| Add *.json to the list of artifacts backed up by Workspace Runner. | Add *.json to the list of artifacts backed up by Workspace Runner. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.format(
revision_build, job_name, build_number)
s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg')
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
revision_build,
job_name,
]
command.extend(sys.argv[2:])
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
'artifacts': {'artifacts': [
'artifacts/machine*/*log*',
'artifacts/*.jenv',
+ 'artifacts/*.json',
]},
'bucket': 'juju-qa-data',
}, config_file)
config_file.flush()
subprocess.check_call([
'workspace-run', config_file.name, sys.argv[1], prefix,
'--s3-config', s3_config, '-v',
])
if __name__ == '__main__':
main()
| Add *.json to the list of artifacts backed up by Workspace Runner. | ## Code Before:
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.format(
revision_build, job_name, build_number)
s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg')
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
revision_build,
job_name,
]
command.extend(sys.argv[2:])
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
'artifacts': {'artifacts': [
'artifacts/machine*/*log*',
'artifacts/*.jenv',
]},
'bucket': 'juju-qa-data',
}, config_file)
config_file.flush()
subprocess.check_call([
'workspace-run', config_file.name, sys.argv[1], prefix,
'--s3-config', s3_config, '-v',
])
if __name__ == '__main__':
main()
## Instruction:
Add *.json to the list of artifacts backed up by Workspace Runner.
## Code After:
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.format(
revision_build, job_name, build_number)
s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg')
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
revision_build,
job_name,
]
command.extend(sys.argv[2:])
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
'artifacts': {'artifacts': [
'artifacts/machine*/*log*',
'artifacts/*.jenv',
'artifacts/*.json',
]},
'bucket': 'juju-qa-data',
}, config_file)
config_file.flush()
subprocess.check_call([
'workspace-run', config_file.name, sys.argv[1], prefix,
'--s3-config', s3_config, '-v',
])
if __name__ == '__main__':
main()
| // ... existing code ...
'artifacts/machine*/*log*',
'artifacts/*.jenv',
'artifacts/*.json',
]},
'bucket': 'juju-qa-data',
// ... rest of the code ... |
9c2951d794bb27952606cae77da1ebcd0d651e72 | aiodownload/api.py | aiodownload/api.py |
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url_map or _url_map
download = download or AioDownload()
tasks = []
for i in iterable:
url = url_map(i)
info = None if i == url else i
tasks.append(
download._loop.create_task(
AioDownload(url, info=info)
)
)
for task_set in download._loop.run_until_complete(asyncio.wait(tasks)):
for task in task_set:
yield task.result()
def _url_map(x):
return str(x)
|
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url_map or _url_map
download = download or AioDownload()
tasks = []
for i in iterable:
url = url_map(i)
info = None if i == url else i
tasks.append(
download._loop.create_task(
download.main(AioDownloadBundle(url, info=info))
)
)
for task_set in download._loop.run_until_complete(asyncio.wait(tasks)):
for task in task_set:
yield task.result()
def _url_map(x):
return str(x)
| Fix - needed to provide create_task a function, not a class | Fix - needed to provide create_task a function, not a class
| Python | mit | jelloslinger/aiodownload |
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url_map or _url_map
download = download or AioDownload()
tasks = []
for i in iterable:
url = url_map(i)
info = None if i == url else i
tasks.append(
download._loop.create_task(
- AioDownload(url, info=info)
+ download.main(AioDownloadBundle(url, info=info))
)
)
for task_set in download._loop.run_until_complete(asyncio.wait(tasks)):
for task in task_set:
yield task.result()
def _url_map(x):
return str(x)
| Fix - needed to provide create_task a function, not a class | ## Code Before:
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url_map or _url_map
download = download or AioDownload()
tasks = []
for i in iterable:
url = url_map(i)
info = None if i == url else i
tasks.append(
download._loop.create_task(
AioDownload(url, info=info)
)
)
for task_set in download._loop.run_until_complete(asyncio.wait(tasks)):
for task in task_set:
yield task.result()
def _url_map(x):
return str(x)
## Instruction:
Fix - needed to provide create_task a function, not a class
## Code After:
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url_map or _url_map
download = download or AioDownload()
tasks = []
for i in iterable:
url = url_map(i)
info = None if i == url else i
tasks.append(
download._loop.create_task(
download.main(AioDownloadBundle(url, info=info))
)
)
for task_set in download._loop.run_until_complete(asyncio.wait(tasks)):
for task in task_set:
yield task.result()
def _url_map(x):
return str(x)
| # ... existing code ...
tasks.append(
download._loop.create_task(
download.main(AioDownloadBundle(url, info=info))
)
)
# ... rest of the code ... |
b3b67fe0e68423fc2f85bccf1f20acdb779a38ba | pylxd/deprecated/tests/utils.py | pylxd/deprecated/tests/utils.py |
from pylxd import api
from pylxd import exceptions as lxd_exceptions
def upload_image(image):
alias = "{}/{}/{}/{}".format(
image["os"], image["release"], image["arch"], image["variant"]
)
lxd = api.API()
imgs = api.API(host="images.linuxcontainers.org")
d = imgs.alias_show(alias)
meta = d[1]["metadata"]
tgt = meta["target"]
try:
lxd.alias_update(meta)
except lxd_exceptions.APIError as ex:
if ex.status_code == 404:
lxd.alias_create(meta)
return tgt
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
|
from pylxd import api
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
| Remove unused testing utility function | Remove unused testing utility function
Signed-off-by: Dougal Matthews <[email protected]>
| Python | apache-2.0 | lxc/pylxd,lxc/pylxd |
from pylxd import api
- from pylxd import exceptions as lxd_exceptions
-
-
- def upload_image(image):
- alias = "{}/{}/{}/{}".format(
- image["os"], image["release"], image["arch"], image["variant"]
- )
- lxd = api.API()
- imgs = api.API(host="images.linuxcontainers.org")
- d = imgs.alias_show(alias)
-
- meta = d[1]["metadata"]
- tgt = meta["target"]
-
- try:
- lxd.alias_update(meta)
- except lxd_exceptions.APIError as ex:
- if ex.status_code == 404:
- lxd.alias_create(meta)
-
- return tgt
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
| Remove unused testing utility function | ## Code Before:
from pylxd import api
from pylxd import exceptions as lxd_exceptions
def upload_image(image):
alias = "{}/{}/{}/{}".format(
image["os"], image["release"], image["arch"], image["variant"]
)
lxd = api.API()
imgs = api.API(host="images.linuxcontainers.org")
d = imgs.alias_show(alias)
meta = d[1]["metadata"]
tgt = meta["target"]
try:
lxd.alias_update(meta)
except lxd_exceptions.APIError as ex:
if ex.status_code == 404:
lxd.alias_create(meta)
return tgt
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
## Instruction:
Remove unused testing utility function
## Code After:
from pylxd import api
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
| # ... existing code ...
from pylxd import api
# ... rest of the code ... |
c24dc7db961b03c947a98454fc3e8655c5f938ff | functional_tests/test_all_users.py | functional_tests/test_all_users.py | from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return "{0}{1}".format(self.live_server_url, reverse(namespace))
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("Alert", self.browser.title)
def test_h1_css(self):
self.browser.get(self.get_full_url("home"))
h1 = self.browser.find_element_by_tag_name("h1")
self.assertIn(h1.value_of_css_property(
"color"), "rgba(200, 50, 255, 1)")
def test_home_files(self):
self.browser.get(self.live_server_url + "/robots.txt")
self.assertNotIn("Not Found", self.browser.title)
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
def test_localization(self):
today = date.today()
self.browser.get(self.get_full_url("home"))
local_date = self.browser.find_element_by_id("local-date")
self.assertEqual(formats.date_format(
today, use_l10n=True), local_date.text)
| from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return "{0}{1}".format(self.live_server_url, reverse(namespace))
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("Alert", self.browser.title)
def test_h2_css(self):
self.browser.get(self.get_full_url("home"))
h2 = self.browser.find_element_by_tag_name("h2")
self.assertIn(h2.value_of_css_property(
"color"), "rgba(0, 0, 0, 1)")
def test_home_files(self):
self.browser.get(self.live_server_url + "/robots.txt")
self.assertNotIn("Not Found", self.browser.title)
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
| Fix css and heading test also removed localization test as no longer required | Fix css and heading test also removed localization test as no longer required
| Python | mit | iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert | from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return "{0}{1}".format(self.live_server_url, reverse(namespace))
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("Alert", self.browser.title)
- def test_h1_css(self):
+ def test_h2_css(self):
self.browser.get(self.get_full_url("home"))
- h1 = self.browser.find_element_by_tag_name("h1")
+ h2 = self.browser.find_element_by_tag_name("h2")
- self.assertIn(h1.value_of_css_property(
+ self.assertIn(h2.value_of_css_property(
- "color"), "rgba(200, 50, 255, 1)")
+ "color"), "rgba(0, 0, 0, 1)")
def test_home_files(self):
self.browser.get(self.live_server_url + "/robots.txt")
self.assertNotIn("Not Found", self.browser.title)
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
- def test_localization(self):
- today = date.today()
- self.browser.get(self.get_full_url("home"))
- local_date = self.browser.find_element_by_id("local-date")
- self.assertEqual(formats.date_format(
- today, use_l10n=True), local_date.text)
- | Fix css and heading test also removed localization test as no longer required | ## Code Before:
from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return "{0}{1}".format(self.live_server_url, reverse(namespace))
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("Alert", self.browser.title)
def test_h1_css(self):
self.browser.get(self.get_full_url("home"))
h1 = self.browser.find_element_by_tag_name("h1")
self.assertIn(h1.value_of_css_property(
"color"), "rgba(200, 50, 255, 1)")
def test_home_files(self):
self.browser.get(self.live_server_url + "/robots.txt")
self.assertNotIn("Not Found", self.browser.title)
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
def test_localization(self):
today = date.today()
self.browser.get(self.get_full_url("home"))
local_date = self.browser.find_element_by_id("local-date")
self.assertEqual(formats.date_format(
today, use_l10n=True), local_date.text)
## Instruction:
Fix css and heading test also removed localization test as no longer required
## Code After:
from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return "{0}{1}".format(self.live_server_url, reverse(namespace))
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("Alert", self.browser.title)
def test_h2_css(self):
self.browser.get(self.get_full_url("home"))
h2 = self.browser.find_element_by_tag_name("h2")
self.assertIn(h2.value_of_css_property(
"color"), "rgba(0, 0, 0, 1)")
def test_home_files(self):
self.browser.get(self.live_server_url + "/robots.txt")
self.assertNotIn("Not Found", self.browser.title)
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
| # ... existing code ...
self.assertIn("Alert", self.browser.title)
def test_h2_css(self):
self.browser.get(self.get_full_url("home"))
h2 = self.browser.find_element_by_tag_name("h2")
self.assertIn(h2.value_of_css_property(
"color"), "rgba(0, 0, 0, 1)")
def test_home_files(self):
# ... modified code ...
self.browser.get(self.live_server_url + "/humans.txt")
self.assertNotIn("Not Found", self.browser.title)
# ... rest of the code ... |
5748b1a7dc4a5be3b2b9da9959eabe586347078a | tensorflow_federated/python/program/value_reference.py | tensorflow_federated/python/program/value_reference.py | """Defines the abstract interface for classes that reference values."""
import abc
from typing import Any
from tensorflow_federated.python.core.impl.types import typed_object
class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface for classes that reference values.
This interfaces provides the capability to maniplutate values without
requiring them to be materialized as Python objects.
"""
@abc.abstractmethod
def get_value(self) -> Any:
pass
|
import abc
from typing import Union
import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface representing references to server placed values."""
@abc.abstractmethod
def get_value(self) -> Union[np.generic, np.ndarray]:
"""Returns the referenced value as a numpy scalar or array."""
raise NotImplementedError
| Update the Value Reference API to be more precise about the types of values being referenced. | Update the Value Reference API to be more precise about the types of values being referenced.
PiperOrigin-RevId: 404647934
| Python | apache-2.0 | tensorflow/federated,tensorflow/federated,tensorflow/federated | - """Defines the abstract interface for classes that reference values."""
import abc
- from typing import Any
+ from typing import Union
+
+ import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
- class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
+ class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
+ """An abstract interface representing references to server placed values."""
- """An abstract interface for classes that reference values.
-
- This interfaces provides the capability to maniplutate values without
- requiring them to be materialized as Python objects.
- """
@abc.abstractmethod
- def get_value(self) -> Any:
- pass
+ def get_value(self) -> Union[np.generic, np.ndarray]:
+ """Returns the referenced value as a numpy scalar or array."""
+ raise NotImplementedError
| Update the Value Reference API to be more precise about the types of values being referenced. | ## Code Before:
"""Defines the abstract interface for classes that reference values."""
import abc
from typing import Any
from tensorflow_federated.python.core.impl.types import typed_object
class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface for classes that reference values.
This interfaces provides the capability to maniplutate values without
requiring them to be materialized as Python objects.
"""
@abc.abstractmethod
def get_value(self) -> Any:
pass
## Instruction:
Update the Value Reference API to be more precise about the types of values being referenced.
## Code After:
import abc
from typing import Union
import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface representing references to server placed values."""
@abc.abstractmethod
def get_value(self) -> Union[np.generic, np.ndarray]:
"""Returns the referenced value as a numpy scalar or array."""
raise NotImplementedError
| ...
import abc
from typing import Union
import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
...
class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface representing references to server placed values."""
@abc.abstractmethod
def get_value(self) -> Union[np.generic, np.ndarray]:
"""Returns the referenced value as a numpy scalar or array."""
raise NotImplementedError
... |
b9b4089fcd7f26ebf339c568ba6454d538a1813e | zk_shell/cli.py | zk_shell/cli.py | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| Handle IOError in run_once mode so paging works | Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <[email protected]>
| Python | apache-2.0 | harlowja/zk_shell,harlowja/zk_shell,rgs1/zk_shell,rgs1/zk_shell | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
+ try:
- sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ except IOError:
+ sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| Handle IOError in run_once mode so paging works | ## Code Before:
from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
## Instruction:
Handle IOError in run_once mode so paging works
## Code After:
from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| ...
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
... |
8090fa9c072656497ff383e9b76d49af2955e420 | examples/hopv/hopv_graph_conv.py | examples/hopv/hopv_graph_conv.py | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvTensorGraph(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
| from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
| Fix GraphConvTensorGraph to GraphConvModel in hopv example | Fix GraphConvTensorGraph to GraphConvModel in hopv example
| Python | mit | Agent007/deepchem,lilleswing/deepchem,lilleswing/deepchem,Agent007/deepchem,peastman/deepchem,miaecle/deepchem,peastman/deepchem,ktaneishi/deepchem,miaecle/deepchem,Agent007/deepchem,deepchem/deepchem,ktaneishi/deepchem,deepchem/deepchem,ktaneishi/deepchem,miaecle/deepchem,lilleswing/deepchem | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
- from models import GraphConvTensorGraph
+ from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
- model = GraphConvTensorGraph(
+ model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
| Fix GraphConvTensorGraph to GraphConvModel in hopv example | ## Code Before:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvTensorGraph(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
## Instruction:
Fix GraphConvTensorGraph to GraphConvModel in hopv example
## Code After:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = hopv_datasets
# Fit models
metric = [
dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
dc.metrics.Metric(
dc.metrics.mean_absolute_error, np.mean, mode="regression")
]
# Number of features on conv-mols
n_feat = 75
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
# Fit trained model
model.fit(train_dataset, nb_epoch=25)
print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
| // ... existing code ...
import numpy as np
from models import GraphConvModel
np.random.seed(123)
// ... modified code ...
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
// ... rest of the code ... |
c1b97bbc6fc0603c0f2a809175edf88cd1e4a207 | setup.py | setup.py | from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.5.1',
author="Yuji Ikeda",
author_email="[email protected]",
packages=packages,
scripts=scripts,
install_requires=['numpy'])
| from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.5.1',
author="Yuji Ikeda",
author_email="[email protected]",
packages=packages,
scripts=scripts,
install_requires=['numpy', 'h5py', 'phonopy'])
| Add requirement of h5py and phonopy | Add requirement of h5py and phonopy
| Python | mit | yuzie007/ph_unfolder,yuzie007/upho | from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.5.1',
author="Yuji Ikeda",
author_email="[email protected]",
packages=packages,
scripts=scripts,
- install_requires=['numpy'])
+ install_requires=['numpy', 'h5py', 'phonopy'])
| Add requirement of h5py and phonopy | ## Code Before:
from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.5.1',
author="Yuji Ikeda",
author_email="[email protected]",
packages=packages,
scripts=scripts,
install_requires=['numpy'])
## Instruction:
Add requirement of h5py and phonopy
## Code After:
from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.5.1',
author="Yuji Ikeda",
author_email="[email protected]",
packages=packages,
scripts=scripts,
install_requires=['numpy', 'h5py', 'phonopy'])
| // ... existing code ...
packages=packages,
scripts=scripts,
install_requires=['numpy', 'h5py', 'phonopy'])
// ... rest of the code ... |
9217bfc6bab0d152e33d9fda60218c404b61d064 | cmd2/__init__.py | cmd2/__init__.py | from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| Add EmptyStatement exception to default imports | Add EmptyStatement exception to default imports
| Python | mit | python-cmd2/cmd2,python-cmd2/cmd2 | - from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
+ from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| Add EmptyStatement exception to default imports | ## Code Before:
from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
## Instruction:
Add EmptyStatement exception to default imports
## Code After:
from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| // ... existing code ...
from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
// ... rest of the code ... |
dd8c85a49a31693f43e6f6877a0657d63cbc1b01 | auth0/v2/device_credentials.py | auth0/v2/device_credentials.py | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id=None, client_id=None, type=None,
fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| Remove default arguments for user_id, client_id and type | Remove default arguments for user_id, client_id and type
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
+ def get(self, user_id, client_id, type, fields=[], include_fields=True):
- def get(self, user_id=None, client_id=None, type=None,
- fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| Remove default arguments for user_id, client_id and type | ## Code Before:
from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id=None, client_id=None, type=None,
fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
## Instruction:
Remove default arguments for user_id, client_id and type
## Code After:
from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| // ... existing code ...
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
// ... rest of the code ... |
3e98ed8801d380b6ab40156b1f20a1f9fe23a755 | books/views.py | books/views.py | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.all()
serializer_class = BookPageSerializer
| from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer
| Order book pages by page number. | Order book pages by page number.
| Python | mit | Pepedou/Famas | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
- queryset = BookPage.objects.all()
+ queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer
| Order book pages by page number. | ## Code Before:
from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.all()
serializer_class = BookPageSerializer
## Instruction:
Order book pages by page number.
## Code After:
from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer
| // ... existing code ...
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer
// ... rest of the code ... |
d7ebf5c6db9b73133915aabb3dbd9c5b283f9982 | ooni/tests/test_trueheaders.py | ooni/tests/test_trueheaders.py | from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['ValueA', 'ValueB'],
}
dummy_headers_dict3 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header4': ['ValueA', 'ValueB'],
}
class TestTrueHeaders(unittest.TestCase):
def test_names_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set())
def test_names_not_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3']))
th = TrueHeaders(dummy_headers_dict3)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4']))
def test_names_match_expect_ignore(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
| from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['ValueA', 'ValueB'],
}
dummy_headers_dict3 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header4': ['ValueA', 'ValueB'],
}
class TestTrueHeaders(unittest.TestCase):
def test_names_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set())
def test_names_not_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3']))
th = TrueHeaders(dummy_headers_dict3)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4']))
def test_names_match_expect_ignore(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
| Fix unittest for true headers.. | Fix unittest for true headers..
| Python | bsd-2-clause | kdmurray91/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe | from twisted.trial import unittest
- from ooni.utils.txagentwithsocks import TrueHeaders
+ from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['ValueA', 'ValueB'],
}
dummy_headers_dict3 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header4': ['ValueA', 'ValueB'],
}
class TestTrueHeaders(unittest.TestCase):
def test_names_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set())
def test_names_not_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3']))
th = TrueHeaders(dummy_headers_dict3)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4']))
def test_names_match_expect_ignore(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
| Fix unittest for true headers.. | ## Code Before:
from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['ValueA', 'ValueB'],
}
dummy_headers_dict3 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header4': ['ValueA', 'ValueB'],
}
class TestTrueHeaders(unittest.TestCase):
def test_names_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set())
def test_names_not_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3']))
th = TrueHeaders(dummy_headers_dict3)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4']))
def test_names_match_expect_ignore(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
## Instruction:
Fix unittest for true headers..
## Code After:
from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['ValueA', 'ValueB'],
}
dummy_headers_dict3 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header4': ['ValueA', 'ValueB'],
}
class TestTrueHeaders(unittest.TestCase):
def test_names_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict)), set())
def test_names_not_match(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3']))
th = TrueHeaders(dummy_headers_dict3)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2)), set(['Header3', 'Header4']))
def test_names_match_expect_ignore(self):
th = TrueHeaders(dummy_headers_dict)
self.assertEqual(th.getDiff(TrueHeaders(dummy_headers_dict2), ignore=['Header3']), set())
| # ... existing code ...
from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
# ... rest of the code ... |
5b7a1a40ea43834feb5563f566d07bd5b31c589d | tests/test-recipes/metadata/always_include_files_glob/run_test.py | tests/test-recipes/metadata/always_include_files_glob/run_test.py | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
if __name__ == '__main__':
main()
| import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
main()
| Add error messages to the asserts | Add error messages to the asserts
| Python | bsd-3-clause | ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,ilastik/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,frol/conda-build,frol/conda-build | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
- assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
+ assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
- assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
+ assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
main()
| Add error messages to the asserts | ## Code Before:
import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
if __name__ == '__main__':
main()
## Instruction:
Add error messages to the asserts
## Code After:
import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
main()
| # ... existing code ...
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
# ... rest of the code ... |
08812c8507fac2c57bd143dd7aad4c54d5c0aa75 | panoptes_client/user.py | panoptes_client/user.py | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
@classmethod
def where(cls, **kwargs):
email = kwargs.get('email')
if not email:
for user in super(User, cls).where(**kwargs):
yield user
return
if not isiterable(email):
email = [email]
for batch in split(email, 50):
kwargs['email'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
@property
def avatar(self):
"""
A dict containing metadata about the user's avatar.
"""
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
| from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
@classmethod
def where(cls, **kwargs):
email = kwargs.get('email')
login = kwargs.get('login')
if email and login:
raise ValueError(
'Queries are supported on at most ONE of email and login'
)
if email:
if not isiterable(email):
email = [email]
for batch in split(email, 50):
kwargs['email'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
elif login:
if not isiterable(login):
login = [login]
for batch in split(login, 50):
kwargs['login'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
else:
for user in super(User, cls).where(**kwargs):
yield user
@property
def avatar(self):
"""
A dict containing metadata about the user's avatar.
"""
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
| Allow batched User lookups by login name | Allow batched User lookups by login name
| Python | apache-2.0 | zooniverse/panoptes-python-client | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
@classmethod
def where(cls, **kwargs):
email = kwargs.get('email')
+ login = kwargs.get('login')
- if not email:
- for user in super(User, cls).where(**kwargs):
- yield user
- return
- if not isiterable(email):
- email = [email]
+ if email and login:
+ raise ValueError(
+ 'Queries are supported on at most ONE of email and login'
+ )
+ if email:
+ if not isiterable(email):
+ email = [email]
+
- for batch in split(email, 50):
+ for batch in split(email, 50):
- kwargs['email'] = ",".join(batch)
+ kwargs['email'] = ",".join(batch)
+ for user in super(User, cls).where(**kwargs):
+ yield user
+
+ elif login:
+ if not isiterable(login):
+ login = [login]
+
+ for batch in split(login, 50):
+ kwargs['login'] = ",".join(batch)
+ for user in super(User, cls).where(**kwargs):
+ yield user
+
+ else:
for user in super(User, cls).where(**kwargs):
yield user
@property
def avatar(self):
"""
A dict containing metadata about the user's avatar.
"""
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
| Allow batched User lookups by login name | ## Code Before:
from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
@classmethod
def where(cls, **kwargs):
email = kwargs.get('email')
if not email:
for user in super(User, cls).where(**kwargs):
yield user
return
if not isiterable(email):
email = [email]
for batch in split(email, 50):
kwargs['email'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
@property
def avatar(self):
"""
A dict containing metadata about the user's avatar.
"""
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
## Instruction:
Allow batched User lookups by login name
## Code After:
from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
@classmethod
def where(cls, **kwargs):
email = kwargs.get('email')
login = kwargs.get('login')
if email and login:
raise ValueError(
'Queries are supported on at most ONE of email and login'
)
if email:
if not isiterable(email):
email = [email]
for batch in split(email, 50):
kwargs['email'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
elif login:
if not isiterable(login):
login = [login]
for batch in split(login, 50):
kwargs['login'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
else:
for user in super(User, cls).where(**kwargs):
yield user
@property
def avatar(self):
"""
A dict containing metadata about the user's avatar.
"""
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
| // ... existing code ...
def where(cls, **kwargs):
email = kwargs.get('email')
login = kwargs.get('login')
if email and login:
raise ValueError(
'Queries are supported on at most ONE of email and login'
)
if email:
if not isiterable(email):
email = [email]
for batch in split(email, 50):
kwargs['email'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
elif login:
if not isiterable(login):
login = [login]
for batch in split(login, 50):
kwargs['login'] = ",".join(batch)
for user in super(User, cls).where(**kwargs):
yield user
else:
for user in super(User, cls).where(**kwargs):
yield user
// ... rest of the code ... |
6caca3259f4ec8f298b1d35f15e4492efbcff6b1 | tests/basics/dict1.py | tests/basics/dict1.py |
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality operator on dicts of same size but with different keys
print({1:1} == {2:1})
# value not found
try:
{}[0]
except KeyError:
print('KeyError')
# unsupported unary op
try:
+{}
except TypeError:
print('TypeError')
# unsupported binary op
try:
{} + {}
except TypeError:
print('TypeError')
|
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality operator on dicts of same size but with different keys
print({1:1} == {2:1})
# value not found
try:
{}[0]
except KeyError as er:
print('KeyError', er, repr(er), er.args)
# unsupported unary op
try:
+{}
except TypeError:
print('TypeError')
# unsupported binary op
try:
{} + {}
except TypeError:
print('TypeError')
| Add test to print full KeyError exc from failed dict lookup. | tests: Add test to print full KeyError exc from failed dict lookup.
| Python | mit | jmarcelino/pycom-micropython,alex-march/micropython,hiway/micropython,AriZuu/micropython,chrisdearman/micropython,kerneltask/micropython,jmarcelino/pycom-micropython,selste/micropython,tuc-osg/micropython,blazewicz/micropython,oopy/micropython,ryannathans/micropython,micropython/micropython-esp32,trezor/micropython,infinnovation/micropython,MrSurly/micropython,puuu/micropython,adafruit/micropython,torwag/micropython,pfalcon/micropython,micropython/micropython-esp32,AriZuu/micropython,ryannathans/micropython,pozetroninc/micropython,tuc-osg/micropython,pozetroninc/micropython,cwyark/micropython,dmazzella/micropython,pramasoul/micropython,tobbad/micropython,lowRISC/micropython,HenrikSolver/micropython,TDAbboud/micropython,pramasoul/micropython,infinnovation/micropython,puuu/micropython,blazewicz/micropython,SHA2017-badge/micropython-esp32,infinnovation/micropython,selste/micropython,AriZuu/micropython,adafruit/micropython,swegener/micropython,mhoffma/micropython,adafruit/circuitpython,mhoffma/micropython,oopy/micropython,deshipu/micropython,trezor/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,tobbad/micropython,ryannathans/micropython,tobbad/micropython,bvernoux/micropython,chrisdearman/micropython,pozetroninc/micropython,blazewicz/micropython,HenrikSolver/micropython,hiway/micropython,torwag/micropython,ryannathans/micropython,AriZuu/micropython,henriknelson/micropython,henriknelson/micropython,mhoffma/micropython,dmazzella/micropython,PappaPeppar/micropython,Timmenem/micropython,mhoffma/micropython,blazewicz/micropython,infinnovation/micropython,oopy/micropython,tralamazza/micropython,dxxb/micropython,TDAbboud/micropython,puuu/micropython,chrisdearman/micropython,PappaPeppar/micropython,Timmenem/micropython,alex-march/micropython,pozetroninc/micropython,TDAbboud/micropython,Peetz0r/micropython-esp32,HenrikSolver/micropython,pramasoul/micropython,TDAbboud/micropython,HenrikSolver/micropython,AriZuu/micropython,oopy/micropython,alex-march/micropython,pramasoul/micropython,tobbad/micropython,alex-robbins/micropython,kerneltask/micropython,pfalcon/micropython,henriknelson/micropython,pfalcon/micropython,adafruit/circuitpython,torwag/micropython,Timmenem/micropython,cwyark/micropython,tuc-osg/micropython,tuc-osg/micropython,MrSurly/micropython,toolmacher/micropython,SHA2017-badge/micropython-esp32,henriknelson/micropython,adafruit/circuitpython,pozetroninc/micropython,micropython/micropython-esp32,alex-robbins/micropython,alex-robbins/micropython,adafruit/micropython,SHA2017-badge/micropython-esp32,dmazzella/micropython,Peetz0r/micropython-esp32,puuu/micropython,swegener/micropython,dxxb/micropython,tuc-osg/micropython,adafruit/micropython,lowRISC/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,MrSurly/micropython-esp32,hosaka/micropython,bvernoux/micropython,selste/micropython,PappaPeppar/micropython,matthewelse/micropython,matthewelse/micropython,trezor/micropython,MrSurly/micropython-esp32,hiway/micropython,SHA2017-badge/micropython-esp32,MrSurly/micropython,adafruit/circuitpython,hiway/micropython,blazewicz/micropython,kerneltask/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,selste/micropython,kerneltask/micropython,MrSurly/micropython,micropython/micropython-esp32,alex-march/micropython,pfalcon/micropython,matthewelse/micropython,alex-robbins/micropython,toolmacher/micropython,puuu/micropython,toolmacher/micropython,tralamazza/micropython,torwag/micropython,hosaka/micropython,hosaka/micropython,alex-march/micropython,trezor/micropython,Timmenem/micropython,hosaka/micropython,ryannathans/micropython,swegener/micropython,jmarcelino/pycom-micropython,mhoffma/micropython,Peetz0r/micropython-esp32,dxxb/micropython,Peetz0r/micropython-esp32,swegener/micropython,toolmacher/micropython,torwag/micropython,deshipu/micropython,deshipu/micropython,adafruit/circuitpython,dxxb/micropython,lowRISC/micropython,cwyark/micropython,Timmenem/micropython,matthewelse/micropython,MrSurly/micropython-esp32,tralamazza/micropython,oopy/micropython,MrSurly/micropython,chrisdearman/micropython,dxxb/micropython,tralamazza/micropython,bvernoux/micropython,hiway/micropython,deshipu/micropython,matthewelse/micropython,toolmacher/micropython,hosaka/micropython,HenrikSolver/micropython,TDAbboud/micropython,tobbad/micropython,swegener/micropython,adafruit/circuitpython,infinnovation/micropython,cwyark/micropython,bvernoux/micropython,adafruit/micropython,trezor/micropython,MrSurly/micropython-esp32,dmazzella/micropython,lowRISC/micropython,kerneltask/micropython,SHA2017-badge/micropython-esp32,lowRISC/micropython,deshipu/micropython,chrisdearman/micropython,matthewelse/micropython,cwyark/micropython,selste/micropython,alex-robbins/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,pramasoul/micropython,bvernoux/micropython |
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality operator on dicts of same size but with different keys
print({1:1} == {2:1})
# value not found
try:
{}[0]
- except KeyError:
+ except KeyError as er:
- print('KeyError')
+ print('KeyError', er, repr(er), er.args)
# unsupported unary op
try:
+{}
except TypeError:
print('TypeError')
# unsupported binary op
try:
{} + {}
except TypeError:
print('TypeError')
| Add test to print full KeyError exc from failed dict lookup. | ## Code Before:
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality operator on dicts of same size but with different keys
print({1:1} == {2:1})
# value not found
try:
{}[0]
except KeyError:
print('KeyError')
# unsupported unary op
try:
+{}
except TypeError:
print('TypeError')
# unsupported binary op
try:
{} + {}
except TypeError:
print('TypeError')
## Instruction:
Add test to print full KeyError exc from failed dict lookup.
## Code After:
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality operator on dicts of same size but with different keys
print({1:1} == {2:1})
# value not found
try:
{}[0]
except KeyError as er:
print('KeyError', er, repr(er), er.args)
# unsupported unary op
try:
+{}
except TypeError:
print('TypeError')
# unsupported binary op
try:
{} + {}
except TypeError:
print('TypeError')
| ...
try:
{}[0]
except KeyError as er:
print('KeyError', er, repr(er), er.args)
# unsupported unary op
... |
53d5f47c828bec78e7241cb9e3d4f614dd18e6f9 | responder.py | responder.py | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)
return random.choice(excuses["excuses"])
def get_response(self):
if self.mime_type == "application/json":
return jsonify({
"excuse": self._excuse
}), "/json/"
elif self.mime_type == "application/xml":
return Response(
render_template('xml.xml', excuse=self._excuse),
mimetype='text/xml'
), "/xml/"
elif self.mime_type == "application/javascript" or "jsonp" in self.args:
return Response(
render_template('jsonp.js', excuse=self._excuse),
mimetype='application/javascript'
), "/jsonp/"
elif self.mime_type == "text/plain":
return Response("Hello world", mimetype='text/plain'), "/text/"
else:
return render_template('html.html', excuse=self._excuse), "/html/"
| import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)
return random.choice(excuses["excuses"])
def get_response(self):
if self.mime_type == "application/json":
return jsonify({
"excuse": self._excuse
}), "/json/"
elif self.mime_type == "application/xml":
return Response(
render_template('xml.xml', excuse=self._excuse),
mimetype='text/xml'
), "/xml/"
elif self.mime_type == "application/javascript" or "jsonp" in self.args:
return Response(
render_template('jsonp.js', excuse=self._excuse),
mimetype='application/javascript'
), "/jsonp/"
elif self.mime_type == "text/plain":
return Response(self._excuse, mimetype='text/plain'), "/text/"
else:
return render_template('html.html', excuse=self._excuse), "/html/"
| Fix bug with text/plain response | Fix bug with text/plain response
| Python | mit | aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)
return random.choice(excuses["excuses"])
def get_response(self):
if self.mime_type == "application/json":
return jsonify({
"excuse": self._excuse
}), "/json/"
elif self.mime_type == "application/xml":
return Response(
render_template('xml.xml', excuse=self._excuse),
mimetype='text/xml'
), "/xml/"
elif self.mime_type == "application/javascript" or "jsonp" in self.args:
return Response(
render_template('jsonp.js', excuse=self._excuse),
mimetype='application/javascript'
), "/jsonp/"
elif self.mime_type == "text/plain":
- return Response("Hello world", mimetype='text/plain'), "/text/"
+ return Response(self._excuse, mimetype='text/plain'), "/text/"
else:
return render_template('html.html', excuse=self._excuse), "/html/"
| Fix bug with text/plain response | ## Code Before:
import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)
return random.choice(excuses["excuses"])
def get_response(self):
if self.mime_type == "application/json":
return jsonify({
"excuse": self._excuse
}), "/json/"
elif self.mime_type == "application/xml":
return Response(
render_template('xml.xml', excuse=self._excuse),
mimetype='text/xml'
), "/xml/"
elif self.mime_type == "application/javascript" or "jsonp" in self.args:
return Response(
render_template('jsonp.js', excuse=self._excuse),
mimetype='application/javascript'
), "/jsonp/"
elif self.mime_type == "text/plain":
return Response("Hello world", mimetype='text/plain'), "/text/"
else:
return render_template('html.html', excuse=self._excuse), "/html/"
## Instruction:
Fix bug with text/plain response
## Code After:
import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)
return random.choice(excuses["excuses"])
def get_response(self):
if self.mime_type == "application/json":
return jsonify({
"excuse": self._excuse
}), "/json/"
elif self.mime_type == "application/xml":
return Response(
render_template('xml.xml', excuse=self._excuse),
mimetype='text/xml'
), "/xml/"
elif self.mime_type == "application/javascript" or "jsonp" in self.args:
return Response(
render_template('jsonp.js', excuse=self._excuse),
mimetype='application/javascript'
), "/jsonp/"
elif self.mime_type == "text/plain":
return Response(self._excuse, mimetype='text/plain'), "/text/"
else:
return render_template('html.html', excuse=self._excuse), "/html/"
| ...
elif self.mime_type == "text/plain":
return Response(self._excuse, mimetype='text/plain'), "/text/"
else:
... |
47ddf999dd7ef8cd7600710ad6ad7611dd55a218 | bin/testNetwork.py | bin/testNetwork.py |
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if env['GATEWAY']:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if env['IFACE']:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
|
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if 'IFACE' in env:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
| Change the config dictionary key validation | Change the config dictionary key validation
| Python | apache-2.0 | starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser |
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
- if env['GATEWAY']:
+ if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
- if env['IFACE']:
+ if 'IFACE' in env:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
| Change the config dictionary key validation | ## Code Before:
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if env['GATEWAY']:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if env['IFACE']:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
## Instruction:
Change the config dictionary key validation
## Code After:
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if 'IFACE' in env:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
| ...
GATEWAY = '192.168.1.1'
if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if 'IFACE' in env:
IFACE = env['IFACE']
... |
27d40996f0912a1b9b16afa0884f10b1504acce2 | scoring_engine/web/__init__.py | scoring_engine/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
app.register_blueprint(overview.mod)
app.register_blueprint(services.mod)
app.register_blueprint(admin.mod)
app.register_blueprint(auth.mod)
app.register_blueprint(profile.mod)
app.register_blueprint(api.mod)
app.register_blueprint(about.mod)
| import os
import logging
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
app.register_blueprint(overview.mod)
app.register_blueprint(services.mod)
app.register_blueprint(admin.mod)
app.register_blueprint(auth.mod)
app.register_blueprint(profile.mod)
app.register_blueprint(api.mod)
app.register_blueprint(about.mod)
| Use error severity for flask output | Use error severity for flask output
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | import os
+ import logging
from flask import Flask
+
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
+
+
+ log = logging.getLogger('werkzeug')
+ log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
app.register_blueprint(overview.mod)
app.register_blueprint(services.mod)
app.register_blueprint(admin.mod)
app.register_blueprint(auth.mod)
app.register_blueprint(profile.mod)
app.register_blueprint(api.mod)
app.register_blueprint(about.mod)
| Use error severity for flask output | ## Code Before:
import os
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
app.register_blueprint(overview.mod)
app.register_blueprint(services.mod)
app.register_blueprint(admin.mod)
app.register_blueprint(auth.mod)
app.register_blueprint(profile.mod)
app.register_blueprint(api.mod)
app.register_blueprint(about.mod)
## Instruction:
Use error severity for flask output
## Code After:
import os
import logging
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
app.register_blueprint(overview.mod)
app.register_blueprint(services.mod)
app.register_blueprint(admin.mod)
app.register_blueprint(auth.mod)
app.register_blueprint(profile.mod)
app.register_blueprint(api.mod)
app.register_blueprint(about.mod)
| ...
import os
import logging
from flask import Flask
app = Flask(__name__)
...
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
... |
56e3f571196bdc0ab8882f56ed66192d54ff8cad | gmt/clib/tests/test_functions.py | gmt/clib/tests/test_functions.py | import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R10/70/-3/8 -JX4i/3i -Ba -P ->tmp.ps'
session = create_session()
call_module(session, module, args)
assert os.path.exists('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
| import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R10/70/-3/8 -JX4i/3i -Ba -P ->tmp.ps'
session = create_session()
call_module(session, module, args)
assert os.path.exists('tmp.ps')
os.remove('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
| Remove tmp file created by test | Remove tmp file created by test
| Python | bsd-3-clause | GenericMappingTools/gmt-python,GenericMappingTools/gmt-python | import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R10/70/-3/8 -JX4i/3i -Ba -P ->tmp.ps'
session = create_session()
call_module(session, module, args)
assert os.path.exists('tmp.ps')
+ os.remove('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
| Remove tmp file created by test | ## Code Before:
import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R10/70/-3/8 -JX4i/3i -Ba -P ->tmp.ps'
session = create_session()
call_module(session, module, args)
assert os.path.exists('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
## Instruction:
Remove tmp file created by test
## Code After:
import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R10/70/-3/8 -JX4i/3i -Ba -P ->tmp.ps'
session = create_session()
call_module(session, module, args)
assert os.path.exists('tmp.ps')
os.remove('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
| ...
call_module(session, module, args)
assert os.path.exists('tmp.ps')
os.remove('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
... |
b16474b4523e8e804f28188ba74c992896748efe | broctl/Napatech.py | broctl/Napatech.py | import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only if there is a Napatech interface in use
for nn in self.nodes():
if nn.type == 'worker' and nn.interface.startswith('napatech::'):
return True
return False
def nodeKeys(self):
return ['dedupe_lru_size', 'host_buffer_allowance']
def options(self):
return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'),
('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')]
def broctl_config(self):
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance'))
return script
| import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only if there is a Napatech interface in use
for nn in self.nodes():
if nn.type == 'worker' and nn.interface.startswith('napatech::'):
return True
return False
def nodeKeys(self):
return ['dedupe_lru_size', 'host_buffer_allowance']
def options(self):
return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'),
('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')]
def broctl_config(self):
script = ''
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance'))
return script
| Fix minor bug in broctl plugin. | Fix minor bug in broctl plugin.
| Python | bsd-3-clause | hosom/bro-napatech,hosom/bro-napatech | import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only if there is a Napatech interface in use
for nn in self.nodes():
if nn.type == 'worker' and nn.interface.startswith('napatech::'):
return True
return False
def nodeKeys(self):
return ['dedupe_lru_size', 'host_buffer_allowance']
def options(self):
return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'),
('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')]
def broctl_config(self):
+ script = ''
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance'))
return script
| Fix minor bug in broctl plugin. | ## Code Before:
import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only if there is a Napatech interface in use
for nn in self.nodes():
if nn.type == 'worker' and nn.interface.startswith('napatech::'):
return True
return False
def nodeKeys(self):
return ['dedupe_lru_size', 'host_buffer_allowance']
def options(self):
return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'),
('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')]
def broctl_config(self):
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance'))
return script
## Instruction:
Fix minor bug in broctl plugin.
## Code After:
import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only if there is a Napatech interface in use
for nn in self.nodes():
if nn.type == 'worker' and nn.interface.startswith('napatech::'):
return True
return False
def nodeKeys(self):
return ['dedupe_lru_size', 'host_buffer_allowance']
def options(self):
return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'),
('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')]
def broctl_config(self):
script = ''
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance'))
return script
| # ... existing code ...
def broctl_config(self):
script = ''
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
# ... rest of the code ... |
9dafef749aaf2fca9e865cf28b043ea22bafe3a5 | backend/django/apps/accounts/tests.py | backend/django/apps/accounts/tests.py | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseAccount
first_name = 'John'
last_name = 'Doe'
email = '{}.{}@email.com'.format(first_name, last_name)
password = 'passjohn1'
class FactoryBoyCreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_can_create_user(self):
response = self.client.get(
reverse('_accounts:account-detail', kwargs={'pk': 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertJSONEqual(
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
| from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseAccount
first_name = 'John'
last_name = 'Doe'
email = '{}.{}@email.com'.format(first_name, last_name)
password = 'passjohn1'
class FactoryBoyCreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_can_create_user(self):
response = self.client.get(
reverse('_accounts:account-detail', kwargs={'pk': 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertJSONEqual(
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
class CreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_create_user(self):
self.user.email = '[email protected]'
data = json.dumps(WholeAccountSerializer(self.user).data)
response = self.client.post(
reverse('_accounts:account-list'),
data,
content_type='application/json')
self.assertEqual(
first=response.status_code, second=status.HTTP_201_CREATED)
| Create a test for Account creation | Create a test for Account creation
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseAccount
first_name = 'John'
last_name = 'Doe'
email = '{}.{}@email.com'.format(first_name, last_name)
password = 'passjohn1'
class FactoryBoyCreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_can_create_user(self):
response = self.client.get(
reverse('_accounts:account-detail', kwargs={'pk': 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertJSONEqual(
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
+
+ class CreateUserTest(APITestCase):
+
+ def setUp(self):
+ self.user = UserFactory()
+
+ def test_create_user(self):
+ self.user.email = '[email protected]'
+ data = json.dumps(WholeAccountSerializer(self.user).data)
+ response = self.client.post(
+ reverse('_accounts:account-list'),
+ data,
+ content_type='application/json')
+ self.assertEqual(
+ first=response.status_code, second=status.HTTP_201_CREATED)
+ | Create a test for Account creation | ## Code Before:
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseAccount
first_name = 'John'
last_name = 'Doe'
email = '{}.{}@email.com'.format(first_name, last_name)
password = 'passjohn1'
class FactoryBoyCreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_can_create_user(self):
response = self.client.get(
reverse('_accounts:account-detail', kwargs={'pk': 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertJSONEqual(
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
## Instruction:
Create a test for Account creation
## Code After:
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseAccount
first_name = 'John'
last_name = 'Doe'
email = '{}.{}@email.com'.format(first_name, last_name)
password = 'passjohn1'
class FactoryBoyCreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_can_create_user(self):
response = self.client.get(
reverse('_accounts:account-detail', kwargs={'pk': 1}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertJSONEqual(
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
class CreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_create_user(self):
self.user.email = '[email protected]'
data = json.dumps(WholeAccountSerializer(self.user).data)
response = self.client.post(
reverse('_accounts:account-list'),
data,
content_type='application/json')
self.assertEqual(
first=response.status_code, second=status.HTTP_201_CREATED)
| ...
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
class CreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_create_user(self):
self.user.email = '[email protected]'
data = json.dumps(WholeAccountSerializer(self.user).data)
response = self.client.post(
reverse('_accounts:account-list'),
data,
content_type='application/json')
self.assertEqual(
first=response.status_code, second=status.HTTP_201_CREATED)
... |
4d29aa24b39285c491182edd69ecb7c22a9d643d | ceph_medic/tests/test_main.py | ceph_medic/tests/test_main.py | import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert out.out == ''
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
| import pytest
import ceph_medic.main
from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
def fake_exists(path):
if path == ssh_config:
return True
if path.endswith('cephmedic.conf'):
return False
return True
with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
m_exists.side_effect = fake_exists
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
| Fix test breakage when ssh_config missing | tests: Fix test breakage when ssh_config missing
I assumed /etc/ssh/ssh_config would be present, but it turns out in a
mock chroot environment it isn't.
Signed-off-by: Zack Cerza <[email protected]>
| Python | mit | alfredodeza/ceph-doctor | import pytest
import ceph_medic.main
+
+ from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
+
+ def fake_exists(path):
+ if path == ssh_config:
+ return True
+ if path.endswith('cephmedic.conf'):
+ return False
+ return True
+
+ with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
+ m_exists.side_effect = fake_exists
- ceph_medic.main.Medic(argv)
+ ceph_medic.main.Medic(argv)
out = capsys.readouterr()
- assert out.out == ''
+ assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
| Fix test breakage when ssh_config missing | ## Code Before:
import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert out.out == ''
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
## Instruction:
Fix test breakage when ssh_config missing
## Code After:
import pytest
import ceph_medic.main
from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
def fake_exists(path):
if path == ssh_config:
return True
if path.endswith('cephmedic.conf'):
return False
return True
with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
m_exists.side_effect = fake_exists
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
| ...
import pytest
import ceph_medic.main
from mock import patch
...
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
def fake_exists(path):
if path == ssh_config:
return True
if path.endswith('cephmedic.conf'):
return False
return True
with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
m_exists.side_effect = fake_exists
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
... |
959897478bbda18f02aa6e38f2ebdd837581f1f0 | tests/test_sct_verify_signature.py | tests/test_sct_verify_signature.py | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
got_verified, got_output, got_cmd_res = \
verify_signature(signature_input, signature, pubkey)
assert got_verified is True
assert got_output == 'Verified OK\n'
assert got_cmd_res.exitcode == 0
signature_input = b'some invalid signature input'
got_verified, got_output, got_cmd_res = \
verify_signature(signature_input, signature, pubkey)
assert got_verified is False
assert got_output == 'Verification Failure\n'
assert got_cmd_res.exitcode == 1
| from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
assert verify_signature(signature_input, signature, pubkey) is True
signature_input = b'some invalid signature input'
assert verify_signature(signature_input, signature, pubkey) is False
| Fix test for changed SctVerificationResult | Fix test for changed SctVerificationResult
| Python | mit | theno/ctutlz,theno/ctutlz | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
- got_verified, got_output, got_cmd_res = \
- verify_signature(signature_input, signature, pubkey)
+ assert verify_signature(signature_input, signature, pubkey) is True
-
- assert got_verified is True
- assert got_output == 'Verified OK\n'
- assert got_cmd_res.exitcode == 0
signature_input = b'some invalid signature input'
- got_verified, got_output, got_cmd_res = \
- verify_signature(signature_input, signature, pubkey)
+ assert verify_signature(signature_input, signature, pubkey) is False
- assert got_verified is False
- assert got_output == 'Verification Failure\n'
- assert got_cmd_res.exitcode == 1
- | Fix test for changed SctVerificationResult | ## Code Before:
from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
got_verified, got_output, got_cmd_res = \
verify_signature(signature_input, signature, pubkey)
assert got_verified is True
assert got_output == 'Verified OK\n'
assert got_cmd_res.exitcode == 0
signature_input = b'some invalid signature input'
got_verified, got_output, got_cmd_res = \
verify_signature(signature_input, signature, pubkey)
assert got_verified is False
assert got_output == 'Verification Failure\n'
assert got_cmd_res.exitcode == 1
## Instruction:
Fix test for changed SctVerificationResult
## Code After:
from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
assert verify_signature(signature_input, signature, pubkey) is True
signature_input = b'some invalid signature input'
assert verify_signature(signature_input, signature, pubkey) is False
| // ... existing code ...
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
assert verify_signature(signature_input, signature, pubkey) is True
signature_input = b'some invalid signature input'
assert verify_signature(signature_input, signature, pubkey) is False
// ... rest of the code ... |
2ec5f71d04ae17a1c0a457fba1b82f8c8e8891ab | sc2reader/listeners/utils.py | sc2reader/listeners/utils.py | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass | Add a default ListenerBase.setup implementation. | Add a default ListenerBase.setup implementation.
| Python | mit | StoicLoofah/sc2reader,vlaufer/sc2reader,vlaufer/sc2reader,GraylinKim/sc2reader,ggtracker/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,StoicLoofah/sc2reader | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
+
+ def setup(self, replay):
+ pass | Add a default ListenerBase.setup implementation. | ## Code Before:
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
## Instruction:
Add a default ListenerBase.setup implementation.
## Code After:
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass | // ... existing code ...
def accepts(self, event):
return true
def setup(self, replay):
pass
// ... rest of the code ... |
2ef0ccfbf337d0ef1870c5a1191b2bcdcffd1f9e | dbaas/backup/admin/log_configuration.py | dbaas/backup/admin/log_configuration.py | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path")
| from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path",
"cron_minute", "cron_hour")
| Add new fields on LogConfiguration model | Add new fields on LogConfiguration model
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
- "filer_path", "mount_point_path", "log_path")
+ "filer_path", "mount_point_path", "log_path",
+ "cron_minute", "cron_hour")
| Add new fields on LogConfiguration model | ## Code Before:
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path")
## Instruction:
Add new fields on LogConfiguration model
## Code After:
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path",
"cron_minute", "cron_hour")
| # ... existing code ...
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path",
"cron_minute", "cron_hour")
# ... rest of the code ... |
End of preview. Expand
in Data Studio
Code Apply
Processed EditPackFT with fuzzy diff
generated using heuristics.
Columns
old_contents
the old codenew_contents
the new codefuzzy_diff
the code segment extracted from diff betweenold_contents
andnew_contents
Augmentation
Examples with number of diff chunks > 1 were duplicated. Old contents have one of the diff chunks applied.
Example
Diff
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
+ with producers[self.connection].acquire(block=False) as producer:
+ for queue in task_queues:
+ maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
- for queue in task_queues:
- maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
Snippet
# ... existing code ...
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
# ... modified code ...
with producers[self.connection].acquire(block=False) as producer:
producer.publish(payload,
exchange=task_exchange,
# ... rest of the code ...
Partial apply
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
- Downloads last month
- 184