Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #407

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Accelerators/GANs/gan.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def train(output_path, max_epoch, to_restore):

for i in range(sess.run(global_step), max_epoch):
for j in range(int(60000 // batch_size)):
print("epoch:%s, iter:%s" % (i, j))
print(f"epoch:{i}, iter:{j}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function train refactored with the following changes:

x_value, _ = mnist.train.next_batch(batch_size)
x_value = 2 * x_value.astype(np.float32) - 1
z_value = generate_prior(batch_size, z_size)
Expand Down
2 changes: 1 addition & 1 deletion C/Tree_2k/examples/visualization/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def compute_segments(line):
if len(data) != 4:
print("### error: can only plot 2D data", file=sys.stderr)
sys.exit(1)
center = data[0:2]
center = data[:2]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function compute_segments refactored with the following changes:

extent = data[2:4]
ur = (center[0] + extent[0], center[1] + extent[1])
ul = (center[0] - extent[0], center[1] + extent[1])
Expand Down
4 changes: 2 additions & 2 deletions CPlusPlus/Tbb/Tree/format_timings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
for line in file:
match = re.match(r'^time: ([^s]+)\s+s$', line)
if match is not None:
time_avg = float(match.group(1))
time_avg = float(match[1])
nr_timings += 1
continue
match = re.match('^procs: (\d+)$', line)
if match is not None:
nr_procs = int(match.group(1))
nr_procs = int(match[1])
Comment on lines -20 to +25
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 20-25 refactored with the following changes:

print('{0:d} {1:.6f}'.format(nr_procs, time_avg/nr_timings))
5 changes: 1 addition & 4 deletions DataStorage/NetCDF/PythonSamples/write_netcdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
arg_parser.add_argument('-v', dest='version', choices=['3', '4'],
default='3', help='NetCDF version to create')
options = arg_parser.parse_args()
if options.version == '3':
version = 'NETCDF3_CLASSIC'
else:
version = 'NETCDF4'
version = 'NETCDF3_CLASSIC' if options.version == '3' else 'NETCDF4'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 20-23 refactored with the following changes:

rootgrp = Dataset(options.file, 'w', format='NETCDF3_CLASSIC')
x_dim = rootgrp.createDimension('x', options.x)
y_dim = rootgrp.createDimension('y', options.y)
Expand Down
3 changes: 1 addition & 2 deletions Debugging/Arithmetic/dna_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ def available_nucl(nucl_left):

def get_nucl(nucl_left):
while True:
avail_nucls = available_nucl(nucl_left)
if avail_nucls:
if avail_nucls := available_nucl(nucl_left):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_nucl refactored with the following changes:

nucl = random.choice(avail_nucls)
nucl_left[nucl] -= 1
yield nucl
Expand Down
2 changes: 1 addition & 1 deletion Debugging/CompilerFlags/FloatEqual/on_circle_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ def compute_y(x, radius):
[0.0, 0.0, 2.0, 1.0, compute_y(1.0, 2.0)],
]

cmd = './on_circle_c.exe'
for case in cases:
cmd = './on_circle_c.exe'
Comment on lines +16 to -17
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 17-17 refactored with the following changes:

args = ['{0:.15f}'.format(x) for x in case]
print(cmd, ' '.join(args))
output = check_output([cmd, *args])
Expand Down
7 changes: 4 additions & 3 deletions Python/Biopython/align_seqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
arg_parser.add_argument('--show', action='store_true',
help='show MUSCLE output')
options = arg_parser.parse_args()
seqs = {}
for seq_record in SeqIO.parse(options.file, options.format):
seqs[seq_record.id] = seq_record.seq
seqs = {
seq_record.id: seq_record.seq
for seq_record in SeqIO.parse(options.file, options.format)
}
Comment on lines -20 to +23
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 20-22 refactored with the following changes:

if options.alignment:
with open(options.alignment, 'r') as alignment_file:
stdout = alignment_file.read()
Expand Down
4 changes: 2 additions & 2 deletions Python/Biopython/entrez_db_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
record = Entrez.read(handle)
db_info = record['DbInfo']
print(db_info['Description'])
print('Count: {}'.format(db_info['Count']))
print('Last update: {}'.format(db_info['LastUpdate']))
print(f"Count: {db_info['Count']}")
print(f"Last update: {db_info['LastUpdate']}")
Comment on lines -21 to +22
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 21-22 refactored with the following changes:

if options.fields:
print('Fields:')
fmt_str = '{Name} ({FullName}): {Description}'
Expand Down
7 changes: 4 additions & 3 deletions Python/Biopython/read_seq.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ def compute_stats(seq):
arg_parser.add_argument('file', help='sequence file to parse')
arg_parser.add_argument('--format', default='fasta', help='file format')
options = arg_parser.parse_args()
seqs = {}
for seq_record in SeqIO.parse(options.file, options.format):
seqs[seq_record.id] = seq_record.seq
seqs = {
seq_record.id: seq_record.seq
for seq_record in SeqIO.parse(options.file, options.format)
}
Comment on lines -26 to +29
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 26-28 refactored with the following changes:

fmt_str = ('id: {id}\n\t'
'length: {stats.length}\n\t'
'gc: {stats.gc}\n\t'
Expand Down
6 changes: 3 additions & 3 deletions Python/Biopython/search_entrez.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@
if options.summary:
handle = Entrez.esummary(db='nucleotide', id=seq_id)
summary = Entrez.read(handle)
print('ID {}:'.format(seq_id))
print(' {}'.format(summary[0]['Title']))
print(' Updated: {}'.format(summary[0]['UpdateDate']))
print(f'ID {seq_id}:')
print(f" {summary[0]['Title']}")
print(f" Updated: {summary[0]['UpdateDate']}")
Comment on lines -29 to +31
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 29-31 refactored with the following changes:

else:
file_name = os.path.join('Data', '{0}.gbk'.format(seq_id))
if not os.path.isfile(file_name):
Expand Down
2 changes: 1 addition & 1 deletion Python/Biopython/seq_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import textwrap

def print_seq_record(seq_record, indent_with=' ', indent=''):
print('Sequence ID: {}'.format(seq_record.id))
print(f'Sequence ID: {seq_record.id}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function print_seq_record refactored with the following changes:

indent += indent_with
print('{0}Name: {1}'.format(indent, seq_record.name))
print('{0}Description: {1}'.format(indent, seq_record.description))
Expand Down
4 changes: 1 addition & 3 deletions Python/Birdsong/create_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ def normalize(signal, ampl):
arg_parser.add_argument('--out', action='store_true',
help='print signal to standard output')
options = arg_parser.parse_args()
if options.specs_file:
pass
else:
if not options.specs_file:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 45-47 refactored with the following changes:

if len(options.freqs) != len(options.ampls):
msg = '# error: {0:d} frequencies for {1:d} amplitudes\n'
sys.stderr.write(msg.format(len(options.freqs),
Expand Down
5 changes: 1 addition & 4 deletions Python/CodeCoverage/functions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
def fac_r(n):
if n < 2:
return 1
else:
return n*fac_r(n - 1)
return 1 if n < 2 else n*fac_r(n - 1)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fac_r refactored with the following changes:


def fac_i(n):
result = 1
Expand Down
5 changes: 1 addition & 4 deletions Python/CodeEvaluation/fac.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
def fac(n):
if n < 2:
return 1
else:
return n*fac(n-1)
return 1 if n < 2 else n*fac(n-1)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fac refactored with the following changes:

5 changes: 1 addition & 4 deletions Python/CodeEvaluation/fib.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
return 1 if n in [0, 1] else fib(n-1) + fib(n-2)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fib refactored with the following changes:

5 changes: 1 addition & 4 deletions Python/CodeTesting/Asserts/fac.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ def fac(n):
'''compute the factorial of given number'''
assert type(n) == int, 'argument must be integer'
assert n >= 0, 'argument must be positive'
if n > 1:
return n*fac(n - 1)
else:
return 1
return n*fac(n - 1) if n > 1 else 1
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fac refactored with the following changes:


if __name__ == '__main__':
for i in range(5):
Expand Down
7 changes: 3 additions & 4 deletions Python/CodeTesting/constant_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,10 @@ def get_value(self, name):
WHERE name = ?''', (name, ))
rows = cursor.fetchall()
cursor.close()
if not rows:
msg = "constant '{0}' is undefined".format(name)
raise UnknownConstantError(msg)
else:
if rows:
return rows[0][0]
msg = "constant '{0}' is undefined".format(name)
raise UnknownConstantError(msg)
Comment on lines -44 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConstantDb.get_value refactored with the following changes:


def get_names(self):
cursor = self._conn.cursor()
Expand Down
2 changes: 1 addition & 1 deletion Python/CommandLineArgs/ArgParse/partial_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
options.resoure_specs))
print('resources: ' + ', '.join(specs))
if options.account:
print('account: ' + options.account)
print(f'account: {options.account}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 22-22 refactored with the following changes:

print('unparsed: ' + ', '.join(unparsed))
2 changes: 1 addition & 1 deletion Python/CommandLineArgs/ArgParse/two_stage_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


def parse_job_script(file_name):
args = list()
args = []
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_job_script refactored with the following changes:

with open(file_name) as file:
for line in file:
if line.lstrip().startswith('#PBS '):
Expand Down
5 changes: 1 addition & 4 deletions Python/ConfigParser/config_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@


def main():
if len(sys.argv) > 1:
cfg_file = sys.argv[1]
else:
cfg_file = 'defaults.conf'
cfg_file = sys.argv[1] if len(sys.argv) > 1 else 'defaults.conf'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

cfg_parser = SafeConfigParser()
cfg_parser.read(cfg_file)
print('Sections:')
Expand Down
3 changes: 1 addition & 2 deletions Python/ContextManager/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ def main():
print('in context {0}'.format(c2._context_nr))
with label('foo') as foo, label('bar') as bar:
print(foo, bar)
with ContextTest(1) as c1, ContextTest(2) as c2:
with (ContextTest(1) as c1, ContextTest(2) as c2):
print('in context {0}'.format(c1._context_nr))
raise Exception()
print('in context {0}'.format(c2._context_nr))
Comment on lines -40 to -43
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

return 0

if __name__ == '__main__':
Expand Down
7 changes: 2 additions & 5 deletions Python/Coroutines/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,12 @@ def process_line(line, mode=float):
if not line:
return None
items = [item.strip() for item in line.split(',')]
if mode == float:
return [float(item) for item in items]
else:
return items
return [float(item) for item in items] if mode == float else items
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function process_line refactored with the following changes:


if __name__ == '__main__':
line = sys.stdin.readline()
names = process_line(line, mode='text')
averagers = [stats() for name in names]
averagers = [stats() for _ in names]
Comment on lines -37 to +34
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 37-37 refactored with the following changes:

for averager in averagers:
next(averager)
for line in sys.stdin:
Expand Down
2 changes: 1 addition & 1 deletion Python/Cython/Numpy/compute_sums.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def py_sum(a):
for func in [array_sum, np.sum, py_sum]:
total = 0.0
start_time = timeit.default_timer()
for iter_nr in range(options.iter):
for _ in range(options.iter):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 28-28 refactored with the following changes:

total += func(a)
total_time = timeit.default_timer() - start_time
print('{0:s}: {1:.6f} s ({2})'.format(func.__name__, total_time,
Expand Down
7 changes: 3 additions & 4 deletions Python/Cython/Primes/primes_vanilla.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@
def primes(kmax):
p = array('i', [0]*1000)
result = []
if kmax > 1000:
kmax = 1000
kmax = min(kmax, 1000)
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
i += 1
if i == k:
p[k] = n
k = k + 1
k += 1
Comment on lines -7 to +16
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function primes refactored with the following changes:

result.append(n)
n = n + 1
return result
6 changes: 4 additions & 2 deletions Python/Dask/create_csv_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

def write_file(args):
file_name, rows, curr_time, delta_time, curr_vals, delta_val = args
fieldnames = ['timestamp']
fieldnames.extend(['C{0:d}'.format(i + 1) for i in range(len(curr_vals))])
fieldnames = [
'timestamp',
*['C{0:d}'.format(i + 1) for i in range(len(curr_vals))],
]
Comment on lines -13 to +16
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function write_file refactored with the following changes:

with open(file_name, 'w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
Expand Down
2 changes: 1 addition & 1 deletion Python/Dask/dask_distr_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get_hostname(i):
if options.verbose:
print('task placement:')
print('\t' + '\n\t'.join(process_locations))
count = dict()
count = {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 42-42 refactored with the following changes:

for process_location in process_locations:
_, _, hostname = process_location.split()
if hostname not in count:
Expand Down
13 changes: 5 additions & 8 deletions Python/DataFormats/Vcd/vcd_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def parse_config_line(meta_data, line):
meta_data[symbol] = demangle_name(name)

def parse_config(vcd_file):
meta_data = dict()
meta_data = {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_config refactored with the following changes:

for line in vcd_file:
line = line.strip()
if line == '$end':
Expand All @@ -37,16 +37,15 @@ def update_buffer(buffer, line, meta_data):
buffer[key] = value

def init_data(meta_data):
data = dict()
data['time'] = list()
data = {'time': []}
for var in meta_data:
data[meta_data[var]] = list()
data[meta_data[var]] = []
Comment on lines -40 to +42
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function init_data refactored with the following changes:

return data

def parse_data(vcd_file, meta_data):
data = init_data(meta_data)
time_stamp = None
buffer = dict()
buffer = {}
Comment on lines -49 to +48
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_data refactored with the following changes:

for line in vcd_file:
line = line.strip()
if line.startswith('#'):
Expand All @@ -68,9 +67,7 @@ def write_vcd_data_structure(out_file, data, sep=' '):
columns = list(data.keys())
out_file.write(sep.join(columns) + '\n')
for time_step in range(len(data['time'])):
data_line = list()
for var in columns:
data_line.append(data[var][time_step])
data_line = [data[var][time_step] for var in columns]
Comment on lines -71 to +70
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function write_vcd_data_structure refactored with the following changes:

out_file.write(sep.join(str(data_item) for data_item in data_line))
out_file.write('\n')

Expand Down
2 changes: 1 addition & 1 deletion Python/DataFormats/agt_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _parse_data(self, agt_file):
if not match:
msg = "line {0:d}: invalid number of measurements '{1}'"
raise AgtDataError(msg.format(self._current_line, nr_lines_str))
nr_lines = int(match.group(1))
nr_lines = int(match[1])
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AgtParser._parse_data refactored with the following changes:

self._current_line += 1
# ignore header line
agt_file.readline()
Expand Down
13 changes: 6 additions & 7 deletions Python/DataFormats/data_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,10 @@ def __iter__(self):
return self

def __next__(self):
if self._current < self.n:
self._current += 1
return self._distr(*self._params)
else:
if self._current >= self.n:
raise StopIteration()
self._current += 1
return self._distr(*self._params)
Comment on lines -50 to +53
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Distribution.__next__ refactored with the following changes:



class DistributionCreator(object):
Expand Down Expand Up @@ -108,9 +107,9 @@ def __init__(self, file_name, table_name, col_defs):
self._row = self._table.row

def _create_table(self, table_name, col_defs):
description = {}
for col_def in col_defs:
description[col_def['name']] = self._typemap[col_def['type']]
description = {
col_def['name']: self._typemap[col_def['type']] for col_def in col_defs
}
Comment on lines -111 to +112
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hdf5Writer._create_table refactored with the following changes:

return self._file.create_table('/', table_name, description)

def set_headers(self, headers):
Expand Down
2 changes: 1 addition & 1 deletion Python/DataFormats/read_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def main():
print('{name} --- {weight}'.format(name=row['name'],
weight=row['weight']))
sum += float(row['weight'])
print('sum = {}'.format(sum))
print(f'sum = {sum}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:


if __name__ == '__main__':
main()
4 changes: 1 addition & 3 deletions Python/DataFormats/read_variable_length_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ def read_array(data_file, length):
arg_parser.add_argument('file', help='binary file to read')
options = arg_parser.parse_args()
with open(options.file, 'rb') as data_file:
buffer = data_file.read(4);
while buffer:
while buffer := data_file.read(4):
length = unpack('I', buffer)[0]
values = read_array(data_file, length)
value_str = ' '.join(f'{x:.2f}' for x in values)
print(f'{length:d}: {value_str:s}')
buffer = data_file.read(4)
Comment on lines -16 to -22
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 16-22 refactored with the following changes:

Loading