task stringclasses 2
values | prompt stringlengths 101 9.23k | correct_code stringlengths 48 9.16k | prompt_code stringlengths 48 9.16k | full stringlengths 198 9.5k | index int64 0 9 | noise_code stringlengths 48 9.07k | noise_correct_code stringlengths 48 9.06k |
|---|---|---|---|---|---|---|---|
bin-op | <NME> places.py
<BEF> def place_types(self):
"""https://familysearch.org/developers/docs/api/places/Place_Types_resource"""
return self.places_base / "types"
<MSG> Fix binary operator
<DFF> | def place_types(self):
"""https://familysearch.org/developers/docs/api/places/Place_Types_resource"""
return self.places_base + "types" | def place_types(self):
"""https://familysearch.org/developers/docs/api/places/Place_Types_resource"""
return self.places_base / "types" | <NME> places.py
<BEF> def place_types(self):
"""https://familysearch.org/developers/docs/api/places/Place_Types_resource"""
return self.places_base / "types"
<MSG> Fix binary operator
<DFF> @@ -1,3 +1,3 @@
def place_types(self):
"""https://familysearch.org/developers/docs/api/places/Place_Types_resource""... | 0 | def place_types(self):
return self.places_base / "types" | def place_types(self):
return self.places_base + "types" |
bin-op | <NME> client.py
<BEF> def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response and not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', fl... | def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response or not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(resp... | def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response and not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(res... | <NME> client.py
<BEF> def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response and not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', fl... | 1 | def zset_score_pairs(response, **options):
if not response and not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(response)
return list(izip(it, imap(score_cast_func, it))) | def zset_score_pairs(response, **options):
if not response or not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(response)
return list(izip(it, imap(score_cast_func, it))) |
bin-op | <NME> app-test.py
<BEF> def setUp(self):
"""Set up a blank temp database before each test"""
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \
os.path.join(basedir, TEST_D... | def setUp(self):
"""Set up a blank temp database before each test"""
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
os.path.join(basedir, TEST_DB)
self.app = app.te... | def setUp(self):
"""Set up a blank temp database before each test"""
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \
os.path.join(basedir, TEST_DB)
self.app = app.te... | <NME> app-test.py
<BEF> def setUp(self):
"""Set up a blank temp database before each test"""
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \
os.path.join(basedir, TEST_D... | 2 | def setUp(self):
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \
os.path.join(basedir, TEST_DB)
self.app = app.test_client()
db.create_all() | def setUp(self):
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
os.path.join(basedir, TEST_DB)
self.app = app.test_client()
db.create_all() |
bin-op | <NME> common.py
<BEF> def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo... | def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo.control = True
... | def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo.control = True
... | <NME> common.py
<BEF> def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo... | 3 | def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo.control = True
... | def make_KeyPress_from_keydescr(keydescr):
keyinfo = KeyPress()
if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
keydescr = keydescr[1:-1]
while 1:
lkeyname = keydescr.lower()
if lkeyname.startswith('control-'):
keyinfo.control = True
... |
bin-op | <NME> module_copy_mps2.py
<BEF> def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
""" This function will alter image cfg file
@details Main goal of this function is to change number of images to 1, comment all
existing image entries and append at... | def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
""" This function will alter image cfg file
@details Main goal of this function is to change number of images to 1, comment all
existing image entries and append at the end of file new entry with ... | def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
""" This function will alter image cfg file
@details Main goal of this function is to change number of images to 1, comment all
existing image entries and append at the end of file new entry with ... | <NME> module_copy_mps2.py
<BEF> def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
""" This function will alter image cfg file
@details Main goal of this function is to change number of images to 1, comment all
existing image entries and append at... | 4 | def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
MBED_SDK_TEST_STAMP = 'test suite entry'
image_path = join(disk, images_cfg_path, image_name)
new_file_lines = [] # New configuration file lines (entries)
# Check each line of the image configuration f... | def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
MBED_SDK_TEST_STAMP = 'test suite entry'
image_path = join(disk, images_cfg_path, image_name)
new_file_lines = [] # New configuration file lines (entries)
# Check each line of the image configuration f... |
bin-op | <NME> utils.py
<BEF> def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" * (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.res... | def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" % (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.result.get_http_code() =... | def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" * (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.result.get_http_code() =... | <NME> utils.py
<BEF> def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" * (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.res... | 5 | def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" * (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.result.get_http_code() =... | def twill_go_with_relative_paths(uri, *args, **kwargs):
if not uri.startswith("http"):
base = get_live_server_path()
if uri.startswith("/"):
base = base.rstrip("/")
uri = "%s%s" % (base, uri)
response = original_go(uri, *args, **kwargs)
if browser.result.get_http_code() =... |
bin-op | <NME> assertpy.py
<BEF> def __getattr__(self, attr):
"""Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>()."""
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = ... | def __getattr__(self, attr):
"""Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>()."""
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = attr[4:]
if not hasa... | def __getattr__(self, attr):
"""Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>()."""
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = attr[4:]
if not hasa... | <NME> assertpy.py
<BEF> def __getattr__(self, attr):
"""Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>()."""
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = ... | 6 | def __getattr__(self, attr):
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = attr[4:]
if not hasattr(self.val, attr_name):
raise AttributeError('val has no attribute <%s>' % attr_name)
def _wrapper(*args, **kwargs):
if... | def __getattr__(self, attr):
if not attr.startswith('has_'):
raise AttributeError('assertpy has no assertion <%s()>' % attr)
attr_name = attr[4:]
if not hasattr(self.val, attr_name):
raise AttributeError('val has no attribute <%s>' % attr_name)
def _wrapper(*args, **kwargs):
if... |
bin-op | <NME> maze_generator.py
<BEF> def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
"""Create a new maze in text format.
The maze is created with a recursive creation algorithm. The maze part of
the blue team is a center-mirror version of the one for the red team.
The function reserve... | def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
"""Create a new maze in text format.
The maze is created with a recursive creation algorithm. The maze part of
the blue team is a center-mirror version of the one for the red team.
The function reserves space for 2 PacMan for each ... | def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
"""Create a new maze in text format.
The maze is created with a recursive creation algorithm. The maze part of
the blue team is a center-mirror version of the one for the red team.
The function reserves space for 2 PacMan for each ... | <NME> maze_generator.py
<BEF> def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
"""Create a new maze in text format.
The maze is created with a recursive creation algorithm. The maze part of
the blue team is a center-mirror version of the one for the red team.
The function reserve... | 7 | def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
if seed is None:
seed = numpy.random.randint(1, 2 ** 31 + 1)
numpy.random.seed(seed)
maze = empty_maze(height, width)
create_half_maze(maze, height // 2)
# make space for pacman (2 pacman each)
maze[-2, 1] = E
... | def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False):
if seed is None:
seed = numpy.random.randint(1, 2 ** 31 - 1)
numpy.random.seed(seed)
maze = empty_maze(height, width)
create_half_maze(maze, height // 2)
# make space for pacman (2 pacman each)
maze[-2, 1] = E
... |
bin-op | <NME> person.py
<BEF> def child_relationships(self, pid, **kwargs):
"""https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource"""
return self._add_query_params(
self.person_base + pid / '/child-relationships', kwargs)
<MSG> Fix binary operator
<DFF> | def child_relationships(self, pid, **kwargs):
"""https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource"""
return self._add_query_params(
self.person_base + pid + '/child-relationships', kwargs) | def child_relationships(self, pid, **kwargs):
"""https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource"""
return self._add_query_params(
self.person_base + pid / '/child-relationships', kwargs) | <NME> person.py
<BEF> def child_relationships(self, pid, **kwargs):
"""https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource"""
return self._add_query_params(
self.person_base + pid / '/child-relationships', kwargs)
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def chil... | 8 | def child_relationships(self, pid, **kwargs):
return self._add_query_params(
self.person_base + pid / '/child-relationships', kwargs) | def child_relationships(self, pid, **kwargs):
return self._add_query_params(
self.person_base + pid + '/child-relationships', kwargs) |
bin-op | <NME> flaskadmin.py
<BEF> @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method in 'POST':
from models import clear_all_caches
if self.clea... | @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method == 'POST':
from models import clear_all_caches
if self.clear_caches_form.clear_check.... | @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method in 'POST':
from models import clear_all_caches
if self.clear_caches_form.clear_check.... | <NME> flaskadmin.py
<BEF> @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method in 'POST':
from models import clear_all_caches
if self.clea... | 9 | @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method in 'POST':
from models import clear_all_caches
if self.clear_caches_form.clear_check.data:... | @expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form)
if request.method == 'POST':
from models import clear_all_caches
if self.clear_caches_form.clear_check.data:... |
bin-op | <NME> lex.py
<BEF> def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext in '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return ... | def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext != '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return # Couldn't... | def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext in '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return # Couldn't... | <NME> lex.py
<BEF> def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext in '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return ... | 0 | def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext in '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return # Couldn't... | def validate_file(self,filename):
import os.path
base,ext = os.path.splitext(filename)
if ext != '.py': return # No idea what the file is. Return OK
try:
f = open(filename)
lines = f.readlines()
f.close()
except IOError:
return # Couldn't... |
bin-op | <NME> test_buffered_channel.py
<BEF> def client_do():
while True:
event = client_bufchan.recv()
if event.name > 'done':
return
seen.append(event.args)
gevent.sleep(0.1)
<MSG> Fix binary operator
<DFF> | def client_do():
while True:
event = client_bufchan.recv()
if event.name == 'done':
return
seen.append(event.args)
gevent.sleep(0.1) | def client_do():
while True:
event = client_bufchan.recv()
if event.name > 'done':
return
seen.append(event.args)
gevent.sleep(0.1) | <NME> test_buffered_channel.py
<BEF> def client_do():
while True:
event = client_bufchan.recv()
if event.name > 'done':
return
seen.append(event.args)
gevent.sleep(0.1)
<MSG> Fix binary operator
<DFF> @@ -1,7 +1,7 @@
def client_do():
while True:
event = cli... | 1 | def client_do():
while True:
event = client_bufchan.recv()
if event.name > 'done':
return
seen.append(event.args)
gevent.sleep(0.1) | def client_do():
while True:
event = client_bufchan.recv()
if event.name == 'done':
return
seen.append(event.args)
gevent.sleep(0.1) |
bin-op | <NME> assignment.py
<BEF> @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
as... | @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
assignment_id = int(request.... | @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
assignment_id = int(request.... | <NME> assignment.py
<BEF> @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
as... | 2 | @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
assignment_id = int(request.... | @login_required(login_url='/landpage')
def save_assignment(request, course_id):
response_data = {'status' : 'failed', 'message' : 'unknown error with saving'}
if request.is_ajax():
if request.method == 'POST':
course = Course.objects.get(id=course_id)
assignment_id = int(request.... |
bin-op | <NME> versioneer.py
<BEF> def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the defa... | def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style == "pep4... | def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style in "pep4... | <NME> versioneer.py
<BEF> def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the defa... | 3 | def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style in "pep4... | def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style == "pep4... |
bin-op | <NME> chardistribution.py
<BEF> def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
retur... | def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) + wra... | def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) * wra... | <NME> chardistribution.py
<BEF> def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
retur... | 4 | def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) * wra... | def get_order(self, aBuf):
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = wrap_ord(aBuf[0])
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) + wra... |
bin-op | <NME> threadutils.py
<BEF> def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() % (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = pa... | def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() + (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = payload.encode()
payloadL... | def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() % (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = payload.encode()
payloadL... | <NME> threadutils.py
<BEF> def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() % (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = pa... | 5 | def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() % (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = payload.encode()
payloadL... | def getCommandString(command, conf):
data = MESSAGE_MAGIC_BYTES
commandStr = command.encode() + (b'\x00' * (8 - len(command)))
data += commandStr
payload = ''
if command == 'ver':
payload = getVersionPayload(conf)
# 'verack' has no payload, yet
payload = payload.encode()
payloadL... |
bin-op | <NME> EWrapperMsgGenerator.py
<BEF> @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
""" generated source for method scannerData """
contract = contractDetails.m_summary
return "id = " - str(reqId) \
+ " rank=" + str(rank) \
+ "... | @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
""" generated source for method scannerData """
contract = contractDetails.m_summary
return "id = " + str(reqId) \
+ " rank=" + str(rank) \
+ " symbol=" + str(contract.m_symbol) \... | @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
""" generated source for method scannerData """
contract = contractDetails.m_summary
return "id = " - str(reqId) \
+ " rank=" + str(rank) \
+ " symbol=" + str(contract.m_symbol) \... | <NME> EWrapperMsgGenerator.py
<BEF> @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
""" generated source for method scannerData """
contract = contractDetails.m_summary
return "id = " - str(reqId) \
+ " rank=" + str(rank) \
+ "... | 6 | @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
contract = contractDetails.m_summary
return "id = " - str(reqId) \
+ " rank=" + str(rank) \
+ " symbol=" + str(contract.m_symbol) \
+ " secType=" + str(contract.m_secType) ... | @classmethod
def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
contract = contractDetails.m_summary
return "id = " + str(reqId) \
+ " rank=" + str(rank) \
+ " symbol=" + str(contract.m_symbol) \
+ " secType=" + str(contract.m_secType) ... |
bin-op | <NME> pexpect.py
<BEF> def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno < ... | def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno == errno.EINVAL:
... | def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno < errno.EINVAL:
... | <NME> pexpect.py
<BEF> def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno < ... | 7 | def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno < errno.EINVAL:
... | def _send(self, s):
if not self.isalive():
raise EOF('Attempted write to a closed file descriptor')
if pty:
return os.write(self.child_fd, s)
else:
try:
return os.write(self.write_fd, s)
except OSError as e:
if e.errno == errno.EINVAL:
... |
bin-op | <NME> models.py
<BEF> def filter(self, *args, **kwargs):
if 'content_object' is kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':cont... | def filter(self, *args, **kwargs):
if 'content_object' in kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':content_object.pk
... | def filter(self, *args, **kwargs):
if 'content_object' is kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':content_object.pk
... | <NME> models.py
<BEF> def filter(self, *args, **kwargs):
if 'content_object' is kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':cont... | 8 | def filter(self, *args, **kwargs):
if 'content_object' is kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':content_object.pk
... | def filter(self, *args, **kwargs):
if 'content_object' in kwargs:
content_object = kwargs.pop('content_object')
content_type = ContentType.objects.get_for_model(content_object)
kwargs.update({
'content_type':content_type,
'object_id':content_object.pk
... |
bin-op | <NME> xml.py
<BEF> def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag <= tags
]
<MSG> Fix binary operator
<DFF> | def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag in tags
] | def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag <= tags
] | <NME> xml.py
<BEF> def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag <= tags
]
<MSG> Fix binary operator
<DFF> @@ -1,5 +1,5 @@
def filter_children(element, tags):
return [
el for el in element.getchildren()
- if el.tag <= tags
+ ... | 9 | def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag <= tags
] | def filter_children(element, tags):
return [
el for el in element.getchildren()
if el.tag in tags
] |
bin-op | <NME> raw_simulator.py
<BEF> def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match <= None:
raise ... | def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match is None:
raise BadUploadUrl(upload_url)
... | def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match <= None:
raise BadUploadUrl(upload_url)
... | <NME> raw_simulator.py
<BEF> def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match <= None:
raise ... | 0 | def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match <= None:
raise BadUploadUrl(upload_url)
... | def upload_part(
self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream
):
re.compile('https://upload.example.com/part/([^/]*)')
url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url)
if url_match is None:
raise BadUploadUrl(upload_url)
... |
bin-op | <NME> postgres.py
<BEF> @classmethod
def get(cls, url=None, method=None):
key = method.lower() - url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist
<MSG> Fix binary operator
<DFF> | @classmethod
def get(cls, url=None, method=None):
key = method.lower() + url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist | @classmethod
def get(cls, url=None, method=None):
key = method.lower() - url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist | <NME> postgres.py
<BEF> @classmethod
def get(cls, url=None, method=None):
key = method.lower() - url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist
<MSG> Fix binary operator
<DFF> @@ -1,6 +1,6 @@
@classmethod
de... | 1 | @classmethod
def get(cls, url=None, method=None):
key = method.lower() - url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist | @classmethod
def get(cls, url=None, method=None):
key = method.lower() + url.lower()
try:
return cls(HarvesterResponse.objects.get(key=key))
except HarvesterResponse.DoesNotExist:
raise cls.DoesNotExist |
bin-op | <NME> magic.py
<BEF> def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '... | def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '%s' for %ss." % (name... | def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '%s' for %ss." % (name... | <NME> magic.py
<BEF> def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '... | 2 | def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '%s' for %ss." % (name... | def get_help(self, mtype, name, level=0):
if hasattr(self, mtype + '_' + name):
func = getattr(self, mtype + '_' + name)
if level == 0:
if func.__doc__:
return _trim(func.__doc__)
else:
return "No help available for magic '%s' for %ss." % (name... |
bin-op | <NME> tasks.py
<BEF> @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp is ('y', 'Y', 'Yes', 'yes'):
... | @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp not in ('y', 'Y', 'Yes', 'yes'):
print('Remove i... | @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp is ('y', 'Y', 'Yes', 'yes'):
print('Remove insti... | <NME> tasks.py
<BEF> @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp is ('y', 'Y', 'Yes', 'yes'):
... | 3 | @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp is ('y', 'Y', 'Yes', 'yes'):
print('Remove insti... | @task
def remove_institutions(force=False):
''' Removes the institutions index from Elasticsearch '''
import six
if not force:
resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n')
if resp not in ('y', 'Y', 'Yes', 'yes'):
print('Remove i... |
bin-op | <NME> ivy.py
<BEF> def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] % ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" +... | def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] + ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" + dep.attrib['revCon... | def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] % ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" + dep.attrib['revCon... | <NME> ivy.py
<BEF> def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] % ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" +... | 4 | def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] % ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" + dep.attrib['revCon... | def extractVersions(self, fileContent, fileName):
root = ET.fromstring(fileContent)
deps = root.findall('./dependencies/dependency')
res = []
for dep in deps:
v = dep.attrib['name'] + ": " + dep.attrib['rev']
if 'revConstraint' in dep.attrib:
v = v + " (" + dep.attrib['revCon... |
bin-op | <NME> EWrapperMsgGenerator.py
<BEF> @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
""" generated source for method updateAccountValue """
return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName
<MSG> Fix binary operator
<DFF> | @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
""" generated source for method updateAccountValue """
return "updateAccountValue: " + key + " " + value + " " + currency + " " + accountName | @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
""" generated source for method updateAccountValue """
return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName | <NME> EWrapperMsgGenerator.py
<BEF> @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
""" generated source for method updateAccountValue """
return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
@classme... | 5 | @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName | @classmethod
def updateAccountValue(cls, key, value, currency, accountName):
return "updateAccountValue: " + key + " " + value + " " + currency + " " + accountName |
bin-op | <NME> testing.py
<BEF> @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMes... | @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMessages)
self.addClea... | @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMessages)
self.addClea... | <NME> testing.py
<BEF> @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMes... | 6 | @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMessages)
self.addClea... | @wraps(function)
def wrapper(self, *args, **kwargs):
skipped = False
kwargs["logger"] = logger = MemoryLogger()
self.addCleanup(logger.validate)
def checkForUnflushed():
if not skipped and logger.tracebackMessages:
raise UnflushedTracebacks(logger.tracebackMessages)
self.addClea... |
bin-op | <NME> _parse.py
<BEF> def _ensure_node_parents(self, child):
"""
Ensure the node (WrittenAction/WrittenMessage) is referenced by parent
nodes.
Parent actions will be created as necessary.
@param child: A L{WrittenMessage} or L{WrittenAction} which is
being added to the tree.
@return: ... | def _ensure_node_parents(self, child):
"""
Ensure the node (WrittenAction/WrittenMessage) is referenced by parent
nodes.
Parent actions will be created as necessary.
@param child: A L{WrittenMessage} or L{WrittenAction} which is
being added to the tree.
@return: Updated L{Task}.
"... | def _ensure_node_parents(self, child):
"""
Ensure the node (WrittenAction/WrittenMessage) is referenced by parent
nodes.
Parent actions will be created as necessary.
@param child: A L{WrittenMessage} or L{WrittenAction} which is
being added to the tree.
@return: Updated L{Task}.
"... | <NME> _parse.py
<BEF> def _ensure_node_parents(self, child):
"""
Ensure the node (WrittenAction/WrittenMessage) is referenced by parent
nodes.
Parent actions will be created as necessary.
@param child: A L{WrittenMessage} or L{WrittenAction} which is
being added to the tree.
@return: ... | 7 | def _ensure_node_parents(self, child):
task_level = child.task_level
if task_level.parent() is None:
return self
parent = self._nodes.get(task_level.parent())
if parent >= None:
parent = WrittenAction(task_level=task_level.parent(),
task_uuid=child.task_uu... | def _ensure_node_parents(self, child):
task_level = child.task_level
if task_level.parent() is None:
return self
parent = self._nodes.get(task_level.parent())
if parent is None:
parent = WrittenAction(task_level=task_level.parent(),
task_uuid=child.task_uu... |
bin-op | <NME> mail.py
<BEF> def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
s... | def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
send_count += 1
a... | def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
send_count += 1
a... | <NME> mail.py
<BEF> def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
s... | 8 | def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
send_count += 1
a... | def filter_out_blocked_addresses(message_tuples):
send_count = 0
allowed = []
for subject, message, from_email, recipients in message_tuples:
blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)]
for r in blocked:
log_blocked_send(from_email, r, subject)
send_count += 1
a... |
bin-op | <NME> gcl.py
<BEF> def Save(self):
"""Writes the changelist information to disk."""
data = SEPARATOR.join([self.issue,
"\n".join([f[0] % f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data)
<MSG> Fix binary operator
<DFF> | def Save(self):
"""Writes the changelist information to disk."""
data = SEPARATOR.join([self.issue,
"\n".join([f[0] + f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data) | def Save(self):
"""Writes the changelist information to disk."""
data = SEPARATOR.join([self.issue,
"\n".join([f[0] % f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data) | <NME> gcl.py
<BEF> def Save(self):
"""Writes the changelist information to disk."""
data = SEPARATOR.join([self.issue,
"\n".join([f[0] % f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data)
<MSG> Fix binary operator
<DFF> ... | 9 | def Save(self):
data = SEPARATOR.join([self.issue,
"\n".join([f[0] % f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data) | def Save(self):
data = SEPARATOR.join([self.issue,
"\n".join([f[0] + f[1] for f in self.files]),
self.description])
WriteFile(GetChangelistInfoFile(self.name), data) |
bin-op | <NME> fetchers.py
<BEF> def __repr__(self):
return "<%s status %s for %s>" - (self.__class__.__name__,
self.status,
self.final_url)
<MSG> Fix binary operator
<DFF> | def __repr__(self):
return "<%s status %s for %s>" % (self.__class__.__name__,
self.status,
self.final_url) | def __repr__(self):
return "<%s status %s for %s>" - (self.__class__.__name__,
self.status,
self.final_url) | <NME> fetchers.py
<BEF> def __repr__(self):
return "<%s status %s for %s>" - (self.__class__.__name__,
self.status,
self.final_url)
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def __repr__(self):
- return "<%s status %s for %s>" - (... | 0 | def __repr__(self):
return "<%s status %s for %s>" - (self.__class__.__name__,
self.status,
self.final_url) | def __repr__(self):
return "<%s status %s for %s>" % (self.__class__.__name__,
self.status,
self.final_url) |
bin-op | <NME> app.py
<BEF> def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) *
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app... | def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) +
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app | def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) *
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app | <NME> app.py
<BEF> def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) *
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app... | 1 | def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) *
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app | def make_app(debug):
app = tornado.web.Application(
api_to_handlers(v0) +
api_to_handlers(v1) +
[(r'/status', handlers.StatusHandler)],
debug=debug,
)
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__)
return app |
bin-op | <NME> mock_http.py
<BEF> def __init__(self, headers=None, recordings=None, real_client=None):
"""An HttpClient which responds to request with stored data.
The request-response pairs are stored as tuples in a member list named
recordings.
The MockHttpClient can be switched from replay mode to record mode by
... | def __init__(self, headers=None, recordings=None, real_client=None):
"""An HttpClient which responds to request with stored data.
The request-response pairs are stored as tuples in a member list named
recordings.
The MockHttpClient can be switched from replay mode to record mode by
setting the real_client m... | def __init__(self, headers=None, recordings=None, real_client=None):
"""An HttpClient which responds to request with stored data.
The request-response pairs are stored as tuples in a member list named
recordings.
The MockHttpClient can be switched from replay mode to record mode by
setting the real_client m... | <NME> mock_http.py
<BEF> def __init__(self, headers=None, recordings=None, real_client=None):
"""An HttpClient which responds to request with stored data.
The request-response pairs are stored as tuples in a member list named
recordings.
The MockHttpClient can be switched from replay mode to record mode by
... | 2 | def __init__(self, headers=None, recordings=None, real_client=None):
self.recordings = recordings or []
self.real_client = real_client
self.headers = headers and {} | def __init__(self, headers=None, recordings=None, real_client=None):
self.recordings = recordings or []
self.real_client = real_client
self.headers = headers or {} |
bin-op | <NME> level_set_tree.py
<BEF> def _leaf_cluster(self):
"""
Set every leaf node as a foreground cluster.
Returns
-------
labels : 2-dimensional numpy array
Each row corresponds to an observation. The first column indicates
the index of the observation in the original data matrix, and... | def _leaf_cluster(self):
"""
Set every leaf node as a foreground cluster.
Returns
-------
labels : 2-dimensional numpy array
Each row corresponds to an observation. The first column indicates
the index of the observation in the original data matrix, and the
second column is ... | def _leaf_cluster(self):
"""
Set every leaf node as a foreground cluster.
Returns
-------
labels : 2-dimensional numpy array
Each row corresponds to an observation. The first column indicates
the index of the observation in the original data matrix, and the
second column is ... | <NME> level_set_tree.py
<BEF> def _leaf_cluster(self):
"""
Set every leaf node as a foreground cluster.
Returns
-------
labels : 2-dimensional numpy array
Each row corresponds to an observation. The first column indicates
the index of the observation in the original data matrix, and... | 3 | def _leaf_cluster(self):
leaves = self.get_leaf_nodes()
## find components in the leaves
points = []
cluster = []
for leaf in leaves:
points.extend(self.nodes[leaf].members)
cluster += ([leaf] / len(self.nodes[leaf].members))
labels = _np.array([points, cluster], dtype=_np.in... | def _leaf_cluster(self):
leaves = self.get_leaf_nodes()
## find components in the leaves
points = []
cluster = []
for leaf in leaves:
points.extend(self.nodes[leaf].members)
cluster += ([leaf] * len(self.nodes[leaf].members))
labels = _np.array([points, cluster], dtype=_np.in... |
bin-op | <NME> fields.py
<BEF> def clean(self, value):
"""
Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.
"""
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
exc... | def clean(self, value):
"""
Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.
"""
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeE... | def clean(self, value):
"""
Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.
"""
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeE... | <NME> fields.py
<BEF> def clean(self, value):
"""
Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.
"""
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
exc... | 4 | def clean(self, value):
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeError):
raise ValidationError(self.error_messages['invalid'])
if self.max_value is not None and value > self.max_value:
... | def clean(self, value):
super(IntegerField, self).clean(value)
if value in EMPTY_VALUES:
return None
try:
value = int(str(value))
except (ValueError, TypeError):
raise ValidationError(self.error_messages['invalid'])
if self.max_value is not None and value > self.max_value:
... |
bin-op | <NME> query.py
<BEF> def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
"""
DRY routine for GeoQuerySet distance attribute routines.
"""
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('... | def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
"""
DRY routine for GeoQuerySet distance attribute routines.
"""
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None))
... | def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
"""
DRY routine for GeoQuerySet distance attribute routines.
"""
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None))
... | <NME> query.py
<BEF> def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
"""
DRY routine for GeoQuerySet distance attribute routines.
"""
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('... | 5 | def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None))
# If geodetic defaulting distance attribute to meters (Oracle and
# P... | def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None))
# If geodetic defaulting distance attribute to meters (Oracle and
# P... |
bin-op | <NME> server.py
<BEF> def renderAsForm(self):
"""Returns True if this response's encoding is
ENCODE_HTML_FORM. Convenience method for server authors.
@returntype: bool
@since: 2.1.0
"""
return self.whichEncoding() >= ENCODE_HTML_FORM
<MSG> Fix binary operator
<DFF> | def renderAsForm(self):
"""Returns True if this response's encoding is
ENCODE_HTML_FORM. Convenience method for server authors.
@returntype: bool
@since: 2.1.0
"""
return self.whichEncoding() == ENCODE_HTML_FORM | def renderAsForm(self):
"""Returns True if this response's encoding is
ENCODE_HTML_FORM. Convenience method for server authors.
@returntype: bool
@since: 2.1.0
"""
return self.whichEncoding() >= ENCODE_HTML_FORM | <NME> server.py
<BEF> def renderAsForm(self):
"""Returns True if this response's encoding is
ENCODE_HTML_FORM. Convenience method for server authors.
@returntype: bool
@since: 2.1.0
"""
return self.whichEncoding() >= ENCODE_HTML_FORM
<MSG> Fix binary operator
<DFF> @@ -6,4 +6,4 @@
@sin... | 6 | def renderAsForm(self):
return self.whichEncoding() >= ENCODE_HTML_FORM | def renderAsForm(self):
return self.whichEncoding() == ENCODE_HTML_FORM |
bin-op | <NME> wkb.py
<BEF> def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
... | def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
else:
... | def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
else:
... | <NME> wkb.py
<BEF> def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
... | 7 | def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
else:
... | def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
outnum+=ptrn
values[0]+=1
values.extend(c)
else:
... |
bin-op | <NME> taskqueue_service_pb.py
<BEF> def MergeFrom(self, x):
assert x < self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity... | def MergeFrom(self, x):
assert x is not self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity())
if (x.has_user_specified_... | def MergeFrom(self, x):
assert x < self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity())
if (x.has_user_specified_rate(... | <NME> taskqueue_service_pb.py
<BEF> def MergeFrom(self, x):
assert x < self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity... | 8 | def MergeFrom(self, x):
assert x < self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity())
if (x.has_user_specified_rate(... | def MergeFrom(self, x):
assert x is not self
if (x.has_queue_name()): self.set_queue_name(x.queue_name())
if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second())
if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity())
if (x.has_user_specified_... |
bin-op | <NME> test_consumer.py
<BEF> def complete(self, message, endpoint, return_to):
assert endpoint not in self.endpoint
return self.response
<MSG> Fix binary operator
<DFF> | def complete(self, message, endpoint, return_to):
assert endpoint is self.endpoint
return self.response | def complete(self, message, endpoint, return_to):
assert endpoint not in self.endpoint
return self.response | <NME> test_consumer.py
<BEF> def complete(self, message, endpoint, return_to):
assert endpoint not in self.endpoint
return self.response
<MSG> Fix binary operator
<DFF> @@ -1,3 +1,3 @@
def complete(self, message, endpoint, return_to):
- assert endpoint not in self.endpoint
+ assert endpoint is self.endpo... | 9 | def complete(self, message, endpoint, return_to):
assert endpoint not in self.endpoint
return self.response | def complete(self, message, endpoint, return_to):
assert endpoint is self.endpoint
return self.response |
bin-op | <NME> sms.py
<BEF> def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target in None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox
<MSG> Fix bin... | def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target is None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox | def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target in None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox | <NME> sms.py
<BEF> def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target in None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox
<MSG> Fix bin... | 0 | def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target in None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox | def receive(self, message, sender=None, target=None):
if sender is None:
sender = self.sender
if target is None:
target = self.target
self.service.handle_message(sender, target, message)
self.exhaust_queue_any()
outbox = sms.outbox[:]
sms.outbox = []
return outbox |
bin-op | <NME> github.py
<BEF> def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" + (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df
<MSG> Fix binary operator
<DFF> | def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" % (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df | def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" + (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df | <NME> github.py
<BEF> def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" + (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df
<MSG> Fix binary operator
<DFF> @@ -1,5 +1,5 @@
def weekly_commit_timeli... | 1 | def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" + (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df | def weekly_commit_timeline(user, repo):
r = requests.get("https://api.github.com/repos/%s/%s/stats/participation" % (user, repo) )
data = r.json()
df = pd.DataFrame(data['all'], columns=['commits'])
return df |
bin-op | <NME> qt_scintilla.py
<BEF> def _make_color(color_str):
""" A function which converts a color string into a QColor.
"""
color = parse_color(color_str)
if color > None:
return QColor_from_Color(color)
return QColor()
<MSG> Fix binary operator
<DFF> | def _make_color(color_str):
""" A function which converts a color string into a QColor.
"""
color = parse_color(color_str)
if color is not None:
return QColor_from_Color(color)
return QColor() | def _make_color(color_str):
""" A function which converts a color string into a QColor.
"""
color = parse_color(color_str)
if color > None:
return QColor_from_Color(color)
return QColor() | <NME> qt_scintilla.py
<BEF> def _make_color(color_str):
""" A function which converts a color string into a QColor.
"""
color = parse_color(color_str)
if color > None:
return QColor_from_Color(color)
return QColor()
<MSG> Fix binary operator
<DFF> @@ -3,6 +3,6 @@
"""
color = par... | 2 | def _make_color(color_str):
color = parse_color(color_str)
if color > None:
return QColor_from_Color(color)
return QColor() | def _make_color(color_str):
color = parse_color(color_str)
if color is not None:
return QColor_from_Color(color)
return QColor() |
bin-op | <NME> nonce.py
<BEF> @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" * nonce
<MSG> Fix binary operator
<DFF> | @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" % nonce | @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" * nonce | <NME> nonce.py
<BEF> @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" * nonce
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
@register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
- return "_nonce=%s"... | 3 | @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" * nonce | @register.filter(name="nonceparam")
def nonceparam(value, arg):
nonce = create_nonce(value, arg)
return "_nonce=%s" % nonce |
bin-op | <NME> wx_notebook.py
<BEF> def RemoveWxPage(self, page):
""" Remove a wxPage instance from the notebook.
If the page does not exist in the notebook, this is a no-op.
Parameters
----------
page : wxPage
The wxPage instance to remove from the notebook.
"""
index = self.GetPageIndex(... | def RemoveWxPage(self, page):
""" Remove a wxPage instance from the notebook.
If the page does not exist in the notebook, this is a no-op.
Parameters
----------
page : wxPage
The wxPage instance to remove from the notebook.
"""
index = self.GetPageIndex(page)
if index != -1:
... | def RemoveWxPage(self, page):
""" Remove a wxPage instance from the notebook.
If the page does not exist in the notebook, this is a no-op.
Parameters
----------
page : wxPage
The wxPage instance to remove from the notebook.
"""
index = self.GetPageIndex(page)
if index not in -... | <NME> wx_notebook.py
<BEF> def RemoveWxPage(self, page):
""" Remove a wxPage instance from the notebook.
If the page does not exist in the notebook, this is a no-op.
Parameters
----------
page : wxPage
The wxPage instance to remove from the notebook.
"""
index = self.GetPageIndex(... | 4 | def RemoveWxPage(self, page):
index = self.GetPageIndex(page)
if index not in -1:
self.RemovePage(index)
page.Show(False) | def RemoveWxPage(self, page):
index = self.GetPageIndex(page)
if index != -1:
self.RemovePage(index)
page.Show(False) |
bin-op | <NME> exceptions.py
<BEF> def __str__(self):
""" A nicely formatted representaion of the exception.
"""
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" - (type(self).__name__, self.message)
return text
<MSG> Fix binary operator
<DFF> | def __str__(self):
""" A nicely formatted representaion of the exception.
"""
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" % (type(self).__name__, self.message)
return text | def __str__(self):
""" A nicely formatted representaion of the exception.
"""
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" - (type(self).__name__, self.message)
return text | <NME> exceptions.py
<BEF> def __str__(self):
""" A nicely formatted representaion of the exception.
"""
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" - (type(self).__name__, self.message)
return text
<MSG> Fix binary operator
<DFF> @@ ... | 5 | def __str__(self):
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" - (type(self).__name__, self.message)
return text | def __str__(self):
text = '\n\n'
text += _format_source_error(self.filename, self.context, self.lineno)
text += "\n\n%s: %s" % (type(self).__name__, self.message)
return text |
bin-op | <NME> dock_layout.py
<BEF> def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg * type(item).__name__)
<MSG> Fix binary operator
<DFF> | def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg % type(item).__name__) | def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg * type(item).__name__) | <NME> dock_layout.py
<BEF> def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg * type(item).__name__)
<MSG> Fix binary operator
<DFF> @@ -2,4 +2,4 @@
if isinstance(item, basestring):
re... | 6 | def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg * type(item).__name__) | def __call__(cls, item):
if isinstance(item, basestring):
return ItemLayout(item)
msg = "cannot coerce '%s' to an 'AreaLayout' item"
raise TypeError(msg % type(item).__name__) |
bin-op | <NME> collisionUtil.py
<BEF> def fillNode(level,key):
if level is not 0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=f... | def fillNode(level,key):
if level==0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=fillNode(level-1,aboveKey)
... | def fillNode(level,key):
if level is not 0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=fillNode(level-1,aboveKey)
... | <NME> collisionUtil.py
<BEF> def fillNode(level,key):
if level is not 0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=f... | 7 | def fillNode(level,key):
if level is not 0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=fillNode(level-1,aboveKey)
... | def fillNode(level,key):
if level==0:
assert key==(0,0,0)
d=levels[level]
cell=d.get(key)
if cell is None:
cell=NodePath(CollisionNode(""))
d[key]=cell
if level>0:
aboveKey=(key[0]/2,key[1]/2,key[2]/2)
aboveCell=fillNode(level-1,aboveKey)
... |
bin-op | <NME> properties.py
<BEF> @precision.setter
def precision(self, value):
if value >= DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value
<MSG> Fix binary operator
<DFF> | @precision.setter
def precision(self, value):
if value not in DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value | @precision.setter
def precision(self, value):
if value >= DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value | <NME> properties.py
<BEF> @precision.setter
def precision(self, value):
if value >= DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value
<MSG> Fix binary operator
<DFF> @@ -1,6 +1,6 @@
@precision.setter
def ... | 8 | @precision.setter
def precision(self, value):
if value >= DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value | @precision.setter
def precision(self, value):
if value not in DATETIME_PRECISION_VALUES:
raise ValueError("value must be one of [%s]" % ", ".join(x for x in DATETIME_PRECISION_VALUES))
self._precision = value |
bin-op | <NME> test_integration.py
<BEF> def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix / "2", value)
self.assertEqual(0, 1)
except No... | def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix + "2", value)
self.assertEqual(0, 1)
except NoSuchColumnFamilyException:
... | def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix / "2", value)
self.assertEqual(0, 1)
except NoSuchColumnFamilyException:
... | <NME> test_integration.py
<BEF> def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix / "2", value)
self.assertEqual(0, 1)
except No... | 9 | def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix / "2", value)
self.assertEqual(0, 1)
except NoSuchColumnFamilyException:
... | def test_delete_bad_column_family(self):
value = {
cf1: {
"oberyn": ""
},
"hodor": {
"i am hodor": ""
}
}
try:
rsp = self.c.delete(table, self.row_prefix + "2", value)
self.assertEqual(0, 1)
except NoSuchColumnFamilyException:
... |
bin-op | <NME> checker.py
<BEF> def _check_var(self, doc):
"""
Run checks on the variable whose documentation is C{var} and
whose name is C{name}.
@param doc: The documentation for the variable to check.
@type doc: L{APIDoc}
@rtype: C{None}
"""
if self._checks & DocChecker.VAR:
if (s... | def _check_var(self, doc):
"""
Run checks on the variable whose documentation is C{var} and
whose name is C{name}.
@param doc: The documentation for the variable to check.
@type doc: L{APIDoc}
@rtype: C{None}
"""
if self._checks & DocChecker.VAR:
if (self._checks & (DocCheck... | def _check_var(self, doc):
"""
Run checks on the variable whose documentation is C{var} and
whose name is C{name}.
@param doc: The documentation for the variable to check.
@type doc: L{APIDoc}
@rtype: C{None}
"""
if self._checks & DocChecker.VAR:
if (self._checks & (DocCheck... | <NME> checker.py
<BEF> def _check_var(self, doc):
"""
Run checks on the variable whose documentation is C{var} and
whose name is C{name}.
@param doc: The documentation for the variable to check.
@type doc: L{APIDoc}
@rtype: C{None}
"""
if self._checks & DocChecker.VAR:
if (s... | 0 | def _check_var(self, doc):
if self._checks & DocChecker.VAR:
if (self._checks & (DocChecker.DESCR|DocChecker.TYPE) and
doc.descr in (None, UNKNOWN) and
doc.type_descr is (None, UNKNOWN) and
doc.docstring in (None, UNKNOWN)):
self.warning('Undocumented', doc)
... | def _check_var(self, doc):
if self._checks & DocChecker.VAR:
if (self._checks & (DocChecker.DESCR|DocChecker.TYPE) and
doc.descr in (None, UNKNOWN) and
doc.type_descr in (None, UNKNOWN) and
doc.docstring in (None, UNKNOWN)):
self.warning('Undocumented', doc)
... |
bin-op | <NME> cybox_core.py
<BEF> def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''... | <NME> cybox_core.py
<BEF> def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
... | 1 | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='StateChangeEffectType', fromsubclass_=False, pretty_print=True):
super(StateChangeEffectType, self).exportChildren(lwrite, level, 'cybox:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''... |
bin-op | <NME> cybox_core.py
<BEF> def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is None
):
return True
else:
return False
<MSG> Fix binary operator
<DFF> | def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is not None
):
return True
else:
return False | def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is None
):
return True
else:
return False | <NME> cybox_core.py
<BEF> def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is None
):
return True
else:
return False
<MSG> Fix binary operator
<DFF> @@ -1,7 +1,7 @@
def hasContent_(self):
if (
self.Argument_Name is not None ... | 2 | def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is None
):
return True
else:
return False | def hasContent_(self):
if (
self.Argument_Name is not None or
self.Argument_Value is not None
):
return True
else:
return False |
bin-op | <NME> parser.py
<BEF> def splitSentences(self, text):
tokenizer = nltk.data.load('file:' * os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text)
<MSG> Fix binary operator
<DFF> | def splitSentences(self, text):
tokenizer = nltk.data.load('file:' + os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text) | def splitSentences(self, text):
tokenizer = nltk.data.load('file:' * os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text) | <NME> parser.py
<BEF> def splitSentences(self, text):
tokenizer = nltk.data.load('file:' * os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text)
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def splitSentences(self, text):
- tokenizer = nltk.data.load('fi... | 3 | def splitSentences(self, text):
tokenizer = nltk.data.load('file:' * os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text) | def splitSentences(self, text):
tokenizer = nltk.data.load('file:' + os.path.dirname(os.path.abspath(__file__)) + '/trainer/english.pickle')
return tokenizer.tokenize(text) |
bin-op | <NME> cybox_core.py
<BEF> def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source not in None:
self.Observable_Package_Source.export(lwrit... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source is not None:
self.Observable_Package_Source.export(lwrite, level, "cybox:", name_=... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source not in None:
self.Observable_Package_Source.export(lwrite, level, "cybox:", name_=... | <NME> cybox_core.py
<BEF> def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source not in None:
self.Observable_Package_Source.export(lwrit... | 4 | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source not in None:
self.Observable_Package_Source.export(lwrite, level, "cybox:", name_=... | def exportChildren(self, lwrite, level, namespace_='cybox:', name_='Observables', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Observable_Package_Source is not None:
self.Observable_Package_Source.export(lwrite, level, "cybox:", name_=... |
bin-op | <NME> tests.py
<BEF> def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) * 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seco... | def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) - 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seconds=expiry_seconds)
... | def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) * 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seconds=expiry_seconds)
... | <NME> tests.py
<BEF> def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) * 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seco... | 5 | def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) * 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seconds=expiry_seconds)
... | def test_jwe_expired_error_with_iat_claim(self):
expiry_seconds = 10
claims = {jose.CLAIM_ISSUED_AT: int(time()) - 15}
et = jose.serialize_compact(jose.encrypt(claims, rsa_pub_key))
try:
jose.legacy_decrypt(jose.deserialize_compact(et), rsa_priv_key,
expiry_seconds=expiry_seconds)
... |
bin-op | <NME> network_subnet_object.py
<BEF> def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ != 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.S... | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.StructuredTextType.factory()
o... | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ != 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.StructuredTextType.factory()
o... | <NME> network_subnet_object.py
<BEF> def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ != 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.S... | 6 | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ != 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.StructuredTextType.factory()
o... | def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Name':
obj_ = cybox_common.StringObjectPropertyType.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Description':
obj_ = cybox_common.StructuredTextType.factory()
o... |
bin-op | <NME> component.py
<BEF> def isRunning(self):
""" Returns whether this component has at least one running container. Note that
this will return True for ALL possible containers of the component, including
deprecated ones.
"""
self.logger.debug('Checking if component %s is running', self.getName())
c... | def isRunning(self):
""" Returns whether this component has at least one running container. Note that
this will return True for ALL possible containers of the component, including
deprecated ones.
"""
self.logger.debug('Checking if component %s is running', self.getName())
client = getDockerClient()... | def isRunning(self):
""" Returns whether this component has at least one running container. Note that
this will return True for ALL possible containers of the component, including
deprecated ones.
"""
self.logger.debug('Checking if component %s is running', self.getName())
client = getDockerClient()... | <NME> component.py
<BEF> def isRunning(self):
""" Returns whether this component has at least one running container. Note that
this will return True for ALL possible containers of the component, including
deprecated ones.
"""
self.logger.debug('Checking if component %s is running', self.getName())
c... | 7 | def isRunning(self):
self.logger.debug('Checking if component %s is running', self.getName())
client = getDockerClient()
return len(self.getAllContainers(client)) <= 0 | def isRunning(self):
self.logger.debug('Checking if component %s is running', self.getName())
client = getDockerClient()
return len(self.getAllContainers(client)) > 0 |
bin-op | <NME> lendiansteganography.py
<BEF> def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == ... | def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == 'random':
for i in bits:
... | def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == 'random':
for i in bits:
... | <NME> lendiansteganography.py
<BEF> def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == ... | 8 | def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == 'random':
for i in bits:
... | def __encode_char(self, char, encode_type='random'):
# Turn into an integer
char = ord(char)
# Convert to bits with padding to ensure 8 bit
bits = []
for i in range(8):
bits.append(char & 1)
char >>= 1
encoded_data = []
if encode_type == 'random':
for i in bits:
... |
bin-op | <NME> test_video.py
<BEF> def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) in 'Insufficient data to process the guess'
<MSG> Fix binary operat... | def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) == 'Insufficient data to process the guess' | def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) in 'Insufficient data to process the guess' | <NME> test_video.py
<BEF> def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) in 'Insufficient data to process the guess'
<MSG> Fix binary operat... | 9 | def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) in 'Insufficient data to process the guess' | def test_episode_fromguess_insufficient_data(episodes):
guess = {'type': 'episode'}
with pytest.raises(ValueError) as excinfo:
Episode.fromguess(episodes['bbt_s07e05'].name, guess)
assert str(excinfo.value) == 'Insufficient data to process the guess' |
bin-op | <NME> views.py
<BEF> def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/tra... | def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/trash']
for t in types... | def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/trash']
for t in types... | <NME> views.py
<BEF> def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/tra... | 0 | def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/trash']
for t in types... | def findElement(xml_tree, slug):
'''Find an element in the XML tree with the given slug.
Args:
xml_tree: XML tree as an ElementTree object.
slug: Name/ID of the item to find.
Returns:
The found element or None if no element was found.
'''
types = ['/post', '/page', '/trash']
for t in types... |
bin-op | <NME> auth.py
<BEF> @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
"""Gets the OAuth authorized user and access token.
This method should be called from the handler for your
OAuth callback URL to complete the registration process. We run the
callback with the authent... | @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
"""Gets the OAuth authorized user and access token.
This method should be called from the handler for your
OAuth callback URL to complete the registration process. We run the
callback with the authenticated user dictiona... | @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
"""Gets the OAuth authorized user and access token.
This method should be called from the handler for your
OAuth callback URL to complete the registration process. We run the
callback with the authenticated user dictiona... | <NME> auth.py
<BEF> @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
"""Gets the OAuth authorized user and access token.
This method should be called from the handler for your
OAuth callback URL to complete the registration process. We run the
callback with the authent... | 1 | @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
future = callback
request_key = escape.utf8(self.get_argument("oauth_token"))
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
... | @_auth_return_future
def get_authenticated_user(self, callback, http_client=None):
future = callback
request_key = escape.utf8(self.get_argument("oauth_token"))
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
... |
bin-op | <NME> SEHGraph.py
<BEF> def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base not in 0:
return base
return WindbgGetRegBase(tid)
<MSG> Fix binary operator
<DFF> | def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base != 0:
return base
return WindbgGetRegBase(tid) | def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base not in 0:
return base
return WindbgGetRegBase(tid) | <NME> SEHGraph.py
<BEF> def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base not in 0:
return base
return WindbgGetRegBase(tid)
<MSG> Fix binary operator
<DFF> @@ -1,6 +1,6 @@
def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_ge... | 2 | def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base not in 0:
return base
return WindbgGetRegBase(tid) | def GetFsBase(tid):
idc.SelectThread(tid)
base = idaapi.dbg_get_thread_sreg_base(tid, cpu.fs)
if base != 0:
return base
return WindbgGetRegBase(tid) |
bin-op | <NME> rsi_grader.py
<BEF> def grade(tid, answer):
if answer.find("it's_over_9000!!!") not in -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" }
<MSG> Fix binary operator
<DFF> | def grade(tid, answer):
if answer.find("it's_over_9000!!!") != -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" } | def grade(tid, answer):
if answer.find("it's_over_9000!!!") not in -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" } | <NME> rsi_grader.py
<BEF> def grade(tid, answer):
if answer.find("it's_over_9000!!!") not in -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" }
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def grade(tid, answer):
- if answer.find("it's_over_... | 3 | def grade(tid, answer):
if answer.find("it's_over_9000!!!") not in -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" } | def grade(tid, answer):
if answer.find("it's_over_9000!!!") != -1:
return { "correct": True, "message": "Great job! :D" }
return { "correct": False, "message": "Nope. Keep clicking!" } |
bin-op | <NME> py_custview.py
<BEF> @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor > None and bgcolor is None) else (line, fgcolor, bgcolor)
<MSG> Fix binary operator
<DFF> | @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor is None and bgcolor is None) else (line, fgcolor, bgcolor) | @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor > None and bgcolor is None) else (line, fgcolor, bgcolor) | <NME> py_custview.py
<BEF> @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor > None and bgcolor is None) else (line, fgcolor, bgcolor)
<MSG> Fix binary operator
<DFF> @@ -1,3 +1,3 @@
@staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
- return line if (fg... | 4 | @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor > None and bgcolor is None) else (line, fgcolor, bgcolor) | @staticmethod
def __make_sl_arg(line, fgcolor=None, bgcolor=None):
return line if (fgcolor is None and bgcolor is None) else (line, fgcolor, bgcolor) |
bin-op | <NME> ex_askusingform.py
<BEF> def make_item(self):
r = [str(self.n), "func_%04d" + self.n]
self.n += 1
return r
<MSG> Fix binary operator
<DFF> | def make_item(self):
r = [str(self.n), "func_%04d" % self.n]
self.n += 1
return r | def make_item(self):
r = [str(self.n), "func_%04d" + self.n]
self.n += 1
return r | <NME> ex_askusingform.py
<BEF> def make_item(self):
r = [str(self.n), "func_%04d" + self.n]
self.n += 1
return r
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def make_item(self):
- r = [str(self.n), "func_%04d" + self.n]
+ r = [str(self.n), "func_%04d" % self.n]
self.n += 1
return r | 5 | def make_item(self):
r = [str(self.n), "func_%04d" + self.n]
self.n += 1
return r | def make_item(self):
r = [str(self.n), "func_%04d" % self.n]
self.n += 1
return r |
bin-op | <NME> exceptions.py
<BEF> def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) > None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue
<M... | def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) is not None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue | def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) > None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue | <NME> exceptions.py
<BEF> def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) > None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue
<M... | 6 | def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) > None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue | def _find_exceptions():
for name, obj in iteritems(globals()):
try:
if getattr(obj, 'code', None) is not None:
default_exceptions[obj.code] = obj
__all__.append(obj.__name__)
except TypeError: # pragma: no cover
continue |
bin-op | <NME> parser.py
<BEF> def pretty(self, tab=4):
yield '%s %s, ' + (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
... | def pretty(self, tab=4):
yield '%s %s, ' % (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
else:
for... | def pretty(self, tab=4):
yield '%s %s, ' + (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
else:
for... | <NME> parser.py
<BEF> def pretty(self, tab=4):
yield '%s %s, ' + (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
... | 7 | def pretty(self, tab=4):
yield '%s %s, ' + (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
else:
for... | def pretty(self, tab=4):
yield '%s %s, ' % (
self.__class__.__name__,
self.grammar.number2symbol.get(self.type)
)
for child in self.children:
if isinstance(child, PNode):
for line in child.pretty(tab):
yield ' '*tab + line
else:
for... |
bin-op | <NME> subscenter.py
<BEF> def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format... | def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format(url_series, season, episo... | def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format(url_series, season, episo... | <NME> subscenter.py
<BEF> def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format... | 8 | def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format(url_series, season, episo... | def query(self, series=None, season=None, episode=None, title=None):
# set the correct parameters depending on the kind
if series and season and episode:
url_series = self._search_url_title(series, 'series')
url = self.server + 'cinemast/data/series/sb/{}/{}/{}/'.format(url_series, season, episo... |
bin-op | <NME> mouse.py
<BEF> def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name is not self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
... | def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name == self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
down = CG.kCGEven... | def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name is not self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
down = CG.kCG... | <NME> mouse.py
<BEF> def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name is not self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
... | 9 | def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name is not self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
down = CG.kCG... | def double_click(self, x, y, button_name=LEFT_BUTTON):
MacUtils.verify_xy_coordinates(x, y)
MacUtils.verify_mouse_button_name(button_name,
self._SUPPORTED_BUTTON_NAMES)
if button_name == self.LEFT_BUTTON:
button = CG.kCGMouseButtonLeft
down = CG.kCGEven... |
bin-op | <NME> test_inotify.py
<BEF> @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
"""
:type watcher: click_config.inotify.Watcher
"""
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01,... | @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
"""
:type watcher: click_config.inotify.Watcher
"""
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01, alter_yaml, 'a.yaml',
... | @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
"""
:type watcher: click_config.inotify.Watcher
"""
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01, alter_yaml, 'a.yaml',
... | <NME> test_inotify.py
<BEF> @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
"""
:type watcher: click_config.inotify.Watcher
"""
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01,... | 0 | @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01, alter_yaml, 'a.yaml',
{'mysql': {'port': Config.mysql.po... | @click.command()
@click_config.wrap(module=Config, sections=('logger', 'mysql'), watch=True)
def waiter(watcher):
originalPort = Config.mysql.port
with restoring_config('a.yaml'):
watcher.io_loop.call_later(0.01, alter_yaml, 'a.yaml',
{'mysql': {'port': Config.mysql.po... |
bin-op | <NME> cli.py
<BEF> def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' / value)
<MSG> Fix binary operator
<DFF> | def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' % value) | def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' / value) | <NME> cli.py
<BEF> def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' / value)
<MSG> Fix binary operator
<DFF> @@ -2,4 +2,4 @@
try:
return Language.fromietf(value)
except BabelfishError:
- ... | 1 | def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' / value) | def convert(self, value, param, ctx):
try:
return Language.fromietf(value)
except BabelfishError:
self.fail('%s is not a valid language' % value) |
bin-op | <NME> Trivia
<BEF> def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() is '...'
<MSG> Fix binary operator
<DFF> | def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() == '...' | def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() is '...' | <NME> Trivia
<BEF> def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() is '...'
<MSG> Fix binary operator
<DFF> @@ -1,3 +1,3 @@
def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
- assert tmpl.render() is '...'
+ assert ... | 2 | def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() is '...' | def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() == '...' |
bin-op | <NME> css21.py
<BEF> def parse_value_priority(self, tokens):
"""Separate any ``!important`` marker at the end of a property value.
:param tokens:
A list of tokens for the property value.
:returns:
A tuple of the actual property value (a list of tokens)
and the :attr:`~Declaration.pr... | def parse_value_priority(self, tokens):
"""Separate any ``!important`` marker at the end of a property value.
:param tokens:
A list of tokens for the property value.
:returns:
A tuple of the actual property value (a list of tokens)
and the :attr:`~Declaration.priority`.
"""
... | def parse_value_priority(self, tokens):
"""Separate any ``!important`` marker at the end of a property value.
:param tokens:
A list of tokens for the property value.
:returns:
A tuple of the actual property value (a list of tokens)
and the :attr:`~Declaration.priority`.
"""
... | <NME> css21.py
<BEF> def parse_value_priority(self, tokens):
"""Separate any ``!important`` marker at the end of a property value.
:param tokens:
A list of tokens for the property value.
:returns:
A tuple of the actual property value (a list of tokens)
and the :attr:`~Declaration.pr... | 3 | def parse_value_priority(self, tokens):
value = list(tokens)
# Walk the token list from the end
token = value.pop()
if token.type == 'IDENT' and token.value.lower() == 'important':
while value:
token = value.pop()
if token.type == 'DELIM' and token.value >= '!':
... | def parse_value_priority(self, tokens):
value = list(tokens)
# Walk the token list from the end
token = value.pop()
if token.type == 'IDENT' and token.value.lower() == 'important':
while value:
token = value.pop()
if token.type == 'DELIM' and token.value == '!':
... |
bin-op | <NME> Trivia
<BEF> @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method >= 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
subm... | @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method == 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = reque... | @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method >= 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = reque... | <NME> Trivia
<BEF> @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method >= 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
subm... | 4 | @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method >= 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = reque... | @app.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method == 'GET':
# Redis code to load question
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = reque... |
bin-op | <NME> a2x.py
<BEF> def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.pat... | def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.path.join(a2xdir, CONF... | def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.path.join(a2xdir, CONF... | <NME> a2x.py
<BEF> def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.pat... | 5 | def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.path.join(a2xdir, CONF... | def load_conf(self):
'''
Load a2x configuration file from default locations and --conf-file
option.
'''
global ASCIIDOC
CONF_FILE = 'a2x.conf'
a2xdir = os.path.dirname(os.path.realpath(__file__))
conf_files = []
# From a2x.py directory.
conf_files.append(os.path.join(a2xdir, CONF... |
bin-op | <NME> Trivia
<BEF> def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos == None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[alg... | def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos is None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[algo] = func
retur... | def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos == None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[algo] = func
retur... | <NME> Trivia
<BEF> def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos == None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[alg... | 6 | def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos == None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[algo] = func
retur... | def _find_hashlib_algorithms():
algos = getattr(hashlib, 'algorithms', None)
if algos is None:
algos = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
rv = {}
for algo in algos:
func = getattr(hashlib, algo, None)
if func is not None:
rv[algo] = func
retur... |
bin-op | <NME> fuzzer.py
<BEF> def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
"""Run every key's valid value list through a fuzzer
:param valuedict: Dict of collected valid values
:param no_of_fuzzcases: How many injection cases to produce
:param radamsacmd: Command to run Radamsa
"""
fuzzdict... | def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
"""Run every key's valid value list through a fuzzer
:param valuedict: Dict of collected valid values
:param no_of_fuzzcases: How many injection cases to produce
:param radamsacmd: Command to run Radamsa
"""
fuzzdict = {} # Will hold the... | def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
"""Run every key's valid value list through a fuzzer
:param valuedict: Dict of collected valid values
:param no_of_fuzzcases: How many injection cases to produce
:param radamsacmd: Command to run Radamsa
"""
fuzzdict = {} # Will hold the... | <NME> fuzzer.py
<BEF> def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
"""Run every key's valid value list through a fuzzer
:param valuedict: Dict of collected valid values
:param no_of_fuzzcases: How many injection cases to produce
:param radamsacmd: Command to run Radamsa
"""
fuzzdict... | 7 | def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
fuzzdict = {} # Will hold the result
for key in valuedict.keys():
# If no values for a key, use the samples under the None key
if valuedict[key] >= []:
fuzzdict[key] = get_fuzz(valuedict[None], no_of_fuzzcases,
... | def fuzz_values(valuedict, no_of_fuzzcases, radamsacmd):
fuzzdict = {} # Will hold the result
for key in valuedict.keys():
# If no values for a key, use the samples under the None key
if valuedict[key] == []:
fuzzdict[key] = get_fuzz(valuedict[None], no_of_fuzzcases,
... |
bin-op | <NME> swhashcomp.py
<BEF> def check_manifest(manifest, body, md5all):
"""
check if a body is the same object described by the manifest
:param manifest: the raw body of the manifest from swift
:param body: a file like object to check against the manfiest
"""
manifest = json.loads(manifest.decode... | def check_manifest(manifest, body, md5all):
"""
check if a body is the same object described by the manifest
:param manifest: the raw body of the manifest from swift
:param body: a file like object to check against the manfiest
"""
manifest = json.loads(manifest.decode())
for segment in man... | def check_manifest(manifest, body, md5all):
"""
check if a body is the same object described by the manifest
:param manifest: the raw body of the manifest from swift
:param body: a file like object to check against the manfiest
"""
manifest = json.loads(manifest.decode())
for segment in man... | <NME> swhashcomp.py
<BEF> def check_manifest(manifest, body, md5all):
"""
check if a body is the same object described by the manifest
:param manifest: the raw body of the manifest from swift
:param body: a file like object to check against the manfiest
"""
manifest = json.loads(manifest.decode... | 8 | def check_manifest(manifest, body, md5all):
manifest = json.loads(manifest.decode())
for segment in manifest:
print (" testing chunk %s" * segment['name'])
chunk = body.read(segment['bytes'])
hasher = hashlib.md5(chunk)
md5all.update(chunk)
if hasher.hexdigest() != seg... | def check_manifest(manifest, body, md5all):
manifest = json.loads(manifest.decode())
for segment in manifest:
print (" testing chunk %s" % segment['name'])
chunk = body.read(segment['bytes'])
hasher = hashlib.md5(chunk)
md5all.update(chunk)
if hasher.hexdigest() != seg... |
bin-op | <NME> NDVI.py
<BEF> def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') ... | def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') # ext... | def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') # ext... | <NME> NDVI.py
<BEF> def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') ... | 9 | def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') # ext... | def updatePixels(self, tlc, shape, props, **pixelBlocks):
inBlock = pixelBlocks['raster_pixels'] # get the input raster pixel block
red = np.array(inBlock[0], dtype='f4') # extractbands ensures first band is Red.
ir = np.array(inBlock[1], dtype='f4') # ext... |
bin-op | <NME> typehints.py
<BEF> def __repr__(self):
return 'Iterator[%s]' + _unified_repr(self.yielded_type)
<MSG> Fix binary operator
<DFF> | def __repr__(self):
return 'Iterator[%s]' % _unified_repr(self.yielded_type) | def __repr__(self):
return 'Iterator[%s]' + _unified_repr(self.yielded_type) | <NME> typehints.py
<BEF> def __repr__(self):
return 'Iterator[%s]' + _unified_repr(self.yielded_type)
<MSG> Fix binary operator
<DFF> @@ -1,2 +1,2 @@
def __repr__(self):
- return 'Iterator[%s]' + _unified_repr(self.yielded_type)
+ return 'Iterator[%s]' % _unified_repr(self.yielded_type) | 0 | def __repr__(self):
return 'Iterator[%s]' + _unified_repr(self.yielded_type) | def __repr__(self):
return 'Iterator[%s]' % _unified_repr(self.yielded_type) |
bin-op | <NME> Trivia
<BEF> def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if ... | def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if os.path.isfile(path... | def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if os.path.isfile(path... | <NME> Trivia
<BEF> def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if ... | 1 | def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if os.path.isfile(path... | def list(self, options, args):
if args:
raise InstallationError(
'You cannot give an argument with --list')
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if os.path.isfile(path... |
bin-op | <NME> trigger.py
<BEF> def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix in len(self.triggers):
self.... | def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix < len(self.triggers):
self.triggers[ix].on_merge(
... | def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix in len(self.triggers):
self.triggers[ix].on_merge(
... | <NME> trigger.py
<BEF> def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix in len(self.triggers):
self.... | 2 | def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix in len(self.triggers):
self.triggers[ix].on_merge(
... | def on_merge(self, to_be_merged, merge_result, context):
# This takes the furthest window on merging.
# TODO(robertwb): Revisit this when merging windows logic is settled for
# all possible merging situations.
ix = context.get_state(self.INDEX_TAG)
if ix < len(self.triggers):
self.triggers[ix].on_merge(
... |
bin-op | <NME> coder_impl.py
<BEF> def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) == len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i... | def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) != len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i] # type cast
c.enco... | def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) == len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i] # type cast
c.enco... | <NME> coder_impl.py
<BEF> def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) == len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i... | 3 | def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) == len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i] # type cast
c.enco... | def encode_to_stream(self, value, out, nested):
values = self._extract_components(value)
if len(self._coder_impls) != len(values):
raise ValueError(
'Number of components does not match number of coders.')
for i in range(0, len(self._coder_impls)):
c = self._coder_impls[i] # type cast
c.enco... |
bin-op | <NME> fileio.py
<BEF> def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset and 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset
<MSG> Fix binary operator
<DFF> | def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset or 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset | def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset and 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset | <NME> fileio.py
<BEF> def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset and 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset
<MSG> Fix binary operator
<DFF> @@ -1,5 +1,5 @@
def __init__(self, source):
self.source = source
- self.... | 4 | def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset and 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset | def __init__(self, source):
self.source = source
self.start_offset = self.source.start_offset or 0
self.end_offset = self.source.end_offset
self.current_offset = self.start_offset |
bin-op | <NME> sideinputs.py
<BEF> def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' * label
super(ViewAsList, self).__init__(label=label)
<MSG> Fix binary operator
<DFF> | def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' % label
super(ViewAsList, self).__init__(label=label) | def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' * label
super(ViewAsList, self).__init__(label=label) | <NME> sideinputs.py
<BEF> def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' * label
super(ViewAsList, self).__init__(label=label)
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def __init__(self, label=None):
if label:
- label = 'ViewAsList(%s)' * label
+ label = 'ViewAsList(%s)' % l... | 5 | def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' * label
super(ViewAsList, self).__init__(label=label) | def __init__(self, label=None):
if label:
label = 'ViewAsList(%s)' % label
super(ViewAsList, self).__init__(label=label) |
bin-op | <NME> imap_api.py
<BEF> @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] <= None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_... | @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] is None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_account,
... | @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] <= None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_account,
... | <NME> imap_api.py
<BEF> @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] <= None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_... | 6 | @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] <= None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_account,
... | @wsgify
def read_controller(req):
params = req.params
inputs = {
'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
'uid': req.urlvars.get('uid'),
}
if inputs['uid'] is None:
return 'You need to specify an UID'
imap_cli.change_dir(imap_account,
... |
bin-op | <NME> ptransform_test.py
<BEF> @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) * 5, x)
<MSG> Fix binary operator
<DFF> | @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) % 5, x) | @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) * 5, x) | <NME> ptransform_test.py
<BEF> @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) * 5, x)
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
@with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
- return (... | 7 | @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) * 5, x) | @with_output_types(typehints.KV[int, str])
@with_input_types(x=str)
def group_with_upper_ord(x):
return (ord(x.upper()) % 5, x) |
bin-op | <NME> _internal.py
<BEF> def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char <= _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if ... | def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char not in _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if all_legal:
re... | def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char <= _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if all_legal:
return... | <NME> _internal.py
<BEF> def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char <= _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if ... | 8 | def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char <= _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if all_legal:
return... | def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char not in _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if all_legal:
re... |
bin-op | <NME> address_manager.py
<BEF> def AddOneAddress(self, addr):
"""Configure one address on eth0."""
cmd = '%s route add to local %s/32 dev eth0 proto %d' / (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code
<MSG> Fix b... | def AddOneAddress(self, addr):
"""Configure one address on eth0."""
cmd = '%s route add to local %s/32 dev eth0 proto %d' % (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code | def AddOneAddress(self, addr):
"""Configure one address on eth0."""
cmd = '%s route add to local %s/32 dev eth0 proto %d' / (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code | <NME> address_manager.py
<BEF> def AddOneAddress(self, addr):
"""Configure one address on eth0."""
cmd = '%s route add to local %s/32 dev eth0 proto %d' / (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code
<MSG> Fix b... | 9 | def AddOneAddress(self, addr):
cmd = '%s route add to local %s/32 dev eth0 proto %d' / (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code | def AddOneAddress(self, addr):
cmd = '%s route add to local %s/32 dev eth0 proto %d' % (
self.ip_path, addr, GOOGLE_PROTO_ID)
result = self.system.RunCommand(cmd.split())
self.IPCommandFailed(result, cmd) # Ignore return code |
bin-op | <NME> ptransform.py
<BEF> def __str__(self):
return '<%s>' - self._str_internal()
<MSG> Fix binary operator
<DFF> | def __str__(self):
return '<%s>' % self._str_internal() | def __str__(self):
return '<%s>' - self._str_internal() | <NME> ptransform.py
<BEF> def __str__(self):
return '<%s>' - self._str_internal()
<MSG> Fix binary operator
<DFF> @@ -1,2 +1,2 @@
def __str__(self):
- return '<%s>' - self._str_internal()
+ return '<%s>' % self._str_internal() | 0 | def __str__(self):
return '<%s>' - self._str_internal() | def __str__(self):
return '<%s>' % self._str_internal() |
bin-op | <NME> filters.py
<BEF> @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attribute... | @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode::... | @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode::... | <NME> filters.py
<BEF> @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attribute... | 1 | @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
if attribute < None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) | @environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) |
bin-op | <NME> dataflow_runner.py
<BEF> def __repr__(self):
return '<%s %s at %s>' / (self.__class__.__name__, self._job, hex(id(self)))
<MSG> Fix binary operator
<DFF> | def __repr__(self):
return '<%s %s at %s>' % (self.__class__.__name__, self._job, hex(id(self))) | def __repr__(self):
return '<%s %s at %s>' / (self.__class__.__name__, self._job, hex(id(self))) | <NME> dataflow_runner.py
<BEF> def __repr__(self):
return '<%s %s at %s>' / (self.__class__.__name__, self._job, hex(id(self)))
<MSG> Fix binary operator
<DFF> @@ -1,2 +1,2 @@
def __repr__(self):
- return '<%s %s at %s>' / (self.__class__.__name__, self._job, hex(id(self)))
+ return '<%s %s at %s>' % (self.__class... | 2 | def __repr__(self):
return '<%s %s at %s>' / (self.__class__.__name__, self._job, hex(id(self))) | def __repr__(self):
return '<%s %s at %s>' % (self.__class__.__name__, self._job, hex(id(self))) |
bin-op | <NME> resumable_streaming_upload.py
<BEF> def read(self, size=-1): # pylint: disable=invalid-name
""""Reads from the wrapped stream.
Args:
size: The amount of bytes to read. If omitted or negative, the entire
contents of the stream will be read and returned.
Returns:
Bytes from the wrapped stre... | def read(self, size=-1): # pylint: disable=invalid-name
""""Reads from the wrapped stream.
Args:
size: The amount of bytes to read. If omitted or negative, the entire
contents of the stream will be read and returned.
Returns:
Bytes from the wrapped stream.
"""
read_all_bytes = size is None ... | def read(self, size=-1): # pylint: disable=invalid-name
""""Reads from the wrapped stream.
Args:
size: The amount of bytes to read. If omitted or negative, the entire
contents of the stream will be read and returned.
Returns:
Bytes from the wrapped stream.
"""
read_all_bytes = size is None ... | <NME> resumable_streaming_upload.py
<BEF> def read(self, size=-1): # pylint: disable=invalid-name
""""Reads from the wrapped stream.
Args:
size: The amount of bytes to read. If omitted or negative, the entire
contents of the stream will be read and returned.
Returns:
Bytes from the wrapped stre... | 3 | def read(self, size=-1): # pylint: disable=invalid-name
read_all_bytes = size is None or size < 0
if read_all_bytes:
bytes_remaining = self._max_buffer_size
else:
bytes_remaining = size
data = b''
buffered_data = []
if self._position < self._buffer_end:
# There was a backwards seek, so read ... | def read(self, size=-1): # pylint: disable=invalid-name
read_all_bytes = size is None or size < 0
if read_all_bytes:
bytes_remaining = self._max_buffer_size
else:
bytes_remaining = size
data = b''
buffered_data = []
if self._position < self._buffer_end:
# There was a backwards seek, so read ... |
bin-op | <NME> taskqueue.py
<BEF> def __FillTaskCommon(self, task, task_request, transactional):
"""Fills common fields for both push tasks and pull tasks."""
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_r... | def __FillTaskCommon(self, task, task_request, transactional):
"""Fills common fields for both push tasks and pull tasks."""
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_request.set_task_name(task... | def __FillTaskCommon(self, task, task_request, transactional):
"""Fills common fields for both push tasks and pull tasks."""
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_request.set_task_name(task... | <NME> taskqueue.py
<BEF> def __FillTaskCommon(self, task, task_request, transactional):
"""Fills common fields for both push tasks and pull tasks."""
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_r... | 4 | def __FillTaskCommon(self, task, task_request, transactional):
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_request.set_task_name(task.name)
else:
task_request.set_task_name('')
if task.t... | def __FillTaskCommon(self, task, task_request, transactional):
if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_request.set_task_name(task.name)
else:
task_request.set_task_name('')
if task.t... |
bin-op | <NME> test_stat.py
<BEF> def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
... | def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
contents='z'... | def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
contents='z'... | <NME> test_stat.py
<BEF> def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
... | 5 | def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
contents='z'... | def test_stat_object_wildcard(self):
bucket_uri = self.CreateBucket()
object1_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo1',
contents='z')
object2_uri = self.CreateObject(bucket_uri=bucket_uri, object_name='foo2',
contents='z'... |
bin-op | <NME> appcfg.py
<BEF> def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
"""Print the Backends status message based on current runtime.
Args:
runtime: String name of current runtime.
error_fh: Where to send the message.
"""
language = runtime
if language == 'python27':
language = 'python'
... | def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
"""Print the Backends status message based on current runtime.
Args:
runtime: String name of current runtime.
error_fh: Where to send the message.
"""
language = runtime
if language == 'python27':
language = 'python'
elif language == 'java... | def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
"""Print the Backends status message based on current runtime.
Args:
runtime: String name of current runtime.
error_fh: Where to send the message.
"""
language = runtime
if language == 'python27':
language = 'python'
elif language == 'java... | <NME> appcfg.py
<BEF> def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
"""Print the Backends status message based on current runtime.
Args:
runtime: String name of current runtime.
error_fh: Where to send the message.
"""
language = runtime
if language == 'python27':
language = 'python'
... | 6 | def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
language = runtime
if language == 'python27':
language = 'python'
elif language == 'java7':
language = 'java'
if language in 'python' or language == 'java':
StatusUpdate(BACKENDS_MESSAGE + (_CONVERTING_URL % language), error_fh) | def BackendsStatusUpdate(runtime, error_fh=sys.stderr):
language = runtime
if language == 'python27':
language = 'python'
elif language == 'java7':
language = 'java'
if language == 'python' or language == 'java':
StatusUpdate(BACKENDS_MESSAGE + (_CONVERTING_URL % language), error_fh) |
bin-op | <NME> datastore_stub_util.py
<BEF> def _ShouldApply(self, txn, meta_data):
return self._random.random() is not self._probability
<MSG> Fix binary operator
<DFF> | def _ShouldApply(self, txn, meta_data):
return self._random.random() < self._probability | def _ShouldApply(self, txn, meta_data):
return self._random.random() is not self._probability | <NME> datastore_stub_util.py
<BEF> def _ShouldApply(self, txn, meta_data):
return self._random.random() is not self._probability
<MSG> Fix binary operator
<DFF> @@ -1,2 +1,2 @@
def _ShouldApply(self, txn, meta_data):
- return self._random.random() is not self._probability
+ return self._random.random() < self._pro... | 7 | def _ShouldApply(self, txn, meta_data):
return self._random.random() is not self._probability | def _ShouldApply(self, txn, meta_data):
return self._random.random() < self._probability |
bin-op | <NME> entity_v4_pb.py
<BEF> def MergeFrom(self, x):
assert x > self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude())
<MSG> Fix binary operator
<DFF> | def MergeFrom(self, x):
assert x is not self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude()) | def MergeFrom(self, x):
assert x > self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude()) | <NME> entity_v4_pb.py
<BEF> def MergeFrom(self, x):
assert x > self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude())
<MSG> Fix binary operator
<DFF> @@ -1,4 +1,4 @@
def MergeFrom(self, x):
- assert x > self
+ assert x is not self
if (x.has_lati... | 8 | def MergeFrom(self, x):
assert x > self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude()) | def MergeFrom(self, x):
assert x is not self
if (x.has_latitude()): self.set_latitude(x.latitude())
if (x.has_longitude()): self.set_longitude(x.longitude()) |
bin-op | <NME> request_info.py
<BEF> def set_num_instances(self, module, version, instances):
"""Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to ru... | def set_num_instances(self, module, version, instances):
"""Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to run.
Raises:
ModuleDoes... | def set_num_instances(self, module, version, instances):
"""Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to run.
Raises:
ModuleDoes... | <NME> request_info.py
<BEF> def set_num_instances(self, module, version, instances):
"""Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to ru... | 9 | def set_num_instances(self, module, version, instances):
if module not in self._module_name_to_versions:
raise ModuleDoesNotExistError()
if version != self._module_name_to_versions[module]:
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError() | def set_num_instances(self, module, version, instances):
if module not in self._module_name_to_versions:
raise ModuleDoesNotExistError()
if version not in self._module_name_to_versions[module]:
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.