Skip to content

Sourcery refactored development branch #12

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

Merged
merged 1 commit into from
Aug 3, 2023
Merged
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
5 changes: 1 addition & 4 deletions source-code/code-evaluation/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 source-code/code-evaluation/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:

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))
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
18 changes: 7 additions & 11 deletions source-code/command-line-arguments/Fire/sayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ def __init__(self, name):
self.name = name

def to(self, name=None):
if name is None:
if self.name is None:
return 'No one to say hello to'
else:
return f'Hello to {self.name}'
else:
if name is not None:
return f'Hello {name}'
if self.name is None:
return 'No one to say hello to'
else:
return f'Hello to {self.name}'
Comment on lines -15 to +20
Copy link
Author

Choose a reason for hiding this comment

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

Function Hello.to refactored with the following changes:


def everyone(self):
return 'hello to everyone'
Expand All @@ -34,15 +33,12 @@ def __init__(self, name):

def to(self, name=None):
if name is None:
if self.name is None:
return 'No one to say bye to'
else:
return f'Bye to {self.name}'
return 'No one to say bye to' if self.name is None else f'Bye to {self.name}'
Comment on lines -37 to +36
Copy link
Author

Choose a reason for hiding this comment

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

Function Bye.to refactored with the following changes:

else:
return f'Bye {name}'

def no_one(self):
return f'Bye to no one'
return 'Bye to no one'
Comment on lines -45 to +41
Copy link
Author

Choose a reason for hiding this comment

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

Function Bye.no_one refactored with the following changes:



class Sayer:
Expand Down
5 changes: 1 addition & 4 deletions source-code/config-parser/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
13 changes: 5 additions & 8 deletions source-code/data-formats/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 source-code/data-formats/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 source-code/data-formats/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 source-code/data-formats/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 source-code/data-formats/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:

3 changes: 1 addition & 2 deletions source-code/data-formats/read_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ def startElement(self, name, attrs):

def characters(self, contents):
if self.in_item:
contents = contents.strip()
if contents:
if contents := contents.strip():
Copy link
Author

Choose a reason for hiding this comment

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

Function BlocksHandler.characters refactored with the following changes:

data = float(contents.strip())
logging.info(f"found '{data}'")
self._stack[-1].add_data(data)
Expand Down
3 changes: 1 addition & 2 deletions source-code/file-system/list_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
options = arg_parser.parse_args()
for directory, _, files in os.walk(options.dir):
if options.verbose:
print("### checking directory '{}'".format(directory),
file=sys.stderr)
print(f"### checking directory '{directory}'", file=sys.stderr)
Copy link
Author

Choose a reason for hiding this comment

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

Lines 19-20 refactored with the following changes:

for file_name in files:
_, ext = os.path.splitext(file_name)
if ext == options.ext:
Expand Down
7 changes: 3 additions & 4 deletions source-code/jinja/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@


def generate_person():
person = {
'id': ''.join(random.choices(string.ascii_letters, k=5)),
return {
'id': ''.join(random.choices(string.ascii_letters, k=5)),
'birthyear': random.randint(1950, 2015),
'nr_friends': random.randint(0, 50),
}
return person
Comment on lines -12 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.

Function generate_person refactored with the following changes:


def main():
arg_parser = ArgumentParser(description='generate random people')
Expand All @@ -29,7 +28,7 @@ def main():
people = [generate_person() for _ in range(options.n)]
environment = Environment(loader=PackageLoader('population', 'templates'),
trim_blocks=True, lstrip_blocks=True)
template = environment.get_template('report.' + options.format)
template = environment.get_template(f'report.{options.format}')
Comment on lines -32 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.

Function main refactored with the following changes:

print(template.render(people=people))

if __name__ == '__main__':
Expand Down
10 changes: 2 additions & 8 deletions source-code/logging/log_it_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,11 @@ def main():
help='number of times to do stuff')
options = arg_parser.parse_args()
format_str = '%(asctime)s:%(levelname)s:%(message)s'
if options.info:
level = logging.INFO
else:
level = logging.WARNING
if options.new_log:
filemode = 'w'
else:
filemode = 'a'
level = logging.INFO if options.info else logging.WARNING
if options.log_file:
log_file = Path(options.log_file)
exists = log_file.exists()
filemode = 'w' if options.new_log else 'a'
Comment on lines -33 to +37
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:

logging.basicConfig(level=level, filename=options.log_file,
filemode=filemode, format=format_str)
else:
Expand Down
2 changes: 1 addition & 1 deletion source-code/paramiko/ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def connect(host, user):
ssh = connect(options.host, options.user)
cmd = 'ls -l'
if options.dir:
cmd += ' ' + options.dir
cmd += f' {options.dir}'
Copy link
Author

