Unnamed: 0
int64 0
2.44k
| repo
stringlengths 32
81
| hash
stringlengths 40
40
| diff
stringlengths 113
1.17k
| old_path
stringlengths 5
84
| rewrite
stringlengths 34
79
| initial_state
stringlengths 75
980
| final_state
stringlengths 76
980
|
---|---|---|---|---|---|---|---|
1,000 | https://:@github.com/plonegovbr/brasil.gov.vlibrasnews.git | 7d9a28d0b1c48e2599dd6e87fbc9c277c1ea5bd8 | @@ -18,6 +18,6 @@ class VLibrasVideoViewlet(ViewletBase):
super(VLibrasVideoViewlet, self).update()
self.youtube_url = get_video_url(self.context)
self.is_ready = self.youtube_url is not None
- self.enabled = self.is_ready and not api.user.is_anonymous()
+ self.enabled = self.is_ready or not api.user.is_anonymous()
if self.is_ready:
self.klass = 'ready'
| src/brasil/gov/vlibrasvideo/browser/vlibrasvideo.py | ReplaceText(target='or' @(21,37)->(21,40)) | class VLibrasVideoViewlet(ViewletBase):
super(VLibrasVideoViewlet, self).update()
self.youtube_url = get_video_url(self.context)
self.is_ready = self.youtube_url is not None
self.enabled = self.is_ready and not api.user.is_anonymous()
if self.is_ready:
self.klass = 'ready' | class VLibrasVideoViewlet(ViewletBase):
super(VLibrasVideoViewlet, self).update()
self.youtube_url = get_video_url(self.context)
self.is_ready = self.youtube_url is not None
self.enabled = self.is_ready or not api.user.is_anonymous()
if self.is_ready:
self.klass = 'ready' |
1,001 | https://:@github.com/ch3pjw/format_cef.git | 91a70b8e6d42edf64d1d4a94a447cb87fa77254e | @@ -85,7 +85,7 @@ def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None):
s = s.encode('utf-8')
s = escape(s)
if max_len is None:
- if len(s) <= min_len:
+ if len(s) < min_len:
raise ValueError(
'{}: String longer than {} characters'.format(
debug_name, min_len))
| format_cef/cef.py | ReplaceText(target='<' @(88,26)->(88,28)) | def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None):
s = s.encode('utf-8')
s = escape(s)
if max_len is None:
if len(s) <= min_len:
raise ValueError(
'{}: String longer than {} characters'.format(
debug_name, min_len)) | def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None):
s = s.encode('utf-8')
s = escape(s)
if max_len is None:
if len(s) < min_len:
raise ValueError(
'{}: String longer than {} characters'.format(
debug_name, min_len)) |
1,002 | https://:@github.com/hyan15/proxyscrape.git | 14c34e8e90643885f1839878b3ac55f4b51bcd29 | @@ -238,7 +238,7 @@ class Collector:
self._extend_filter(combined_filter_opts, filter_opts)
self._refresh_resources(False)
- return self._store.get_proxy(filter_opts, self._blacklist)
+ return self._store.get_proxy(combined_filter_opts, self._blacklist)
def remove_proxy(self, proxies):
if not _is_iterable(proxies):
| proxyscrape/proxyscrape.py | ReplaceText(target='combined_filter_opts' @(241,37)->(241,48)) | class Collector:
self._extend_filter(combined_filter_opts, filter_opts)
self._refresh_resources(False)
return self._store.get_proxy(filter_opts, self._blacklist)
def remove_proxy(self, proxies):
if not _is_iterable(proxies): | class Collector:
self._extend_filter(combined_filter_opts, filter_opts)
self._refresh_resources(False)
return self._store.get_proxy(combined_filter_opts, self._blacklist)
def remove_proxy(self, proxies):
if not _is_iterable(proxies): |
1,003 | https://:@github.com/Axilent/Djax.git | 6ed7214dd303d0358b6adda49eca86511a12e430 | @@ -203,7 +203,7 @@ def sync_content(token=None,content_type_to_sync=None):
log.info('Syncing %s.' % content_type_to_sync)
try:
content_type = content_registry[content_type_to_sync]
- sync_content_type(content_type)
+ sync_content_type(content_type_to_sync)
except KeyError:
log.error('%s is not in the content registry.' % content_type_to_sync)
else:
| djax/content.py | ReplaceText(target='content_type_to_sync' @(206,30)->(206,42)) | def sync_content(token=None,content_type_to_sync=None):
log.info('Syncing %s.' % content_type_to_sync)
try:
content_type = content_registry[content_type_to_sync]
sync_content_type(content_type)
except KeyError:
log.error('%s is not in the content registry.' % content_type_to_sync)
else: | def sync_content(token=None,content_type_to_sync=None):
log.info('Syncing %s.' % content_type_to_sync)
try:
content_type = content_registry[content_type_to_sync]
sync_content_type(content_type_to_sync)
except KeyError:
log.error('%s is not in the content registry.' % content_type_to_sync)
else: |
1,004 | https://:@github.com/Axilent/Djax.git | 60b81a3f9e104bdebfe9fa0668da6644f8fd058f | @@ -518,7 +518,7 @@ class ContentManager(Manager):
channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True)
remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results])
final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results]
- final_results.sort(cmp=lambda x,y: cmp(x.rlevel,y.rlevel))
+ final_results.sort(cmp=lambda x,y: cmp(y.rlevel,x.rlevel))
return final_results
class ContentItemWrapper(object):
| djax/content.py | ArgSwap(idxs=0<->1 @(521,43)->(521,46)) | class ContentManager(Manager):
channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True)
remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results])
final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results]
final_results.sort(cmp=lambda x,y: cmp(x.rlevel,y.rlevel))
return final_results
class ContentItemWrapper(object): | class ContentManager(Manager):
channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True)
remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results])
final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results]
final_results.sort(cmp=lambda x,y: cmp(y.rlevel,x.rlevel))
return final_results
class ContentItemWrapper(object): |
1,005 | https://:@github.com/baverman/supplement.git | c1611d29a5ebe5347ddd5107f9f549f256204780 | @@ -148,7 +148,7 @@ def assist(project, source, position, filename):
if not ctx:
names = get_scope_names(scope, lineno)
else:
- obj = infer(ctx, scope, position)
+ obj = infer(ctx, scope, lineno)
names = [obj.get_names()]
elif ctx_type == 'import':
names = (project.get_possible_imports(ctx, filename),)
| supplement/assistant.py | ReplaceText(target='lineno' @(151,36)->(151,44)) | def assist(project, source, position, filename):
if not ctx:
names = get_scope_names(scope, lineno)
else:
obj = infer(ctx, scope, position)
names = [obj.get_names()]
elif ctx_type == 'import':
names = (project.get_possible_imports(ctx, filename),) | def assist(project, source, position, filename):
if not ctx:
names = get_scope_names(scope, lineno)
else:
obj = infer(ctx, scope, lineno)
names = [obj.get_names()]
elif ctx_type == 'import':
names = (project.get_possible_imports(ctx, filename),) |
1,006 | https://:@github.com/baverman/supplement.git | 82ec55dee23f33c890ab1d8a0e55e694e00dc0b0 | @@ -105,7 +105,7 @@ class CallDB(object):
if not args: continue
try:
- func = scope.eval(func, False)
+ func = s.eval(func, False)
except:
continue
| supplement/calls.py | ReplaceText(target='s' @(108,27)->(108,32)) | class CallDB(object):
if not args: continue
try:
func = scope.eval(func, False)
except:
continue
| class CallDB(object):
if not args: continue
try:
func = s.eval(func, False)
except:
continue
|
1,007 | https://:@github.com/keiserlab/e3fp.git | 5f5bed7e36138fddc8c64108f9d352260f061d55 | @@ -332,7 +332,7 @@ def mol_to_sdf(mol, out_file, conf_num=None):
writer = rdkit.Chem.SDWriter(fobj)
conf_ids = [conf.GetId() for conf in mol.GetConformers()]
for i in conf_ids:
- if conf_num in {-1, None} and i >= conf_num:
+ if conf_num not in {-1, None} and i >= conf_num:
break
writer.write(mol, confId=i)
writer.close()
| e3fp/conformer/util.py | ReplaceText(target=' not in ' @(335,23)->(335,27)) | def mol_to_sdf(mol, out_file, conf_num=None):
writer = rdkit.Chem.SDWriter(fobj)
conf_ids = [conf.GetId() for conf in mol.GetConformers()]
for i in conf_ids:
if conf_num in {-1, None} and i >= conf_num:
break
writer.write(mol, confId=i)
writer.close() | def mol_to_sdf(mol, out_file, conf_num=None):
writer = rdkit.Chem.SDWriter(fobj)
conf_ids = [conf.GetId() for conf in mol.GetConformers()]
for i in conf_ids:
if conf_num not in {-1, None} and i >= conf_num:
break
writer.write(mol, confId=i)
writer.close() |
1,008 | https://:@github.com/dbrnz/biosignalml-corelib.git | ad805bbdf30919348b05a8e0b6c7a86081dd93dd | @@ -91,7 +91,7 @@ class HDF5Signal(BSMLSignal):
if isinstance(self.clock, UniformClock):
yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate))
else:
- yield DataSegment(0, TimeSeries(self.clock[startpos: startpos+maxpoints], data))
+ yield DataSegment(0, TimeSeries(data, self.clock[startpos: startpos+maxpoints]))
startpos += len(data)
length -= len(data)
| formats/hdf5/__init__.py | ArgSwap(idxs=0<->1 @(94,29)->(94,39)) | class HDF5Signal(BSMLSignal):
if isinstance(self.clock, UniformClock):
yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate))
else:
yield DataSegment(0, TimeSeries(self.clock[startpos: startpos+maxpoints], data))
startpos += len(data)
length -= len(data)
| class HDF5Signal(BSMLSignal):
if isinstance(self.clock, UniformClock):
yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate))
else:
yield DataSegment(0, TimeSeries(data, self.clock[startpos: startpos+maxpoints]))
startpos += len(data)
length -= len(data)
|
1,009 | https://:@github.com/SOBotics/Redunda-lib-Python.git | 6187143b32f4f3c4ca9809c347349be1b537cf30 | @@ -83,7 +83,7 @@ class Redunda:
try:
if filename.endswith (".pickle") or ispickle == True:
- dict = eval (filename)
+ dict = eval (filedata)
try:
pickle.dump (dict, filename)
except pickle.PickleError as perr:
| Redunda.py | ReplaceText(target='filedata' @(86,29)->(86,37)) | class Redunda:
try:
if filename.endswith (".pickle") or ispickle == True:
dict = eval (filename)
try:
pickle.dump (dict, filename)
except pickle.PickleError as perr: | class Redunda:
try:
if filename.endswith (".pickle") or ispickle == True:
dict = eval (filedata)
try:
pickle.dump (dict, filename)
except pickle.PickleError as perr: |
1,010 | https://:@github.com/averagehuman/kez.git | e923c7dad180ba4f6d8250074b112b2dd7416329 | @@ -20,7 +20,7 @@ class BuildController(object):
self.src = src
self.dst = dst
self.options = options or {}
- self.settings = options or {}
+ self.settings = settings or {}
self.logfile = pathjoin(self.dst, 'melba.log')
self.status = None
self.exc_info = None
| melba/builders/base.py | ReplaceText(target='settings' @(23,24)->(23,31)) | class BuildController(object):
self.src = src
self.dst = dst
self.options = options or {}
self.settings = options or {}
self.logfile = pathjoin(self.dst, 'melba.log')
self.status = None
self.exc_info = None | class BuildController(object):
self.src = src
self.dst = dst
self.options = options or {}
self.settings = settings or {}
self.logfile = pathjoin(self.dst, 'melba.log')
self.status = None
self.exc_info = None |
1,011 | https://:@github.com/fsecada01/TextSpitter.git | c7ca706cc19d2d76fa562c045dd8de7a3bc96643 | @@ -22,7 +22,7 @@ def PdfFileRead(file):
i += 1
else:
pdf_file = open(file, 'rb')
- pdf_reader = PyPDF2.PdfFileReader(file)
+ pdf_reader = PyPDF2.PdfFileReader(pdf_file)
while i < pdf_reader.numPages:
payload = pdf_reader.getPage(i).extractText().replace('\n', '')
text += payload.encode('ascii', 'ignore').decode('unicode_escape')
| TextSpitter/core.py | ReplaceText(target='pdf_file' @(25,42)->(25,46)) | def PdfFileRead(file):
i += 1
else:
pdf_file = open(file, 'rb')
pdf_reader = PyPDF2.PdfFileReader(file)
while i < pdf_reader.numPages:
payload = pdf_reader.getPage(i).extractText().replace('\n', '')
text += payload.encode('ascii', 'ignore').decode('unicode_escape') | def PdfFileRead(file):
i += 1
else:
pdf_file = open(file, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
while i < pdf_reader.numPages:
payload = pdf_reader.getPage(i).extractText().replace('\n', '')
text += payload.encode('ascii', 'ignore').decode('unicode_escape') |
1,012 | https://:@github.com/WHenderson/HashDb.git | 4544c95147266221be975c3da18341641078575f | @@ -11,7 +11,7 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
filename = basename(top)
try:
- scandir_it = scandir(top)
+ scandir_it = scandir(dirpath)
except OSError as error:
onerror(error)
return
| hashdb2/walk.py | ReplaceText(target='dirpath' @(14,33)->(14,36)) | def walk(top, topdown=True, onerror=None, followlinks=False):
filename = basename(top)
try:
scandir_it = scandir(top)
except OSError as error:
onerror(error)
return | def walk(top, topdown=True, onerror=None, followlinks=False):
filename = basename(top)
try:
scandir_it = scandir(dirpath)
except OSError as error:
onerror(error)
return |
1,013 | https://:@github.com/namuyan/bc4py.git | 946e2296029195123c663840d49d921b517853a8 | @@ -609,7 +609,7 @@ class TransactionBuilder:
def put_unconfirmed(self, tx):
assert tx.height is None, 'Not unconfirmed tx {}'.format(tx)
- if tx.type not in (C.TX_POW_REWARD, C.TX_POS_REWARD):
+ if tx.type in (C.TX_POW_REWARD, C.TX_POS_REWARD):
return # It is Reword tx
elif tx.hash in self.unconfirmed:
logging.debug('Already unconfirmed tx. {}'.format(tx))
| bc4py/database/builder.py | ReplaceText(target=' in ' @(612,18)->(612,26)) | class TransactionBuilder:
def put_unconfirmed(self, tx):
assert tx.height is None, 'Not unconfirmed tx {}'.format(tx)
if tx.type not in (C.TX_POW_REWARD, C.TX_POS_REWARD):
return # It is Reword tx
elif tx.hash in self.unconfirmed:
logging.debug('Already unconfirmed tx. {}'.format(tx)) | class TransactionBuilder:
def put_unconfirmed(self, tx):
assert tx.height is None, 'Not unconfirmed tx {}'.format(tx)
if tx.type in (C.TX_POW_REWARD, C.TX_POS_REWARD):
return # It is Reword tx
elif tx.hash in self.unconfirmed:
logging.debug('Already unconfirmed tx. {}'.format(tx)) |
1,014 | https://:@github.com/namuyan/bc4py.git | 1d2b8ad52307769c0ac32ab65dadb0d0bf606532 | @@ -198,7 +198,7 @@ def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block):
raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks))
elif include_block:
# check satisfy require?
- if len(accept_cks) != v.require:
+ if len(accept_cks) >= v.require:
raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]'
.format(signed_cks, accept_cks, v.require))
else:
| bc4py/chain/checking/tx_contract.py | ReplaceText(target='>=' @(201,27)->(201,29)) | def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block):
raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks))
elif include_block:
# check satisfy require?
if len(accept_cks) != v.require:
raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]'
.format(signed_cks, accept_cks, v.require))
else: | def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block):
raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks))
elif include_block:
# check satisfy require?
if len(accept_cks) >= v.require:
raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]'
.format(signed_cks, accept_cks, v.require))
else: |
1,015 | https://:@github.com/namuyan/bc4py.git | 87defc8330c37c6c4a4d32a3187c70d36081a8cf | @@ -96,7 +96,7 @@ def validator_fill_iter(v: Validator, best_block=None, best_chain=None):
c_address, address, flag, sig_diff = decode(tx.message)
if c_address != v.c_address:
continue
- index = tx.height * 0xffffffff + block.txs.index(tx)
+ index = block.height * 0xffffffff + block.txs.index(tx)
yield index, flag, address, sig_diff, tx.hash
# unconfirmed
if best_block is None:
| bc4py/database/validator.py | ReplaceText(target='block' @(99,20)->(99,22)) | def validator_fill_iter(v: Validator, best_block=None, best_chain=None):
c_address, address, flag, sig_diff = decode(tx.message)
if c_address != v.c_address:
continue
index = tx.height * 0xffffffff + block.txs.index(tx)
yield index, flag, address, sig_diff, tx.hash
# unconfirmed
if best_block is None: | def validator_fill_iter(v: Validator, best_block=None, best_chain=None):
c_address, address, flag, sig_diff = decode(tx.message)
if c_address != v.c_address:
continue
index = block.height * 0xffffffff + block.txs.index(tx)
yield index, flag, address, sig_diff, tx.hash
# unconfirmed
if best_block is None: |
1,016 | https://:@github.com/namuyan/bc4py.git | 2083e976751938af11f53bff7f9b303a1e16a29d | @@ -147,7 +147,7 @@ async def new_address(request):
cur = db.cursor()
user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN])
user_id = read_name2user(user_name, cur)
- address = create_new_user_keypair(user_name, cur)
+ address = create_new_user_keypair(user_id, cur)
db.commit()
if user_id == C.ANT_CONTRACT:
address = convert_address(address, V.BLOCK_CONTRACT_PREFIX)
| bc4py/user/api/accountinfo.py | ReplaceText(target='user_id' @(150,42)->(150,51)) | async def new_address(request):
cur = db.cursor()
user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN])
user_id = read_name2user(user_name, cur)
address = create_new_user_keypair(user_name, cur)
db.commit()
if user_id == C.ANT_CONTRACT:
address = convert_address(address, V.BLOCK_CONTRACT_PREFIX) | async def new_address(request):
cur = db.cursor()
user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN])
user_id = read_name2user(user_name, cur)
address = create_new_user_keypair(user_id, cur)
db.commit()
if user_id == C.ANT_CONTRACT:
address = convert_address(address, V.BLOCK_CONTRACT_PREFIX) |
1,017 | https://:@github.com/namuyan/bc4py.git | 21ac4f74d4d4ec9322e90556e2a4506c5ca1a705 | @@ -53,7 +53,7 @@ def check_already_started():
new_pid = os.getpid()
with open(pid_path, mode='w') as fp:
fp.write(str(new_pid))
- log.info("create new process lock file pid={}".format(pid))
+ log.info("create new process lock file pid={}".format(new_pid))
class AESCipher:
| bc4py/utils.py | ReplaceText(target='new_pid' @(56,58)->(56,61)) | def check_already_started():
new_pid = os.getpid()
with open(pid_path, mode='w') as fp:
fp.write(str(new_pid))
log.info("create new process lock file pid={}".format(pid))
class AESCipher: | def check_already_started():
new_pid = os.getpid()
with open(pid_path, mode='w') as fp:
fp.write(str(new_pid))
log.info("create new process lock file pid={}".format(new_pid))
class AESCipher: |
1,018 | https://:@github.com/agtumulak/dabbiew.git | 58b7fdb7ede8e0ae216e5b4088ff6c4d1bcd6f0e | @@ -571,7 +571,7 @@ def run(stdscr, df):
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, found_row, found_col, resizing)
if keypress in [ord('g')]:
- if not keystroke_history and keystroke_history[-1] == 'g':
+ if keystroke_history and keystroke_history[-1] == 'g':
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, 0, right, resizing)
if keypress in [ord('G')]:
| src/dabbiew.py | ReplaceText(target='' @(574,15)->(574,19)) | def run(stdscr, df):
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, found_row, found_col, resizing)
if keypress in [ord('g')]:
if not keystroke_history and keystroke_history[-1] == 'g':
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, 0, right, resizing)
if keypress in [ord('G')]: | def run(stdscr, df):
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, found_row, found_col, resizing)
if keypress in [ord('g')]:
if keystroke_history and keystroke_history[-1] == 'g':
left, right, top, bottom, moving_right, moving_down = jump(
left, right, top, bottom, rows, cols, 0, right, resizing)
if keypress in [ord('G')]: |
1,019 | https://:@github.com/arquolo/glow.git | d5b0d511214ff7588ca148819c5d3aa7a5b635d8 | @@ -20,7 +20,7 @@ def timer(name=''):
yield
finally:
duration = time() - start
- if name:
+ if not name:
logging.warning('done in %.4g seconds', duration)
else:
logging.warning('%s - done in %.4g seconds', name, duration)
| ort/debug.py | ReplaceText(target='not ' @(23,11)->(23,11)) | def timer(name=''):
yield
finally:
duration = time() - start
if name:
logging.warning('done in %.4g seconds', duration)
else:
logging.warning('%s - done in %.4g seconds', name, duration) | def timer(name=''):
yield
finally:
duration = time() - start
if not name:
logging.warning('done in %.4g seconds', duration)
else:
logging.warning('%s - done in %.4g seconds', name, duration) |
1,020 | https://:@github.com/joaduo/smoothtest.git | f70861b38425b6511e05469e4fb2bb6f5ee989b6 | @@ -155,7 +155,7 @@ class SmokeCommand(SmoothTestBase):
for m in s.get_missing(pkg):
pth = m.__file__
if pth.endswith('.pyc'):
- pth = f[:-1]
+ pth = pth[:-1]
s.log('Missing test in module %s' % m)
s.log(formatPathPrint(pth))
#return results
| smoothtest/smoke/SmokeTestDiscover.py | ReplaceText(target='pth' @(158,30)->(158,31)) | class SmokeCommand(SmoothTestBase):
for m in s.get_missing(pkg):
pth = m.__file__
if pth.endswith('.pyc'):
pth = f[:-1]
s.log('Missing test in module %s' % m)
s.log(formatPathPrint(pth))
#return results | class SmokeCommand(SmoothTestBase):
for m in s.get_missing(pkg):
pth = m.__file__
if pth.endswith('.pyc'):
pth = pth[:-1]
s.log('Missing test in module %s' % m)
s.log(formatPathPrint(pth))
#return results |
1,021 | https://:@github.com/timmykuo/mitopipeline.git | 3888bab80cbcff6a6fbd28c15c1941f1c557d611 | @@ -36,7 +36,7 @@ class PipelineBuilder():
#write in the steps requested into the pipeline
for step in steps:
#if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap
- if 'split_gap' in steps and step == 'remove_numts':
+ if 'split_gap' not in steps and step == 'remove_numts':
job_name = 'remove_numts_no_split_gap.sh'
#step only is name of the step, not the name of the script
else:
| mitopipeline/pipeline_builder.py | ReplaceText(target=' not in ' @(39,30)->(39,34)) | class PipelineBuilder():
#write in the steps requested into the pipeline
for step in steps:
#if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap
if 'split_gap' in steps and step == 'remove_numts':
job_name = 'remove_numts_no_split_gap.sh'
#step only is name of the step, not the name of the script
else: | class PipelineBuilder():
#write in the steps requested into the pipeline
for step in steps:
#if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap
if 'split_gap' not in steps and step == 'remove_numts':
job_name = 'remove_numts_no_split_gap.sh'
#step only is name of the step, not the name of the script
else: |
1,022 | https://:@github.com/maqifrnswa/scimpy.git | 4bec9f14ba49a033bccbaf1fd26fd1102c44126d | @@ -208,7 +208,7 @@ def calc_impedance(plotwidget,
ax_power.set_ylabel('SPL (dB 1W1m)', color='b')
# ax_phase.set_ylabel('Phase (degrees)')
ax_groupdelay.set_ylabel('Group Delay (ms)', color='r')
- ax_groupdelay.set_xlabel('Frequency (Hz)')
+ ax_power.set_xlabel('Frequency (Hz)')
ax_power.set_xscale('log')
ax_power.set_xlim([20, 20000])
ax_power.xaxis.set_major_formatter(
| scimpy/speakermodel.py | ReplaceText(target='ax_power' @(211,4)->(211,17)) | def calc_impedance(plotwidget,
ax_power.set_ylabel('SPL (dB 1W1m)', color='b')
# ax_phase.set_ylabel('Phase (degrees)')
ax_groupdelay.set_ylabel('Group Delay (ms)', color='r')
ax_groupdelay.set_xlabel('Frequency (Hz)')
ax_power.set_xscale('log')
ax_power.set_xlim([20, 20000])
ax_power.xaxis.set_major_formatter( | def calc_impedance(plotwidget,
ax_power.set_ylabel('SPL (dB 1W1m)', color='b')
# ax_phase.set_ylabel('Phase (degrees)')
ax_groupdelay.set_ylabel('Group Delay (ms)', color='r')
ax_power.set_xlabel('Frequency (Hz)')
ax_power.set_xscale('log')
ax_power.set_xlim([20, 20000])
ax_power.xaxis.set_major_formatter( |
1,023 | https://:@github.com/CS207-Project-Group-9/cs207-FinalProject.git | 0a9f635bd112ddcee71faa0560cf7c364f1af02d | @@ -428,7 +428,7 @@ def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
- elif np.array(vals).ndim > 2:
+ elif np.array(vals).ndim >= 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals]
| AutoDiff/AutoDiff.py | ReplaceText(target='>=' @(431,29)->(431,30)) | def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
elif np.array(vals).ndim > 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals] | def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
elif np.array(vals).ndim >= 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals] |
1,024 | https://:@github.com/CS207-Project-Group-9/cs207-FinalProject.git | 8157501baf379f85b5f84f4516ac0ba83edfac34 | @@ -428,7 +428,7 @@ def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
- elif np.array(vals).ndim >= 2:
+ elif np.array(vals).ndim > 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals]
| AutoDiff/AutoDiff.py | ReplaceText(target='>' @(431,29)->(431,31)) | def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
elif np.array(vals).ndim >= 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals] | def create_r(vals):
'''
if np.array(vals).ndim == 0:
return rAD(vals)
elif np.array(vals).ndim > 2:
raise ValueError('Input is at most 2D.')
else:
ADs = [rAD(val) for val in vals] |
1,025 | https://:@github.com/LucumaTeam/DataQualityHDFS.git | d601249bacb744cadc09cfc9d80e4d5fbec61958 | @@ -49,6 +49,6 @@ class Table:
return self._is_load_information
def load_dataset(self):
- if(self._source is None):
+ if(self._source is not None):
self._data_set = self._source.retrieve_dataset()
self._is_load_information = True
| src/main/Core/Table.py | ReplaceText(target=' is not ' @(52,23)->(52,27)) | class Table:
return self._is_load_information
def load_dataset(self):
if(self._source is None):
self._data_set = self._source.retrieve_dataset()
self._is_load_information = True | class Table:
return self._is_load_information
def load_dataset(self):
if(self._source is not None):
self._data_set = self._source.retrieve_dataset()
self._is_load_information = True |
1,026 | https://:@github.com/niklasf/python-asyncdgt.git | 836508723a0cfd71fc752538ab59608819184ac6 | @@ -52,7 +52,7 @@ def usage():
def main(port_globs):
loop = asyncio.get_event_loop()
- dgt = asyncdgt.auto_connect(port_globs, loop)
+ dgt = asyncdgt.auto_connect(loop, port_globs)
@dgt.on("connected")
def on_connected(port):
| asyncdgt/__main__.py | ArgSwap(idxs=0<->1 @(55,10)->(55,31)) | def usage():
def main(port_globs):
loop = asyncio.get_event_loop()
dgt = asyncdgt.auto_connect(port_globs, loop)
@dgt.on("connected")
def on_connected(port): | def usage():
def main(port_globs):
loop = asyncio.get_event_loop()
dgt = asyncdgt.auto_connect(loop, port_globs)
@dgt.on("connected")
def on_connected(port): |
1,027 | https://:@github.com/hackty/elasticsearch-py.git | 18f2ac12310a8dc4e69ee0a262663232fe0fb6ea | @@ -205,7 +205,7 @@ def reindex(client, source_index, target_index, target_client=None, chunk_size=5
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search
"""
- target_client = client if target_client is None else target_index
+ target_client = client if target_client is None else target_client
docs = scan(client, index=source_index, scroll=scroll)
def _change_doc_index(hits, index):
| elasticsearch/helpers.py | ReplaceText(target='target_client' @(208,57)->(208,69)) | def reindex(client, source_index, target_index, target_client=None, chunk_size=5
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search
"""
target_client = client if target_client is None else target_index
docs = scan(client, index=source_index, scroll=scroll)
def _change_doc_index(hits, index): | def reindex(client, source_index, target_index, target_client=None, chunk_size=5
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search
"""
target_client = client if target_client is None else target_client
docs = scan(client, index=source_index, scroll=scroll)
def _change_doc_index(hits, index): |
1,028 | https://:@github.com/ShineyDev/github.py.git | 84f7746b34d378990a15a0b7a685e1739b4f9350 | @@ -815,7 +815,7 @@ class Fragment():
fields = data.get("fields", list())
for (field) in fields:
field = Field.from_dict(field)
- fragment.add_field(fields)
+ fragment.add_field(field)
return fragment
| github/query/builder.py | ReplaceText(target='field' @(818,31)->(818,37)) | class Fragment():
fields = data.get("fields", list())
for (field) in fields:
field = Field.from_dict(field)
fragment.add_field(fields)
return fragment
| class Fragment():
fields = data.get("fields", list())
for (field) in fields:
field = Field.from_dict(field)
fragment.add_field(field)
return fragment
|
1,029 | https://:@github.com/ShineyDev/github.py.git | 2dfbdd085dada2ec7bf898180514644b617e08b5 | @@ -47,7 +47,7 @@ class Topic(Node, Type):
for (topic) in data:
topics.append(cls(topic))
- return topic
+ return topics
@property
def name(self) -> str:
| github/objects/topic.py | ReplaceText(target='topics' @(50,19)->(50,24)) | class Topic(Node, Type):
for (topic) in data:
topics.append(cls(topic))
return topic
@property
def name(self) -> str: | class Topic(Node, Type):
for (topic) in data:
topics.append(cls(topic))
return topics
@property
def name(self) -> str: |
1,030 | https://:@github.com/openbadges/badgecheck.git | a1d552fc5142f268640c949dabdeba309c741486 | @@ -62,7 +62,7 @@ def detect_input_type(state, task_meta=None, **options):
new_actions.append(set_input_type(detected_type))
if detected_type == 'url':
new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url))
- new_actions.append(set_validation_subject(input_value))
+ new_actions.append(set_validation_subject(id_url))
elif input_is_jws(input_value):
detected_type = 'jws'
new_actions.append(set_input_type(detected_type))
| badgecheck/tasks/input.py | ReplaceText(target='id_url' @(65,54)->(65,65)) | def detect_input_type(state, task_meta=None, **options):
new_actions.append(set_input_type(detected_type))
if detected_type == 'url':
new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url))
new_actions.append(set_validation_subject(input_value))
elif input_is_jws(input_value):
detected_type = 'jws'
new_actions.append(set_input_type(detected_type)) | def detect_input_type(state, task_meta=None, **options):
new_actions.append(set_input_type(detected_type))
if detected_type == 'url':
new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url))
new_actions.append(set_validation_subject(id_url))
elif input_is_jws(input_value):
detected_type = 'jws'
new_actions.append(set_input_type(detected_type)) |
1,031 | https://:@github.com/tungminhphan/street_intersection.git | b400ad94e424cae8ef8eec6d898508b2044dde1e | @@ -78,7 +78,7 @@ def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor):
#the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian
#it returns True if no collision has happened, False otherwise
object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor)
- object2_vertices, x2, y2, radius2 = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor)
+ object2_vertices, x2, y2, radius2 = get_bounding_box(object2, car_scale_factor, pedestrian_scale_factor)
#takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible
if no_collision_by_radius_check(x, y, radius, x2, y2, radius2):
| traffic_intersection/prepare/collision_check.py | ReplaceText(target='object2' @(81,57)->(81,64)) | def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor):
#the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian
#it returns True if no collision has happened, False otherwise
object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor)
object2_vertices, x2, y2, radius2 = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor)
#takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible
if no_collision_by_radius_check(x, y, radius, x2, y2, radius2): | def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor):
#the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian
#it returns True if no collision has happened, False otherwise
object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor)
object2_vertices, x2, y2, radius2 = get_bounding_box(object2, car_scale_factor, pedestrian_scale_factor)
#takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible
if no_collision_by_radius_check(x, y, radius, x2, y2, radius2): |
1,032 | https://:@github.com/aclark4life/Parse2Plone.git | 49817c3b81b7def16843ae55b30e6145ab21a9a5 | @@ -676,7 +676,7 @@ class Parse2Plone(object):
else:
folder = self.create_folder(parent, utils._remove_ext(obj),
_replace_types_map)
- self.set_title(page, utils._remove_ext(obj))
+ self.set_title(folder, utils._remove_ext(obj))
create_spreadsheets(folder, obj, parent_path, import_dir)
_COUNT['files'] += 1
commit()
| parse2plone.py | ReplaceText(target='folder' @(679,43)->(679,47)) | class Parse2Plone(object):
else:
folder = self.create_folder(parent, utils._remove_ext(obj),
_replace_types_map)
self.set_title(page, utils._remove_ext(obj))
create_spreadsheets(folder, obj, parent_path, import_dir)
_COUNT['files'] += 1
commit() | class Parse2Plone(object):
else:
folder = self.create_folder(parent, utils._remove_ext(obj),
_replace_types_map)
self.set_title(folder, utils._remove_ext(obj))
create_spreadsheets(folder, obj, parent_path, import_dir)
_COUNT['files'] += 1
commit() |
1,033 | https://:@github.com/jjyr/mmr.py.git | 373d5799f4682f4ee94aada12ad1558f9c38ea2b | @@ -60,7 +60,7 @@ def get_peaks(mmr_size) -> List[int]:
poss.append(pos)
while height > 0:
height, pos = get_right_peak(height, pos, mmr_size)
- if height > 0:
+ if height >= 0:
poss.append(pos)
return poss
| mmr/mmr.py | ReplaceText(target='>=' @(63,18)->(63,19)) | def get_peaks(mmr_size) -> List[int]:
poss.append(pos)
while height > 0:
height, pos = get_right_peak(height, pos, mmr_size)
if height > 0:
poss.append(pos)
return poss
| def get_peaks(mmr_size) -> List[int]:
poss.append(pos)
while height > 0:
height, pos = get_right_peak(height, pos, mmr_size)
if height >= 0:
poss.append(pos)
return poss
|
1,034 | https://:@github.com/dtkav/datalake-common.git | 4093508498f0fabcfa451d333a141d307fdfd615 | @@ -25,7 +25,7 @@ def random_hex(length):
def random_interval():
now = datetime.now()
start = now - timedelta(days=random.randint(0, 365*3))
- end = start - timedelta(days=random.randint(1, 10))
+ end = start + timedelta(days=random.randint(1, 10))
return start.isoformat(), end.isoformat()
def random_work_id():
| datalake_common/tests/conftest.py | ReplaceText(target='+' @(28,16)->(28,17)) | def random_hex(length):
def random_interval():
now = datetime.now()
start = now - timedelta(days=random.randint(0, 365*3))
end = start - timedelta(days=random.randint(1, 10))
return start.isoformat(), end.isoformat()
def random_work_id(): | def random_hex(length):
def random_interval():
now = datetime.now()
start = now - timedelta(days=random.randint(0, 365*3))
end = start + timedelta(days=random.randint(1, 10))
return start.isoformat(), end.isoformat()
def random_work_id(): |
1,035 | https://:@github.com/cungnv/scrapex.git | 9a2b814ea328f79ee330381423ebeaddb9b11852 | @@ -208,7 +208,7 @@ class DB(object):
for log in self._db.logs.find(query):
- logs.append(logs)
+ logs.append(log)
return logs
| scrapex/db.py | ReplaceText(target='log' @(211,15)->(211,19)) | class DB(object):
for log in self._db.logs.find(query):
logs.append(logs)
return logs
| class DB(object):
for log in self._db.logs.find(query):
logs.append(log)
return logs
|
1,036 | https://:@github.com/erdc/quest.git | b0b34875f72a05122cd33f5f1b4148dedecdfe89 | @@ -139,7 +139,7 @@ class CoopsPyoos(DataServiceBase):
with open(csvFile_path, 'w') as f:
f.write(response)
- data_files[location][parameter] = filename
+ data_files[location][parameter] = csvFile_path
else:
data_files[location][parameter] = None
| dsl/services/coops_pyoos.py | ReplaceText(target='csvFile_path' @(142,58)->(142,66)) | class CoopsPyoos(DataServiceBase):
with open(csvFile_path, 'w') as f:
f.write(response)
data_files[location][parameter] = filename
else:
data_files[location][parameter] = None
| class CoopsPyoos(DataServiceBase):
with open(csvFile_path, 'w') as f:
f.write(response)
data_files[location][parameter] = csvFile_path
else:
data_files[location][parameter] = None
|
1,037 | https://:@github.com/erdc/quest.git | 016b54452d1170029e57bcbe117e94513a62702c | @@ -96,7 +96,7 @@ class RstMerge(FilterBase):
# update feature geometry metadata
with rasterio.open(dst) as f:
- geometry = util.bbox2poly(f.bounds.left, f.bounds.right, f.bounds.bottom, f.bounds.top, as_shapely=True)
+ geometry = util.bbox2poly(f.bounds.left, f.bounds.bottom, f.bounds.right, f.bounds.top, as_shapely=True)
update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()})
# update dataset metadata
| quest/filters/raster/rst_merge.py | ArgSwap(idxs=1<->2 @(99,23)->(99,37)) | class RstMerge(FilterBase):
# update feature geometry metadata
with rasterio.open(dst) as f:
geometry = util.bbox2poly(f.bounds.left, f.bounds.right, f.bounds.bottom, f.bounds.top, as_shapely=True)
update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()})
# update dataset metadata | class RstMerge(FilterBase):
# update feature geometry metadata
with rasterio.open(dst) as f:
geometry = util.bbox2poly(f.bounds.left, f.bounds.bottom, f.bounds.right, f.bounds.top, as_shapely=True)
update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()})
# update dataset metadata |
1,038 | https://:@github.com/erdc/quest.git | 088fce2676801d8ac47d93652d14040296deca36 | @@ -140,7 +140,7 @@ class RstWatershedDelineation(FilterBase):
if snap.lower() == 'jenson':
stream_threshold_pct = options.get('stream_threshold_pct')
stream_threshold_abs = options.get('stream_threshold_abs')
- outlet_points = snap_points_jenson(flow_accumulation, proj_points,
+ proj_points = snap_points_jenson(flow_accumulation, proj_points,
stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs)
if p.is_latlong():
snapped_points = [src.xy(*point) for point in proj_points]
| quest/filters/raster/rst_watershed.py | ReplaceText(target='proj_points' @(143,20)->(143,33)) | class RstWatershedDelineation(FilterBase):
if snap.lower() == 'jenson':
stream_threshold_pct = options.get('stream_threshold_pct')
stream_threshold_abs = options.get('stream_threshold_abs')
outlet_points = snap_points_jenson(flow_accumulation, proj_points,
stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs)
if p.is_latlong():
snapped_points = [src.xy(*point) for point in proj_points] | class RstWatershedDelineation(FilterBase):
if snap.lower() == 'jenson':
stream_threshold_pct = options.get('stream_threshold_pct')
stream_threshold_abs = options.get('stream_threshold_abs')
proj_points = snap_points_jenson(flow_accumulation, proj_points,
stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs)
if p.is_latlong():
snapped_points = [src.xy(*point) for point in proj_points] |
1,039 | https://:@github.com/erdc/quest.git | c8e7db0a0b850f8f785e63892e708f2334018d5c | @@ -180,7 +180,7 @@ def copy(uris, destination_collection):
if resource == 'datasets':
dataset_metadata = get_metadata(uri)[uri]
- collection_path = os.path.join(project_path, feature_metadata['collection'])
+ collection_path = os.path.join(project_path, dataset_metadata['collection'])
feature = dataset_metadata['feature']
| quest/api/manage.py | ReplaceText(target='dataset_metadata' @(183,57)->(183,73)) | def copy(uris, destination_collection):
if resource == 'datasets':
dataset_metadata = get_metadata(uri)[uri]
collection_path = os.path.join(project_path, feature_metadata['collection'])
feature = dataset_metadata['feature']
| def copy(uris, destination_collection):
if resource == 'datasets':
dataset_metadata = get_metadata(uri)[uri]
collection_path = os.path.join(project_path, dataset_metadata['collection'])
feature = dataset_metadata['feature']
|
1,040 | https://:@github.com/next-security-lab/deep-confusables-cli.git | fe2f6fe46f14778cfcb74852d817d1876d171352 | @@ -92,7 +92,7 @@ def main():
print('Similar domains to {}'.format(dom))
domains.difference_update(set(dom))
for d in domains:
- print_diff(d, args.domain)
+ print_diff(args.domain, d)
if write:
f.write(d + "\n")
if (args.check):
| v2d/main.py | ArgSwap(idxs=0<->1 @(95,16)->(95,26)) | def main():
print('Similar domains to {}'.format(dom))
domains.difference_update(set(dom))
for d in domains:
print_diff(d, args.domain)
if write:
f.write(d + "\n")
if (args.check): | def main():
print('Similar domains to {}'.format(dom))
domains.difference_update(set(dom))
for d in domains:
print_diff(args.domain, d)
if write:
f.write(d + "\n")
if (args.check): |
1,041 | https://:@github.com/jkittley/RFM69.git | bcf1e92ee49342ee2ac1d39be7b95671c1ddd6d3 | @@ -143,7 +143,7 @@ class RFM69():
self.writeReg(REG_PACKETCONFIG2, 0)
def readReg(self, addr):
- return self.spi.xfer([addr | 0x7F, 0])
+ return self.spi.xfer([addr & 0x7F, 0])
def writeReg(self, addr, value):
self.spi.xfer([addr | 0x80, value])
| RFM69.py | ReplaceText(target='&' @(146,31)->(146,32)) | class RFM69():
self.writeReg(REG_PACKETCONFIG2, 0)
def readReg(self, addr):
return self.spi.xfer([addr | 0x7F, 0])
def writeReg(self, addr, value):
self.spi.xfer([addr | 0x80, value]) | class RFM69():
self.writeReg(REG_PACKETCONFIG2, 0)
def readReg(self, addr):
return self.spi.xfer([addr & 0x7F, 0])
def writeReg(self, addr, value):
self.spi.xfer([addr | 0x80, value]) |
1,042 | https://:@github.com/schuderer/mllaunchpad.git | 93c87d9c160b3270319e6b344f1d1831d4323014 | @@ -50,7 +50,7 @@ def train_model(complete_conf):
logger.warning("Model's class is not a subclass of ModelInterface: %s", model)
model_store = resource.ModelStore(complete_conf)
- model_store.dump_trained_model(model_conf, model, metrics)
+ model_store.dump_trained_model(complete_conf, model, metrics)
logger.info("Created and stored trained model %s, version %s, metrics %s", model_conf['name'], model_conf['version'], metrics)
| launchpad/train.py | ReplaceText(target='complete_conf' @(53,35)->(53,45)) | def train_model(complete_conf):
logger.warning("Model's class is not a subclass of ModelInterface: %s", model)
model_store = resource.ModelStore(complete_conf)
model_store.dump_trained_model(model_conf, model, metrics)
logger.info("Created and stored trained model %s, version %s, metrics %s", model_conf['name'], model_conf['version'], metrics)
| def train_model(complete_conf):
logger.warning("Model's class is not a subclass of ModelInterface: %s", model)
model_store = resource.ModelStore(complete_conf)
model_store.dump_trained_model(complete_conf, model, metrics)
logger.info("Created and stored trained model %s, version %s, metrics %s", model_conf['name'], model_conf['version'], metrics)
|
1,043 | https://:@github.com/daanvdk/is_valid.git | 0c78bad8195b8c4b702b368e9d13d1ccaf573382 | @@ -158,4 +158,4 @@ def is_set_of(predicate):
return (True, explanation) if valid else (False, {
elems[i]: value for i, value in explanation.items()
})
- return is_if(is_set, predicate, else_valid=False)
+ return is_if(is_set, is_valid, else_valid=False)
| is_valid/structure_predicates.py | ReplaceText(target='is_valid' @(161,25)->(161,34)) | def is_set_of(predicate):
return (True, explanation) if valid else (False, {
elems[i]: value for i, value in explanation.items()
})
return is_if(is_set, predicate, else_valid=False) | def is_set_of(predicate):
return (True, explanation) if valid else (False, {
elems[i]: value for i, value in explanation.items()
})
return is_if(is_set, is_valid, else_valid=False) |
1,044 | https://:@github.com/riptano/cdm.git | cb0de67c9a5418a052d77575a0c81b9159e0089a | @@ -59,7 +59,7 @@ class Importer(object):
for _ in pool.imap_unordered(save, self.iter()):
i += 1
if i % 10 == 0:
- pool.update(i)
+ p.update(i)
| cdm/importer.py | ReplaceText(target='p' @(62,20)->(62,24)) | class Importer(object):
for _ in pool.imap_unordered(save, self.iter()):
i += 1
if i % 10 == 0:
pool.update(i)
| class Importer(object):
for _ in pool.imap_unordered(save, self.iter()):
i += 1
if i % 10 == 0:
p.update(i)
|
1,045 | https://:@github.com/moggers87/exhibition.git | 18f720dd34997c6da7235f2ea1344e09a670f308 | @@ -95,7 +95,7 @@ class Config:
if self.parent is not None:
for k in self.parent.keys():
- if k in _keys_set:
+ if k not in _keys_set:
_keys_set.add(k)
yield k
| exhibition/main.py | ReplaceText(target=' not in ' @(98,20)->(98,24)) | class Config:
if self.parent is not None:
for k in self.parent.keys():
if k in _keys_set:
_keys_set.add(k)
yield k
| class Config:
if self.parent is not None:
for k in self.parent.keys():
if k not in _keys_set:
_keys_set.add(k)
yield k
|
1,046 | https://:@github.com/moggers87/exhibition.git | 49a8eb6842d2eedecd239f35c651e4afde69cb87 | @@ -486,7 +486,7 @@ def serve(settings):
path = pathlib.Path(settings["deploy_path"], path)
- if not (path.exists() and path.suffix):
+ if not (path.exists() or path.suffix):
for ext in Node._strip_exts:
new_path = path.with_suffix(ext)
if new_path.exists():
| exhibition/main.py | ReplaceText(target='or' @(489,34)->(489,37)) | def serve(settings):
path = pathlib.Path(settings["deploy_path"], path)
if not (path.exists() and path.suffix):
for ext in Node._strip_exts:
new_path = path.with_suffix(ext)
if new_path.exists(): | def serve(settings):
path = pathlib.Path(settings["deploy_path"], path)
if not (path.exists() or path.suffix):
for ext in Node._strip_exts:
new_path = path.with_suffix(ext)
if new_path.exists(): |
1,047 | https://:@github.com/civrev/rlrisk.git | fb9ba4a28cd8dced235e9cb97b861130baa351a9 | @@ -575,7 +575,7 @@ class Risk:
t_count=3
#now add to amount recruited
- recruit+=t_count
+ recruit=t_count
#calculate for continents
for continent in self.continents:
| rlrisk/environment/risk.py | ReplaceText(target='=' @(578,15)->(578,17)) | class Risk:
t_count=3
#now add to amount recruited
recruit+=t_count
#calculate for continents
for continent in self.continents: | class Risk:
t_count=3
#now add to amount recruited
recruit=t_count
#calculate for continents
for continent in self.continents: |
1,048 | https://:@gitlab.com/philn/fb2feed.git | 9e6dc0b80947383a54e0fe99c656d419a4ede2c9 | @@ -126,7 +126,7 @@ async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug):
fe = fg.add_entry()
fe.author(name=page_id, email="%s.facebook.no-reply@fb2feed.org" % page_id)
- fe.id(post_url)
+ fe.id(post_id)
fe.link(href=post_url, rel="alternate")
fe.published(timestamp)
fe.updated(timestamp)
| fb2feed.py | ReplaceText(target='post_id' @(129,18)->(129,26)) | async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug):
fe = fg.add_entry()
fe.author(name=page_id, email="%s.facebook.no-reply@fb2feed.org" % page_id)
fe.id(post_url)
fe.link(href=post_url, rel="alternate")
fe.published(timestamp)
fe.updated(timestamp) | async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug):
fe = fg.add_entry()
fe.author(name=page_id, email="%s.facebook.no-reply@fb2feed.org" % page_id)
fe.id(post_id)
fe.link(href=post_url, rel="alternate")
fe.published(timestamp)
fe.updated(timestamp) |
1,049 | https://:@github.com/sputt/req-compile.git | f76edf2e9821dcef6d7bc851282731821e569d81 | @@ -111,7 +111,7 @@ class DistributionCollection(object):
self.nodes[key] = node
# If a new extra is being supplied, update the metadata
- if reason and node.metadata and reason.extras and set(reason.extras) & node.extras:
+ if reason and node.metadata and reason.extras and set(reason.extras) - node.extras:
metadata_to_apply = node.metadata
if source is not None and source.key in self.nodes:
| req_compile/dists.py | ReplaceText(target='-' @(114,77)->(114,78)) | class DistributionCollection(object):
self.nodes[key] = node
# If a new extra is being supplied, update the metadata
if reason and node.metadata and reason.extras and set(reason.extras) & node.extras:
metadata_to_apply = node.metadata
if source is not None and source.key in self.nodes: | class DistributionCollection(object):
self.nodes[key] = node
# If a new extra is being supplied, update the metadata
if reason and node.metadata and reason.extras and set(reason.extras) - node.extras:
metadata_to_apply = node.metadata
if source is not None and source.key in self.nodes: |
1,050 | https://:@github.com/inovonics/cloud-datastore.git | 72b1cb9760973b300b5ebf3bad1d6836b15d908a | @@ -113,7 +113,7 @@ class InoObjectBase:
def _validate_oid(self):
# Verify the oid is a UUID type variable
- if isinstance(getattr(self, 'oid'), uuid.UUID):
+ if not isinstance(getattr(self, 'oid'), uuid.UUID):
return "oid not of type uuid.UUID but type {}, value {}".format(type(getattr(self, 'oid')), getattr(self, 'oid'))
return None
| inovonics/cloud/datastore/bases.py | ReplaceText(target='not ' @(116,11)->(116,11)) | class InoObjectBase:
def _validate_oid(self):
# Verify the oid is a UUID type variable
if isinstance(getattr(self, 'oid'), uuid.UUID):
return "oid not of type uuid.UUID but type {}, value {}".format(type(getattr(self, 'oid')), getattr(self, 'oid'))
return None
| class InoObjectBase:
def _validate_oid(self):
# Verify the oid is a UUID type variable
if not isinstance(getattr(self, 'oid'), uuid.UUID):
return "oid not of type uuid.UUID but type {}, value {}".format(type(getattr(self, 'oid')), getattr(self, 'oid'))
return None
|
1,051 | https://:@github.com/shawnbrown/squint.git | 9912b140bc25d6d8679819ee8c4fd037a0b01b54 | @@ -116,7 +116,7 @@ class Result(Iterator):
value = __next__(self)
finally:
self._started_iteration = True
- bound_method = __next__.__get__(self.__class__, self)
+ bound_method = __next__.__get__(self, self.__class__)
self.__next__ = bound_method # <- Replace __next__ method!
return value
| squint/result.py | ArgSwap(idxs=0<->1 @(119,27)->(119,43)) | class Result(Iterator):
value = __next__(self)
finally:
self._started_iteration = True
bound_method = __next__.__get__(self.__class__, self)
self.__next__ = bound_method # <- Replace __next__ method!
return value
| class Result(Iterator):
value = __next__(self)
finally:
self._started_iteration = True
bound_method = __next__.__get__(self, self.__class__)
self.__next__ = bound_method # <- Replace __next__ method!
return value
|
1,052 | https://:@github.com/kav2k/singularity-pipeline.git | 4eacf7dfa1ddcdd7feec8ff928d8cac3ee170c72 | @@ -136,7 +136,7 @@ class Pipeline():
self.eprint.bold("# Running pipeline...\n")
if not self.dry_run:
- if os.path.isfile(self.imagefile):
+ if not os.path.isfile(self.imagefile):
raise RuntimeError("Image {} does not exist".format(self.imagefile))
for spec in self.binds:
| singularity_pipeline/pipeline.py | ReplaceText(target='not ' @(139,15)->(139,15)) | class Pipeline():
self.eprint.bold("# Running pipeline...\n")
if not self.dry_run:
if os.path.isfile(self.imagefile):
raise RuntimeError("Image {} does not exist".format(self.imagefile))
for spec in self.binds: | class Pipeline():
self.eprint.bold("# Running pipeline...\n")
if not self.dry_run:
if not os.path.isfile(self.imagefile):
raise RuntimeError("Image {} does not exist".format(self.imagefile))
for spec in self.binds: |
1,053 | https://:@github.com/mvinii94/aws-lambda-log-collector.git | 682850f282b70aa18663699c7e5e32bc4f6a8be1 | @@ -25,7 +25,7 @@ def cli(function_name, profile, region, output, start_time, end_time, pattern, l
epoch_start_time = parse_time(start_time)
epoch_end_time = parse_time(end_time)
- if epoch_start_time < epoch_end_time:
+ if epoch_start_time > epoch_end_time:
raise Exception(INVALID_DATES)
available_profiles = get_profiles()
| collector/cli.py | ReplaceText(target='>' @(28,25)->(28,26)) | def cli(function_name, profile, region, output, start_time, end_time, pattern, l
epoch_start_time = parse_time(start_time)
epoch_end_time = parse_time(end_time)
if epoch_start_time < epoch_end_time:
raise Exception(INVALID_DATES)
available_profiles = get_profiles() | def cli(function_name, profile, region, output, start_time, end_time, pattern, l
epoch_start_time = parse_time(start_time)
epoch_end_time = parse_time(end_time)
if epoch_start_time > epoch_end_time:
raise Exception(INVALID_DATES)
available_profiles = get_profiles() |
1,054 | https://:@github.com/peteshadbolt/abp.git | 9d859145d8a6ec45a7831235bfc05f45932709a7 | @@ -58,7 +58,7 @@ class CircuitModel(object):
def act_cz(self, control, target):
""" Act a CU somewhere """
control = 1 << control
- target = 1 << control
+ target = 1 << target
for i in xrange(self.d):
if (i & control) and (i & target):
self.state[i, 0] *= -1
| abp/qi.py | ReplaceText(target='target' @(61,22)->(61,29)) | class CircuitModel(object):
def act_cz(self, control, target):
""" Act a CU somewhere """
control = 1 << control
target = 1 << control
for i in xrange(self.d):
if (i & control) and (i & target):
self.state[i, 0] *= -1 | class CircuitModel(object):
def act_cz(self, control, target):
""" Act a CU somewhere """
control = 1 << control
target = 1 << target
for i in xrange(self.d):
if (i & control) and (i & target):
self.state[i, 0] *= -1 |
1,055 | https://:@github.com/peteshadbolt/abp.git | 1b787c47377d73a0519f60cc77657b2b09577b49 | @@ -134,7 +134,7 @@ class GraphState(object):
ci = self.get_connection_info(a, b)
if ci["non1"] and not clifford.is_diagonal(self.node[a]["vop"]):
debug("cphase: left one needs treatment again -> putting it to Id")
- self.remove_vop(b, a)
+ self.remove_vop(a, b)
self.cz_with_table(a, b)
| abp/graphstate.py | ArgSwap(idxs=0<->1 @(137,12)->(137,27)) | class GraphState(object):
ci = self.get_connection_info(a, b)
if ci["non1"] and not clifford.is_diagonal(self.node[a]["vop"]):
debug("cphase: left one needs treatment again -> putting it to Id")
self.remove_vop(b, a)
self.cz_with_table(a, b)
| class GraphState(object):
ci = self.get_connection_info(a, b)
if ci["non1"] and not clifford.is_diagonal(self.node[a]["vop"]):
debug("cphase: left one needs treatment again -> putting it to Id")
self.remove_vop(a, b)
self.cz_with_table(a, b)
|
1,056 | https://:@github.com/jsbroks/imantics.git | a9919325c1628d65cc0baf150599e3d04d6cf1be | @@ -43,7 +43,7 @@ class Annotation(Semantic):
:param polygons: bbox to create annotation from
:type polygons: :class:`BBox`, list, tuple
"""
- return cls(image=image, category=image, bbox=bbox)
+ return cls(image=image, category=category, bbox=bbox)
@classmethod
def from_polygons(cls, polygons, image=None, category=None):
| imantics/annotation.py | ReplaceText(target='category' @(46,41)->(46,46)) | class Annotation(Semantic):
:param polygons: bbox to create annotation from
:type polygons: :class:`BBox`, list, tuple
"""
return cls(image=image, category=image, bbox=bbox)
@classmethod
def from_polygons(cls, polygons, image=None, category=None): | class Annotation(Semantic):
:param polygons: bbox to create annotation from
:type polygons: :class:`BBox`, list, tuple
"""
return cls(image=image, category=category, bbox=bbox)
@classmethod
def from_polygons(cls, polygons, image=None, category=None): |
1,057 | https://:@github.com/278mt/cotohappy.git | 09e71e8a654b93db750a1e5f55b1c063b3070470 | @@ -26,7 +26,7 @@ class Reshape(object):
Reshape(mode='links', data=link)
for link in chunk_info['links']
]
- self.predicate = chunk_info['predicate'] if 'predicate' in data else []
+ self.predicate = chunk_info['predicate'] if 'predicate' in chunk_info else []
self.tokens = [
Reshape(mode='tokens', data=token)
| cotohappy/reshape.py | ReplaceText(target='chunk_info' @(29,72)->(29,76)) | class Reshape(object):
Reshape(mode='links', data=link)
for link in chunk_info['links']
]
self.predicate = chunk_info['predicate'] if 'predicate' in data else []
self.tokens = [
Reshape(mode='tokens', data=token) | class Reshape(object):
Reshape(mode='links', data=link)
for link in chunk_info['links']
]
self.predicate = chunk_info['predicate'] if 'predicate' in chunk_info else []
self.tokens = [
Reshape(mode='tokens', data=token) |
1,058 | https://:@github.com/AntoineToubhans/MongoTs.git | 79fa91c7f9f3ecd0e0d22ca01a67a9efc84a9611 | @@ -82,4 +82,4 @@ class MongoTSCollection():
raw_data = list(self._collection.aggregate(pipeline))
- return build_dataframe(raw_data, aggregateby, groupby)
+ return build_dataframe(raw_data, parsed_aggregateby, groupby)
| mongots/collection.py | ReplaceText(target='parsed_aggregateby' @(85,41)->(85,52)) | class MongoTSCollection():
raw_data = list(self._collection.aggregate(pipeline))
return build_dataframe(raw_data, aggregateby, groupby) | class MongoTSCollection():
raw_data = list(self._collection.aggregate(pipeline))
return build_dataframe(raw_data, parsed_aggregateby, groupby) |
1,059 | https://:@github.com/thenewguy/django-randomfields.git | 983d6a2940e17a42326137b6592e0ed3ea3de8bd | @@ -49,7 +49,7 @@ class RandomStringFieldBase(RandomFieldBase):
'min_length': self.min_length,
}
defaults.update(kwargs)
- return super(RandomStringFieldBase, self).formfield(**kwargs)
+ return super(RandomStringFieldBase, self).formfield(**defaults)
class RandomCharField(RandomStringFieldBase, models.CharField):
def check(self, **kwargs):
| randomfields/models/fields/string.py | ReplaceText(target='defaults' @(52,62)->(52,68)) | class RandomStringFieldBase(RandomFieldBase):
'min_length': self.min_length,
}
defaults.update(kwargs)
return super(RandomStringFieldBase, self).formfield(**kwargs)
class RandomCharField(RandomStringFieldBase, models.CharField):
def check(self, **kwargs): | class RandomStringFieldBase(RandomFieldBase):
'min_length': self.min_length,
}
defaults.update(kwargs)
return super(RandomStringFieldBase, self).formfield(**defaults)
class RandomCharField(RandomStringFieldBase, models.CharField):
def check(self, **kwargs): |
1,060 | https://:@github.com/mathcamp/devbox.git | b014314770fe44557b57c7d9d024959be9fb4f4a | @@ -175,7 +175,7 @@ def git_describe(describe_args):
if proc.returncode != 0:
print("Error parsing git revision! Make sure that you have tagged a "
"commit, and that the tag matches the 'tag_match' argument")
- print("Git output: " + output)
+ print("Git output: " + description)
return {
'tag': 'unknown',
'description': 'unknown',
| version_helper.py | ReplaceText(target='description' @(178,31)->(178,37)) | def git_describe(describe_args):
if proc.returncode != 0:
print("Error parsing git revision! Make sure that you have tagged a "
"commit, and that the tag matches the 'tag_match' argument")
print("Git output: " + output)
return {
'tag': 'unknown',
'description': 'unknown', | def git_describe(describe_args):
if proc.returncode != 0:
print("Error parsing git revision! Make sure that you have tagged a "
"commit, and that the tag matches the 'tag_match' argument")
print("Git output: " + description)
return {
'tag': 'unknown',
'description': 'unknown', |
1,061 | https://:@github.com/mathcamp/devbox.git | 54a298fc2018e1b4328a68c08740f5bd49f0864a | @@ -213,7 +213,7 @@ def unbox(repo, dest=None, no_deps=False, *parents):
LOG.info("Installing into %s", install_dir)
dest_conf = load_conf(install_dir)
venv = dest_conf.get('env')
- with pushd(dest):
+ with pushd(install_dir):
if venv is not None:
venv['path'] = os.path.abspath(venv['path'])
run_commands(conf.get('post_setup', []), venv)
| devbox/unbox.py | ReplaceText(target='install_dir' @(216,19)->(216,23)) | def unbox(repo, dest=None, no_deps=False, *parents):
LOG.info("Installing into %s", install_dir)
dest_conf = load_conf(install_dir)
venv = dest_conf.get('env')
with pushd(dest):
if venv is not None:
venv['path'] = os.path.abspath(venv['path'])
run_commands(conf.get('post_setup', []), venv) | def unbox(repo, dest=None, no_deps=False, *parents):
LOG.info("Installing into %s", install_dir)
dest_conf = load_conf(install_dir)
venv = dest_conf.get('env')
with pushd(install_dir):
if venv is not None:
venv['path'] = os.path.abspath(venv['path'])
run_commands(conf.get('post_setup', []), venv) |
1,062 | https://:@github.com/ccxtechnologies/adbus.git | 58d6866e77afaac02195d40348e207d9258b4fc2 | @@ -177,7 +177,7 @@ class Method:
self.name = x.attrib['name']
if x.tag == 'arg':
if x.attrib['direction'] == 'out':
- self.return_signature = x.attrib['type']
+ self.return_signature += x.attrib['type']
elif x.attrib['direction'] == 'in':
self.arg_signatures.append(x.attrib['type'])
| adbus/client/proxy.py | ReplaceText(target='+=' @(180,42)->(180,43)) | class Method:
self.name = x.attrib['name']
if x.tag == 'arg':
if x.attrib['direction'] == 'out':
self.return_signature = x.attrib['type']
elif x.attrib['direction'] == 'in':
self.arg_signatures.append(x.attrib['type'])
| class Method:
self.name = x.attrib['name']
if x.tag == 'arg':
if x.attrib['direction'] == 'out':
self.return_signature += x.attrib['type']
elif x.attrib['direction'] == 'in':
self.arg_signatures.append(x.attrib['type'])
|
1,063 | https://:@github.com/balazstothofficial/models.git | d0b6a34bb0dbd981e3785661f04f04cde9c4222b | @@ -107,7 +107,7 @@ def run_mnist_eager(flags_obj):
# Automatically determine device and data_format
(device, data_format) = ('/gpu:0', 'channels_first')
- if flags_obj.no_gpu or tf.test.is_gpu_available():
+ if flags_obj.no_gpu or not tf.test.is_gpu_available():
(device, data_format) = ('/cpu:0', 'channels_last')
# If data_format is defined in FLAGS, overwrite automatically set value.
if flags_obj.data_format is not None:
| official/mnist/mnist_eager.py | ReplaceText(target='not ' @(110,25)->(110,25)) | def run_mnist_eager(flags_obj):
# Automatically determine device and data_format
(device, data_format) = ('/gpu:0', 'channels_first')
if flags_obj.no_gpu or tf.test.is_gpu_available():
(device, data_format) = ('/cpu:0', 'channels_last')
# If data_format is defined in FLAGS, overwrite automatically set value.
if flags_obj.data_format is not None: | def run_mnist_eager(flags_obj):
# Automatically determine device and data_format
(device, data_format) = ('/gpu:0', 'channels_first')
if flags_obj.no_gpu or not tf.test.is_gpu_available():
(device, data_format) = ('/cpu:0', 'channels_last')
# If data_format is defined in FLAGS, overwrite automatically set value.
if flags_obj.data_format is not None: |
1,064 | https://:@github.com/balazstothofficial/models.git | e9dbef6be831bac9c5cbacf6b3b13e4557e4777c | @@ -353,7 +353,7 @@ class Worker(threading.Thread):
policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions,
logits=logits)
policy_loss *= tf.stop_gradient(advantage)
- policy_loss = 0.01 * entropy
+ policy_loss -= 0.01 * entropy
total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss))
return total_loss
| research/a3c_blogpost/a3c_cartpole.py | ReplaceText(target='-=' @(356,16)->(356,17)) | class Worker(threading.Thread):
policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions,
logits=logits)
policy_loss *= tf.stop_gradient(advantage)
policy_loss = 0.01 * entropy
total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss))
return total_loss
| class Worker(threading.Thread):
policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions,
logits=logits)
policy_loss *= tf.stop_gradient(advantage)
policy_loss -= 0.01 * entropy
total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss))
return total_loss
|
1,065 | https://:@github.com/idigbio/idq.git | c3c53aa2eab9d4a958f5ac338c4daac8fae2d192 | @@ -31,7 +31,7 @@ def create_harness(w):
for f in w.required_fields:
f_name = f.replace(":","_")
- setattr(SingleForm,f_name,StringField(f_name))
+ setattr(SingleForm,f_name,StringField(f))
setattr(SingleForm,"submit",SubmitField(u'Process'))
| idq/harness/__init__.py | ReplaceText(target='f' @(34,46)->(34,52)) | def create_harness(w):
for f in w.required_fields:
f_name = f.replace(":","_")
setattr(SingleForm,f_name,StringField(f_name))
setattr(SingleForm,"submit",SubmitField(u'Process'))
| def create_harness(w):
for f in w.required_fields:
f_name = f.replace(":","_")
setattr(SingleForm,f_name,StringField(f))
setattr(SingleForm,"submit",SubmitField(u'Process'))
|
1,066 | https://:@github.com/iMerica/dj-models.git | 659ab9846e81d95bb75dbb3c00147324bf0d6541 | @@ -22,7 +22,7 @@ def login(request):
else:
errors = {}
response = HttpResponse()
- response.session.set_test_cookie()
+ request.session.set_test_cookie()
t = template_loader.get_template('registration/login')
c = Context(request, {
'form': formfields.FormWrapper(manipulator, request.POST, errors),
| django/views/auth/login.py | ReplaceText(target='request' @(25,4)->(25,12)) | def login(request):
else:
errors = {}
response = HttpResponse()
response.session.set_test_cookie()
t = template_loader.get_template('registration/login')
c = Context(request, {
'form': formfields.FormWrapper(manipulator, request.POST, errors), | def login(request):
else:
errors = {}
response = HttpResponse()
request.session.set_test_cookie()
t = template_loader.get_template('registration/login')
c = Context(request, {
'form': formfields.FormWrapper(manipulator, request.POST, errors), |
1,067 | https://:@github.com/iMerica/dj-models.git | a97648a7e03fb95b09e888e5d59d82d57fb289b7 | @@ -105,7 +105,7 @@ class DecoratorsTest(TestCase):
"""
def my_view(request):
return "response"
- my_view_cached = cache_page(123, my_view)
+ my_view_cached = cache_page(my_view, 123)
self.assertEqual(my_view_cached(HttpRequest()), "response")
class MethodDecoratorAdapterTests(TestCase):
| tests/regressiontests/decorators/tests.py | ArgSwap(idxs=0<->1 @(108,25)->(108,35)) | class DecoratorsTest(TestCase):
"""
def my_view(request):
return "response"
my_view_cached = cache_page(123, my_view)
self.assertEqual(my_view_cached(HttpRequest()), "response")
class MethodDecoratorAdapterTests(TestCase): | class DecoratorsTest(TestCase):
"""
def my_view(request):
return "response"
my_view_cached = cache_page(my_view, 123)
self.assertEqual(my_view_cached(HttpRequest()), "response")
class MethodDecoratorAdapterTests(TestCase): |
1,068 | https://:@github.com/iMerica/dj-models.git | 7db68a888b633f2b65f753d50f21463b65a01edf | @@ -399,7 +399,7 @@ def language(parser, token):
"""
bits = token.split_contents()
- if len(bits) < 2:
+ if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
nodelist = parser.parse(('endlanguage',))
| django/templatetags/i18n.py | ReplaceText(target='!=' @(402,17)->(402,18)) | def language(parser, token):
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
nodelist = parser.parse(('endlanguage',)) | def language(parser, token):
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
nodelist = parser.parse(('endlanguage',)) |
1,069 | https://:@github.com/iMerica/dj-models.git | b2050ff546da4164f90a795e55d7d8c55981783d | @@ -169,7 +169,7 @@ class SQLCompiler(object):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
- if table in only_load and col not in only_load[table]:
+ if table in only_load and column not in only_load[table]:
continue
r = '%s.%s' % (qn(alias), qn(column))
if with_aliases:
| django/db/models/sql/compiler.py | ReplaceText(target='column' @(172,46)->(172,49)) | class SQLCompiler(object):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
if table in only_load and col not in only_load[table]:
continue
r = '%s.%s' % (qn(alias), qn(column))
if with_aliases: | class SQLCompiler(object):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
if table in only_load and column not in only_load[table]:
continue
r = '%s.%s' % (qn(alias), qn(column))
if with_aliases: |
1,070 | https://:@github.com/iMerica/dj-models.git | cfba2460370a6d1808b78e2ba0709ea5c8b7e773 | @@ -42,7 +42,7 @@ def check_settings(base_url=None):
Checks if the staticfiles settings have sane values.
"""
- if base_url is not None:
+ if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
| django/contrib/staticfiles/utils.py | ReplaceText(target=' is ' @(45,15)->(45,23)) | def check_settings(base_url=None):
Checks if the staticfiles settings have sane values.
"""
if base_url is not None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured( | def check_settings(base_url=None):
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured( |
1,071 | https://:@github.com/iMerica/dj-models.git | 5f2be4ecbb5df3760f4c6e49170478719d3026d7 | @@ -824,7 +824,7 @@ class SQLInsertCompiler(SQLCompiler):
for val in values
]
if self.return_id and self.connection.features.can_return_id_from_insert:
- params = values[0]
+ params = params[0]
col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
result.append("VALUES (%s)" % ", ".join(placeholders[0]))
r_fmt, r_params = self.connection.ops.return_insert_id()
| django/db/models/sql/compiler.py | ReplaceText(target='params' @(827,21)->(827,27)) | class SQLInsertCompiler(SQLCompiler):
for val in values
]
if self.return_id and self.connection.features.can_return_id_from_insert:
params = values[0]
col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
result.append("VALUES (%s)" % ", ".join(placeholders[0]))
r_fmt, r_params = self.connection.ops.return_insert_id() | class SQLInsertCompiler(SQLCompiler):
for val in values
]
if self.return_id and self.connection.features.can_return_id_from_insert:
params = params[0]
col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
result.append("VALUES (%s)" % ", ".join(placeholders[0]))
r_fmt, r_params = self.connection.ops.return_insert_id() |
1,072 | https://:@github.com/iMerica/dj-models.git | d72d5ce8274992ce01e39f866a7a250bc459eefe | @@ -37,7 +37,7 @@ class GeoSQLCompiler(compiler.SQLCompiler):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
- if table in only_load and col not in only_load[table]:
+ if table in only_load and column not in only_load[table]:
continue
r = self.get_field_select(field, alias, column)
if with_aliases:
| django/contrib/gis/db/models/sql/compiler.py | ReplaceText(target='column' @(40,46)->(40,49)) | class GeoSQLCompiler(compiler.SQLCompiler):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
if table in only_load and col not in only_load[table]:
continue
r = self.get_field_select(field, alias, column)
if with_aliases: | class GeoSQLCompiler(compiler.SQLCompiler):
if isinstance(col, (list, tuple)):
alias, column = col
table = self.query.alias_map[alias][TABLE_NAME]
if table in only_load and column not in only_load[table]:
continue
r = self.get_field_select(field, alias, column)
if with_aliases: |
1,073 | https://:@github.com/iMerica/dj-models.git | 6ecbac21a9017a53fe18ac81c9c1d2f28185a292 | @@ -111,5 +111,5 @@ class OSMWidget(BaseGeometryWidget):
return 900913
def render(self, name, value, attrs=None):
- return super(self, OSMWidget).render(name, value,
+ return super(OSMWidget, self).render(name, value,
{'default_lon': self.default_lon, 'default_lat': self.default_lat})
| django/contrib/gis/forms/widgets.py | ArgSwap(idxs=0<->1 @(114,15)->(114,20)) | class OSMWidget(BaseGeometryWidget):
return 900913
def render(self, name, value, attrs=None):
return super(self, OSMWidget).render(name, value,
{'default_lon': self.default_lon, 'default_lat': self.default_lat}) | class OSMWidget(BaseGeometryWidget):
return 900913
def render(self, name, value, attrs=None):
return super(OSMWidget, self).render(name, value,
{'default_lon': self.default_lon, 'default_lat': self.default_lat}) |
1,074 | https://:@github.com/iMerica/dj-models.git | 86c248aa646183ef4a1cb407bb3e4cb597272f63 | @@ -575,7 +575,7 @@ class SQLCompiler(object):
for order, order_params in ordering_group_by:
# Even if we have seen the same SQL string, it might have
# different params, so, we add same SQL in "has params" case.
- if order not in seen or params:
+ if order not in seen or order_params:
result.append(order)
params.extend(order_params)
seen.add(order)
| django/db/models/sql/compiler.py | ReplaceText(target='order_params' @(578,44)->(578,50)) | class SQLCompiler(object):
for order, order_params in ordering_group_by:
# Even if we have seen the same SQL string, it might have
# different params, so, we add same SQL in "has params" case.
if order not in seen or params:
result.append(order)
params.extend(order_params)
seen.add(order) | class SQLCompiler(object):
for order, order_params in ordering_group_by:
# Even if we have seen the same SQL string, it might have
# different params, so, we add same SQL in "has params" case.
if order not in seen or order_params:
result.append(order)
params.extend(order_params)
seen.add(order) |
1,075 | https://:@github.com/iMerica/dj-models.git | fddb0131d37109c809ec391e1a134ef1d9e442a7 | @@ -57,7 +57,7 @@ def check_password(password, encoded, setter=None, preferred='default'):
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
- must_update = hasher.must_update(encoded)
+ must_update = preferred.must_update(encoded)
is_correct = hasher.verify(password, encoded)
if setter and is_correct and must_update:
setter(password)
| django/contrib/auth/hashers.py | ReplaceText(target='preferred' @(60,22)->(60,28)) | def check_password(password, encoded, setter=None, preferred='default'):
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = hasher.must_update(encoded)
is_correct = hasher.verify(password, encoded)
if setter and is_correct and must_update:
setter(password) | def check_password(password, encoded, setter=None, preferred='default'):
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(password, encoded)
if setter and is_correct and must_update:
setter(password) |
1,076 | https://:@github.com/iMerica/dj-models.git | e8223b889aab3b5ac0c2312eb9ee2307ea635c97 | @@ -228,7 +228,7 @@ class GenericRelationTests(TestCase):
# then wrong results are produced here as the link to b will also match
# (b and hs1 have equal pks).
self.assertEqual(qs.count(), 1)
- self.assertEqual(qs[0].links__sum, l.id)
+ self.assertEqual(qs[0].links__sum, hs1.id)
l.delete()
# Now if we don't have proper left join, we will not produce any
# results at all here.
| tests/generic_relations_regress/tests.py | ReplaceText(target='hs1' @(231,43)->(231,44)) | class GenericRelationTests(TestCase):
# then wrong results are produced here as the link to b will also match
# (b and hs1 have equal pks).
self.assertEqual(qs.count(), 1)
self.assertEqual(qs[0].links__sum, l.id)
l.delete()
# Now if we don't have proper left join, we will not produce any
# results at all here. | class GenericRelationTests(TestCase):
# then wrong results are produced here as the link to b will also match
# (b and hs1 have equal pks).
self.assertEqual(qs.count(), 1)
self.assertEqual(qs[0].links__sum, hs1.id)
l.delete()
# Now if we don't have proper left join, we will not produce any
# results at all here. |
1,077 | https://:@github.com/iMerica/dj-models.git | 3074c5b19e2da5f7a5359c3cf3c5308eb194cdf9 | @@ -112,7 +112,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
@classmethod
def setUpClass(cls):
- super(cls, ClassDecoratedTestCase).setUpClass()
+ super(ClassDecoratedTestCase, cls).setUpClass()
cls.foo = getattr(settings, 'TEST', 'BUG')
def test_override(self):
| tests/settings_tests/tests.py | ArgSwap(idxs=0<->1 @(115,8)->(115,13)) | class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
@classmethod
def setUpClass(cls):
super(cls, ClassDecoratedTestCase).setUpClass()
cls.foo = getattr(settings, 'TEST', 'BUG')
def test_override(self): | class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
@classmethod
def setUpClass(cls):
super(ClassDecoratedTestCase, cls).setUpClass()
cls.foo = getattr(settings, 'TEST', 'BUG')
def test_override(self): |
1,078 | https://:@github.com/iMerica/dj-models.git | c2b4967e76fd671e6199e4dd54d2a2c1f096b8eb | @@ -23,7 +23,7 @@ def import_string(dotted_path):
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
- dotted_path, class_name)
+ module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
| django/utils/module_loading.py | ReplaceText(target='module_path' @(26,12)->(26,23)) | def import_string(dotted_path):
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
dotted_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
| def import_string(dotted_path):
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
|
1,079 | https://:@github.com/iMerica/dj-models.git | a3fffdca2472885a99e1ea9159a685753cd45738 | @@ -99,7 +99,7 @@ class SessionStore(SessionBase):
# Remove expired sessions.
expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
- if expiry_age < 0:
+ if expiry_age <= 0:
session_data = {}
self.delete()
self.create()
| django/contrib/sessions/backends/file.py | ReplaceText(target='<=' @(102,30)->(102,31)) | class SessionStore(SessionBase):
# Remove expired sessions.
expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
if expiry_age < 0:
session_data = {}
self.delete()
self.create() | class SessionStore(SessionBase):
# Remove expired sessions.
expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
if expiry_age <= 0:
session_data = {}
self.delete()
self.create() |
1,080 | https://:@github.com/iMerica/dj-models.git | abcdb237bb313d116ce2ac8e90f79f61429afc70 | @@ -31,7 +31,7 @@ class DatabaseCreation(BaseDatabaseCreation):
try:
if verbosity >= 1:
print("Destroying old test database for alias %s..." % (
- self._get_database_display_str(target_database_name, verbosity),
+ self._get_database_display_str(verbosity, target_database_name),
))
cursor.execute("DROP DATABASE %s" % qn(target_database_name))
cursor.execute("CREATE DATABASE %s" % qn(target_database_name))
| django/db/backends/mysql/creation.py | ArgSwap(idxs=0<->1 @(34,28)->(34,58)) | class DatabaseCreation(BaseDatabaseCreation):
try:
if verbosity >= 1:
print("Destroying old test database for alias %s..." % (
self._get_database_display_str(target_database_name, verbosity),
))
cursor.execute("DROP DATABASE %s" % qn(target_database_name))
cursor.execute("CREATE DATABASE %s" % qn(target_database_name)) | class DatabaseCreation(BaseDatabaseCreation):
try:
if verbosity >= 1:
print("Destroying old test database for alias %s..." % (
self._get_database_display_str(verbosity, target_database_name),
))
cursor.execute("DROP DATABASE %s" % qn(target_database_name))
cursor.execute("CREATE DATABASE %s" % qn(target_database_name)) |
1,081 | https://:@github.com/iMerica/dj-models.git | 542b7f6c50df18f2aa201cf1de81577c1bee643c | @@ -50,7 +50,7 @@ class SeparateDatabaseAndState(Operation):
to_state = base_state.clone()
for dbop in self.database_operations[:-(pos + 1)]:
dbop.state_forwards(app_label, to_state)
- from_state = base_state.clone()
+ from_state = to_state.clone()
database_operation.state_forwards(app_label, from_state)
database_operation.database_backwards(app_label, schema_editor, from_state, to_state)
| django/db/migrations/operations/special.py | ReplaceText(target='to_state' @(53,25)->(53,35)) | class SeparateDatabaseAndState(Operation):
to_state = base_state.clone()
for dbop in self.database_operations[:-(pos + 1)]:
dbop.state_forwards(app_label, to_state)
from_state = base_state.clone()
database_operation.state_forwards(app_label, from_state)
database_operation.database_backwards(app_label, schema_editor, from_state, to_state)
| class SeparateDatabaseAndState(Operation):
to_state = base_state.clone()
for dbop in self.database_operations[:-(pos + 1)]:
dbop.state_forwards(app_label, to_state)
from_state = to_state.clone()
database_operation.state_forwards(app_label, from_state)
database_operation.database_backwards(app_label, schema_editor, from_state, to_state)
|
1,082 | https://:@github.com/iMerica/dj-models.git | 0d9ff873d9f93efbba875efbf582db88bb0e30ce | @@ -147,7 +147,7 @@ class UserAttributeSimilarityValidator(object):
continue
value_parts = re.split(r'\W+', value) + [value]
for value_part in value_parts:
- if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
+ if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity:
try:
verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
except FieldDoesNotExist:
| django/contrib/auth/password_validation.py | ReplaceText(target='>=' @(150,91)->(150,92)) | class UserAttributeSimilarityValidator(object):
continue
value_parts = re.split(r'\W+', value) + [value]
for value_part in value_parts:
if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
try:
verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
except FieldDoesNotExist: | class UserAttributeSimilarityValidator(object):
continue
value_parts = re.split(r'\W+', value) + [value]
for value_part in value_parts:
if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity:
try:
verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
except FieldDoesNotExist: |
1,083 | https://:@github.com/iMerica/dj-models.git | d5088f838d837fc9e3109c828f18511055f20bea | @@ -383,7 +383,7 @@ class CombinedExpression(Expression):
return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
if (lhs_output and rhs_output and self.connector == self.SUB and
lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
- lhs_output.get_internal_type() == lhs_output.get_internal_type()):
+ lhs_output.get_internal_type() == rhs_output.get_internal_type()):
return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
expressions = []
expression_params = []
| django/db/models/expressions.py | ReplaceText(target='rhs_output' @(386,50)->(386,60)) | class CombinedExpression(Expression):
return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
if (lhs_output and rhs_output and self.connector == self.SUB and
lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
lhs_output.get_internal_type() == lhs_output.get_internal_type()):
return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
expressions = []
expression_params = [] | class CombinedExpression(Expression):
return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
if (lhs_output and rhs_output and self.connector == self.SUB and
lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
lhs_output.get_internal_type() == rhs_output.get_internal_type()):
return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
expressions = []
expression_params = [] |
1,084 | https://:@github.com/iMerica/dj-models.git | 95993a89ce6ca5f5e26b1c22b65c57dcb8c005e9 | @@ -42,7 +42,7 @@ class PasswordResetTokenGenerator:
return False
# Check the timestamp is within limit
- if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
+ if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
| django/contrib/auth/tokens.py | ReplaceText(target='>=' @(45,48)->(45,49)) | class PasswordResetTokenGenerator:
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True | class PasswordResetTokenGenerator:
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True |
1,085 | https://:@github.com/Cologler/lquery-python.git | 2b2d5a249fd80693660433076d8c79ef119c89bb | @@ -55,7 +55,7 @@ class DefaultExprVisitor(ExprVisitor):
right = expr.right.accept(self)
if left is expr.left and right is expr.right:
return expr
- return Make.binary_op(left, right, expr.op)
+ return Make.binary_op(left, expr.op, right)
def visit_func_expr(self, expr):
body = expr.body.accept(self)
| lquery/expr/visitor.py | ArgSwap(idxs=1<->2 @(58,15)->(58,29)) | class DefaultExprVisitor(ExprVisitor):
right = expr.right.accept(self)
if left is expr.left and right is expr.right:
return expr
return Make.binary_op(left, right, expr.op)
def visit_func_expr(self, expr):
body = expr.body.accept(self) | class DefaultExprVisitor(ExprVisitor):
right = expr.right.accept(self)
if left is expr.left and right is expr.right:
return expr
return Make.binary_op(left, expr.op, right)
def visit_func_expr(self, expr):
body = expr.body.accept(self) |
1,086 | https://:@github.com/rkhleics/police-api-client-python.git | 2bedbab8eb7d2efb9ff8e39a821fd2796dd4ce3f | @@ -28,7 +28,7 @@ class BaseService(object):
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {}
- if method == 'GET':
+ if verb == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs
| police_api/service.py | ReplaceText(target='verb' @(31,11)->(31,17)) | class BaseService(object):
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {}
if method == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs | class BaseService(object):
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {}
if verb == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs |
1,087 | https://:@github.com/dw/acid.git | 7cdd45e62d60ea7e67a2a3d656f8cce8dd9f5571 | @@ -94,7 +94,7 @@ class RangeIterator(object):
the iterator is still within the bounds of the collection prefix,
otherwise False."""
keys_raw, self.data = next(self.it, ('', ''))
- keys = keylib.KeyList.from_raw(self.prefix, keys_raw)
+ keys = keylib.KeyList.from_raw(keys_raw, self.prefix)
self.keys = keys
return keys is not None
| acid/iterators.py | ArgSwap(idxs=0<->1 @(97,15)->(97,38)) | class RangeIterator(object):
the iterator is still within the bounds of the collection prefix,
otherwise False."""
keys_raw, self.data = next(self.it, ('', ''))
keys = keylib.KeyList.from_raw(self.prefix, keys_raw)
self.keys = keys
return keys is not None
| class RangeIterator(object):
the iterator is still within the bounds of the collection prefix,
otherwise False."""
keys_raw, self.data = next(self.it, ('', ''))
keys = keylib.KeyList.from_raw(keys_raw, self.prefix)
self.keys = keys
return keys is not None
|
1,088 | https://:@github.com/dw/acid.git | 7cdd45e62d60ea7e67a2a3d656f8cce8dd9f5571 | @@ -35,7 +35,7 @@ class IterTest:
REVERSE = ITEMS[::-1]
def _encode(self, s):
- return keylib.packs(self.prefix, s)
+ return keylib.packs(s, self.prefix)
def setUp(self):
self.e = acid.engines.ListEngine()
| tests/core_test.py | ArgSwap(idxs=0<->1 @(38,15)->(38,27)) | class IterTest:
REVERSE = ITEMS[::-1]
def _encode(self, s):
return keylib.packs(self.prefix, s)
def setUp(self):
self.e = acid.engines.ListEngine() | class IterTest:
REVERSE = ITEMS[::-1]
def _encode(self, s):
return keylib.packs(s, self.prefix)
def setUp(self):
self.e = acid.engines.ListEngine() |
1,089 | https://:@github.com/akuendig/RxPython.git | f1a5d48b5c22cf5d39e592299a3760be72ba79f1 | @@ -50,7 +50,7 @@ class GroupBy(Producer):
else:
if not key in self.map:
writer = Subject()
- self.map[key] = value
+ self.map[key] = writer
fireNewMapEntry = True
except Exception as e:
self.onError(e)
| linq/groupBy.py | ReplaceText(target='writer' @(53,28)->(53,33)) | class GroupBy(Producer):
else:
if not key in self.map:
writer = Subject()
self.map[key] = value
fireNewMapEntry = True
except Exception as e:
self.onError(e) | class GroupBy(Producer):
else:
if not key in self.map:
writer = Subject()
self.map[key] = writer
fireNewMapEntry = True
except Exception as e:
self.onError(e) |
1,090 | https://:@github.com/ANCIR/grano.git | 0c1c013af342409e68adf8e50a80bd72f66cd9a4 | @@ -20,7 +20,7 @@ def save(data, project=None):
""" Create or update a project with a given slug. """
validator = ProjectValidator()
- data = validator.deserialize(validator)
+ data = validator.deserialize(data)
if project is None:
project = Project()
| grano/logic/projects.py | ReplaceText(target='data' @(23,33)->(23,42)) | def save(data, project=None):
""" Create or update a project with a given slug. """
validator = ProjectValidator()
data = validator.deserialize(validator)
if project is None:
project = Project() | def save(data, project=None):
""" Create or update a project with a given slug. """
validator = ProjectValidator()
data = validator.deserialize(data)
if project is None:
project = Project() |
1,091 | https://:@github.com/ANCIR/grano.git | 051a6d6191ba975e6f741c19b354a9017c825de0 | @@ -50,7 +50,7 @@ def update(slug, name):
authz.require(authz.project_manage(project))
schema = object_or_404(Schema.by_name(project, name))
data = request_data({'project': project})
- project = schemata.save(data, schema=schema)
+ schema = schemata.save(data, schema=schema)
db.session.commit()
return jsonify(schemata.to_rest(schema))
| grano/views/schemata_api.py | ReplaceText(target='schema' @(53,4)->(53,11)) | def update(slug, name):
authz.require(authz.project_manage(project))
schema = object_or_404(Schema.by_name(project, name))
data = request_data({'project': project})
project = schemata.save(data, schema=schema)
db.session.commit()
return jsonify(schemata.to_rest(schema))
| def update(slug, name):
authz.require(authz.project_manage(project))
schema = object_or_404(Schema.by_name(project, name))
data = request_data({'project': project})
schema = schemata.save(data, schema=schema)
db.session.commit()
return jsonify(schemata.to_rest(schema))
|
1,092 | https://:@github.com/eljost/pysisyphus.git | b5fd2ffdadc4b9d84a4b553b2e24a739509659be | @@ -100,7 +100,7 @@ class NEB(ChainOfStates):
if self._forces is None:
# Parallel calculation
- if self.parallel != 0:
+ if self.parallel > 0:
with Pool(processes=self.parallel) as pool:
image_number = len(self.images)
par_images = pool.map(self.par_calc, range(image_number))
| pysisyphus/cos/NEB.py | ReplaceText(target='>' @(103,29)->(103,31)) | class NEB(ChainOfStates):
if self._forces is None:
# Parallel calculation
if self.parallel != 0:
with Pool(processes=self.parallel) as pool:
image_number = len(self.images)
par_images = pool.map(self.par_calc, range(image_number)) | class NEB(ChainOfStates):
if self._forces is None:
# Parallel calculation
if self.parallel > 0:
with Pool(processes=self.parallel) as pool:
image_number = len(self.images)
par_images = pool.map(self.par_calc, range(image_number)) |
1,093 | https://:@github.com/eljost/pysisyphus.git | f2aa6358798813b4e77862d57a38ec3286f3a142 | @@ -425,7 +425,7 @@ class ORCA(Calculator):
self.store_wfo_data(atoms, coords)
# In the first iteration we have nothing to compare to
old_root = self.root
- if self.calc_counter >= 1:
+ if self.calc_counter > 1:
last_two_coords = self.wfow.last_two_coords
self.root = self.wfow.track(old_root=self.root)
if self.root != old_root:
| pysisyphus/calculators/ORCA.py | ReplaceText(target='>' @(428,29)->(428,31)) | class ORCA(Calculator):
self.store_wfo_data(atoms, coords)
# In the first iteration we have nothing to compare to
old_root = self.root
if self.calc_counter >= 1:
last_two_coords = self.wfow.last_two_coords
self.root = self.wfow.track(old_root=self.root)
if self.root != old_root: | class ORCA(Calculator):
self.store_wfo_data(atoms, coords)
# In the first iteration we have nothing to compare to
old_root = self.root
if self.calc_counter > 1:
last_two_coords = self.wfow.last_two_coords
self.root = self.wfow.track(old_root=self.root)
if self.root != old_root: |
1,094 | https://:@github.com/eljost/pysisyphus.git | f00266de85fe1696b618f979711c52bafb2312be | @@ -58,7 +58,7 @@ def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False):
# How is this different from above?
elif isinstance(xyz_fns, str) and xyz_fns.endswith(".trj"):
geoms = geoms_from_trj(xyz_fns)
- elif multiple_geoms:
+ elif not multiple_geoms:
geoms = geoms_from_trj(xyz_fns[0])
# Handle multiple .xyz files
else:
| pysisyphus/trj.py | ReplaceText(target='not ' @(61,9)->(61,9)) | def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False):
# How is this different from above?
elif isinstance(xyz_fns, str) and xyz_fns.endswith(".trj"):
geoms = geoms_from_trj(xyz_fns)
elif multiple_geoms:
geoms = geoms_from_trj(xyz_fns[0])
# Handle multiple .xyz files
else: | def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False):
# How is this different from above?
elif isinstance(xyz_fns, str) and xyz_fns.endswith(".trj"):
geoms = geoms_from_trj(xyz_fns)
elif not multiple_geoms:
geoms = geoms_from_trj(xyz_fns[0])
# Handle multiple .xyz files
else: |
1,095 | https://:@github.com/eljost/pysisyphus.git | 98f7e8f2e9a295c727cf57b2dd6bca90fd829b16 | @@ -837,7 +837,7 @@ def plot_opt(h5_fn="optimization.h5", group_name="opt"):
ax1.set_title("max(forces)")
ax1.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹")
- ax2.plot(max_forces, **ax_kwargs)
+ ax2.plot(rms_forces, **ax_kwargs)
ax2.set_title("rms(forces)")
ax2.set_xlabel("Step")
ax2.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹")
| pysisyphus/plot.py | ReplaceText(target='rms_forces' @(840,13)->(840,23)) | def plot_opt(h5_fn="optimization.h5", group_name="opt"):
ax1.set_title("max(forces)")
ax1.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹")
ax2.plot(max_forces, **ax_kwargs)
ax2.set_title("rms(forces)")
ax2.set_xlabel("Step")
ax2.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹") | def plot_opt(h5_fn="optimization.h5", group_name="opt"):
ax1.set_title("max(forces)")
ax1.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹")
ax2.plot(rms_forces, **ax_kwargs)
ax2.set_title("rms(forces)")
ax2.set_xlabel("Step")
ax2.set_ylabel("$E_h$ Bohr⁻¹ (rad)⁻¹") |
1,096 | https://:@github.com/eljost/pysisyphus.git | 2aaee0dec2e2c07da386ede88d22bd3c2b2baf5e | @@ -131,7 +131,7 @@ def run():
inp = make_input(**inp_kwargs)
inp_fn = "packmol.inp"
with open(inp_fn, "w") as handle:
- handle.write(inp_fn)
+ handle.write(inp)
print(f"Wrote packmol input to '{inp_fn}'")
proc = call_packmol(inp)
| pysisyphus/pack.py | ReplaceText(target='inp' @(134,21)->(134,27)) | def run():
inp = make_input(**inp_kwargs)
inp_fn = "packmol.inp"
with open(inp_fn, "w") as handle:
handle.write(inp_fn)
print(f"Wrote packmol input to '{inp_fn}'")
proc = call_packmol(inp) | def run():
inp = make_input(**inp_kwargs)
inp_fn = "packmol.inp"
with open(inp_fn, "w") as handle:
handle.write(inp)
print(f"Wrote packmol input to '{inp_fn}'")
proc = call_packmol(inp) |
1,097 | https://:@github.com/pashango2/Image4Layer.git | 24060ba346c534032314d6f28011d2edfceec1a2 | @@ -191,7 +191,7 @@ def separate_blend(cb, cs, func, eval_str="func(float(a), float(b))"):
# cs has alpha
if cs_alpha:
- base_img = img.copy()
+ base_img = cb.copy()
base_img.paste(img, mask=cs_alpha)
img = base_img
| image4layer/image4layer.py | ReplaceText(target='cb' @(194,23)->(194,26)) | def separate_blend(cb, cs, func, eval_str="func(float(a), float(b))"):
# cs has alpha
if cs_alpha:
base_img = img.copy()
base_img.paste(img, mask=cs_alpha)
img = base_img
| def separate_blend(cb, cs, func, eval_str="func(float(a), float(b))"):
# cs has alpha
if cs_alpha:
base_img = cb.copy()
base_img.paste(img, mask=cs_alpha)
img = base_img
|
1,098 | https://:@github.com/BadrYoubiIdrissi/hydra-plugins.git | d690e35407ad42bbf99d99ced25e7f3f77dae25b | @@ -46,7 +46,7 @@ class RangeSweeper(Sweeper):
src_lists = []
for s in arguments:
key, value = s.split("=")
- gl = re.match(r'glob\((.+)\)', s)
+ gl = re.match(r'glob\((.+)\)', value)
if ',' in value:
possible_values=value.split(',')
elif ':' in value:
| badr_range_sweeper/hydra_plugins/range_sweeper_badr/range_sweeper_badr.py | ReplaceText(target='value' @(49,43)->(49,44)) | class RangeSweeper(Sweeper):
src_lists = []
for s in arguments:
key, value = s.split("=")
gl = re.match(r'glob\((.+)\)', s)
if ',' in value:
possible_values=value.split(',')
elif ':' in value: | class RangeSweeper(Sweeper):
src_lists = []
for s in arguments:
key, value = s.split("=")
gl = re.match(r'glob\((.+)\)', value)
if ',' in value:
possible_values=value.split(',')
elif ':' in value: |
1,099 | https://:@github.com/annoys-parrot/multi_view_network.git | df17d237d8e022cfa14fe76cce812b3914360e20 | @@ -340,7 +340,7 @@ def BuildMultiViewNetwork(
[v1, v2, v3, v4], name='concatenation')
fully_connected = keras.layers.Dense(
units=hidden_units, name='fully_connected')(concatenation)
- dropout = keras.layers.Dropout(rate=dropout_rate)(concatenation)
+ dropout = keras.layers.Dropout(rate=dropout_rate)(fully_connected)
softmax = keras.layers.Dense(
units=output_units, activation='softmax',
name='softmax')(dropout)
| multi_view_network/models.py | ReplaceText(target='fully_connected' @(343,54)->(343,67)) | def BuildMultiViewNetwork(
[v1, v2, v3, v4], name='concatenation')
fully_connected = keras.layers.Dense(
units=hidden_units, name='fully_connected')(concatenation)
dropout = keras.layers.Dropout(rate=dropout_rate)(concatenation)
softmax = keras.layers.Dense(
units=output_units, activation='softmax',
name='softmax')(dropout) | def BuildMultiViewNetwork(
[v1, v2, v3, v4], name='concatenation')
fully_connected = keras.layers.Dense(
units=hidden_units, name='fully_connected')(concatenation)
dropout = keras.layers.Dropout(rate=dropout_rate)(fully_connected)
softmax = keras.layers.Dense(
units=output_units, activation='softmax',
name='softmax')(dropout) |