Choose a reason for hiding this comment

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

Lines 27-27 refactored with the following changes:

_, stdout, stderr = ssh.exec_command(cmd)
for line in stdout:
print(line.rstrip())
Expand Down
47 changes: 25 additions & 22 deletions source-code/processes/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,14 @@ def find_ancestor(pid=None, username=None):
username = get_username()
process = psutil.Process(pid)
parents = process.parents()
for parent in reversed(parents):
if parent.username() == username:
return parent
return process
return next(
(
parent
for parent in reversed(parents)
if parent.username() == username
),
process,
)
Comment on lines -50 to +57
Copy link
Author

Choose a reason for hiding this comment

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

Function find_ancestor refactored with the following changes:

  • Use the built-in function next instead of a for-loop (use-next)



def get_cmdline(process):
Expand All @@ -63,11 +67,11 @@ def get_affinity(process):


def get_read_open_files(process):
open_files = list()
open_files = []
try:
for file in process.open_files():
try:
if 'r' == file.mode:
if file.mode == 'r':
Comment on lines -66 to +74
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_read_open_files refactored with the following changes:

open_files.append(file.path)
except:
pass
Expand All @@ -77,11 +81,11 @@ def get_read_open_files(process):


def get_write_open_files(process):
open_files = list()
open_files = []
try:
for file in process.open_files():
try:
if 'r' != file.mode:
if file.mode != 'r':
Comment on lines -80 to +88
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_write_open_files refactored with the following changes:

open_files.append(f'{file.path}:{Path(file.path).stat().st_size}')
except:
pass
Expand All @@ -91,8 +95,7 @@ def get_write_open_files(process):


def define_actions(inactive=None):
metrics = dict()
metrics['time'] = Metric('time', lambda x: time.time())
metrics = {'time': Metric('time', lambda x: time.time())}
Comment on lines -94 to +98
Copy link
Author

Choose a reason for hiding this comment

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

Function define_actions refactored with the following changes:

metrics['node'] = Metric('node', lambda x: platform.node())
metrics['pid'] = Metric('pid', lambda x: x.pid)
metrics['ppid'] = Metric('ppid', lambda x: x.ppid())
Expand Down Expand Up @@ -121,11 +124,13 @@ def status_header(metrics):

def process_status(process, metrics):
'''Show properties of the specified process'''
status = list()
status = []
with process.oneshot():
for metric in metrics.values():
if metric.is_active:
status.append(metric.measure(process))
status.extend(
metric.measure(process)
for metric in metrics.values()
if metric.is_active
)
Comment on lines -124 to +133
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_status refactored with the following changes:

return ','.join(status)


Expand All @@ -150,20 +155,18 @@ def main():
if not options.affinity:
inactive.append('affinity')
if not options.files:
inactive.append('read_files')
inactive.append('write_files')
inactive.extend(('read_files', 'write_files'))
metrics = define_actions(inactive)
if options.output_file:
file = open(options.output_file, 'w')
else:
file = sys.stdout
file = open(options.output_file, 'w') if options.output_file else sys.stdout
try:
with file:
print(status_header(metrics), file=file)
while True:
process_info = [process_status(process, metrics)]
for child_process in process.children(recursive=True):
process_info.append(process_status(child_process, metrics))
process_info.extend(
process_status(child_process, metrics)
for child_process in process.children(recursive=True)
)
Comment on lines -153 to +169
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:

print('\n'.join(process_info), file=file)
time.sleep(options.delta)
except KeyboardInterrupt:
Expand Down
3 changes: 1 addition & 2 deletions source-code/subprocess/async_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ def execute(cmd, result):
for stderr_line in iter(process.stderr.readline, ''):
yield stderr_line.strip()
stdout, stderr = process.communicate()
return_code = process.wait()
if return_code:
if return_code := process.wait():
Copy link
Author

Choose a reason for hiding this comment

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

Function execute refactored with the following changes:

raise subprocess.CalledProcessError(return_code, cmd)
else:
result.set(stdout)
Expand Down
5 changes: 1 addition & 4 deletions source-code/xml-generator/gen_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ def random(self):
for _ in range(self._size):
tag = self._tags.random()
element = doc.createElement(tag)
if node_list:
parent = random.choice(node_list)
else:
parent = doc
parent = random.choice(node_list) if node_list else doc
Copy link
Author

Choose a reason for hiding this comment

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

Function Docs.random refactored with the following changes:

parent.appendChild(element)
node_list.append(element)
for element in node_list:
Expand Down