Skip to content

Commit 7d9b935

Browse files
committed
[Misc][Lex] Linting
1 parent 2e9c259 commit 7d9b935

File tree

11 files changed

+45
-45
lines changed

11 files changed

+45
-45
lines changed

main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
22

3-
from scheduling import main as scheduling_main
3+
from process_scheduling import main as scheduling_main
44
from memory_managing import main as memory_managing_main
55
from utils.io import input_bounded_num
66
from views import View
@@ -32,4 +32,4 @@ def main():
3232
is_running = False
3333

3434
if __name__ == "__main__":
35-
main()
35+
main()

memory_managing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def main():
2323
pages = [int(page) if page.isdigit() else page for page in pages]
2424

2525
# Selection of memory algorithms to use for simulation
26-
memory_choices: List[Memory] = [FIFO, LRU, LFU, Optimal]
26+
memory_choices = [FIFO, LRU, LFU, Optimal]
2727
print(View.numbered_list(m.name for m in memory_choices), end="\n\n")
2828

2929
is_selecting = True
@@ -74,7 +74,7 @@ def main():
7474

7575
print("## Memory State Visualization")
7676
print("Legend: F -> Page Fault | H -> Page Hit")
77-
table = TableView(header=["Time"] + [s.snapped_on for s in paging_timeline], footer=["Status"] + [s.status for s in paging_timeline])
77+
table = TableView(header=["Time"] + [str(s.snapped_on) for s in paging_timeline], footer=["Status"] + [s.status for s in paging_timeline])
7878
for frame in range(memory.capacity):
7979
row_header = "Frame {}".format(memory.frame_label_of(memory[frame]))
8080
table.add_item(row_header, *(s.snapshot[frame] if s.snapshot[frame] is not None else "--" for s in paging_timeline))
@@ -103,7 +103,7 @@ def main():
103103
print()
104104
print("===== Summary Statistics =====")
105105
print("Legend: Ranked by page hits")
106-
print("Page References:", page_ref)
106+
print("Page References:", " ".join(str(page) for page in pages))
107107

108108
memory_metrics.sort(key=lambda metric : metric.hits, reverse=True)
109109
summary_table = TableView(min_cell_width=8, header=["Rank#", "Page Replacement Algorithm", "Hits", "Faults", "Hit%", "Fault%"])
@@ -112,4 +112,4 @@ def main():
112112
summary_table.render()
113113

114114
if __name__ == "__main__":
115-
main()
115+
main()

modules/memories/memory.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class Memory(ABC, Generic[T]):
1212
def __init__(self, frame_size: int):
1313
self._memory: List[Optional[T]] = [None] * frame_size
1414
self._capacity: int = frame_size
15-
self._iter_ptr: int = 0
15+
self.__iter_ptr: int = 0
1616

1717
def __eq__(self, other: 'Memory'):
1818
return self.name == other.name and self.size == other.size and self._capacity == other.capacity and all(a == b for a, b in zip(self._memory, other))
@@ -21,13 +21,13 @@ def __getitem__(self, idx: int):
2121
return self._memory[idx]
2222

2323
def __iter__(self):
24-
self._iter_ptr = 0
24+
self.__iter_ptr = 0
2525
return self
2626

2727
def __next__(self):
28-
if self._iter_ptr < self._capacity:
29-
value = self._memory[self._iter_ptr]
30-
self._iter_ptr += 1
28+
if self.__iter_ptr < self._capacity:
29+
value = self._memory[self.__iter_ptr]
30+
self.__iter_ptr += 1
3131
return value
3232

3333
raise StopIteration

modules/processor.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def __last_log_end_time(self):
2727

2828
def __record_cleared_process(self, cleared_process: Process):
2929
""" Records the cleared process to the logs. """
30-
log = ProcessLog(cleared_process.pid, self.__last_log_end_time, self.__clock.time, tag=cleared_process.queue_level)
30+
log = ProcessLog(str(cleared_process.pid), self.__last_log_end_time, self.__clock.time, tag=cleared_process.queue_level)
3131
self.__process_logs.append(log)
3232

3333
def __record_idle_time(self, loaded_process: Process):
@@ -48,7 +48,7 @@ def is_occupied(self):
4848

4949
@property
5050
def is_finished(self):
51-
return self.is_occupied and self.__current_process.is_depleted
51+
return self.__current_process is not None and self.__current_process.is_depleted
5252

5353
@property
5454
def idle_time(self):
@@ -65,11 +65,10 @@ def current_process(self):
6565

6666
def run(self, time_quantum = 1):
6767
""" Runs the processor by a given time quantum. """
68-
if self.is_occupied:
69-
for _ in range(time_quantum):
70-
if not self.__current_process.is_depleted:
71-
self.__current_process.tick()
72-
self.__tick_signal.emit(self.__current_process)
68+
for _ in range(time_quantum):
69+
if self.__current_process is not None and not self.__current_process.is_depleted:
70+
self.__current_process.tick()
71+
self.__tick_signal.emit(self.__current_process)
7372

7473
def on_tick(self, fn: Callable[[Process], None]):
7574
""" Adds a function to listen whenever the processor does a tick. """
@@ -96,7 +95,7 @@ def clear(self):
9695
""" Removes a loaded process from the processor, and returns that removed process to the caller. """
9796
cleared_process = None
9897

99-
if self.is_occupied:
98+
if self.__current_process is not None:
10099
cleared_process = self.__current_process
101100
self.__current_process = None
102101
self.__clear_signal.emit(cleared_process)
@@ -109,4 +108,4 @@ def on_clear(self, fn: Callable[[Process], None]):
109108

110109
def off_clear(self, fn: Callable[[Process], None]):
111110
""" Removes a function listening to the processor clear. """
112-
self.__clear_signal.ignore(fn)
111+
self.__clear_signal.ignore(fn)

modules/schedulers/mlfq.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self, processes: List[Process], processor: Processor, time_quantums
2929
self.__layers.append(last_layer(processes, processor))
3030

3131
@staticmethod
32-
def last_layer_choices() -> List[Scheduler]:
32+
def last_layer_choices():
3333
return [FCFS, SJF, PriorityNP]
3434

3535
@classmethod
@@ -40,7 +40,7 @@ def factory(cls, time_quantums: List[int], last_layer: Callable[[List[Process],
4040

4141
@property
4242
def round_robin_layers(self) -> List[RoundRobin]:
43-
return self.__layers[:-1]
43+
return self.__layers[:-1] # pyright: ignore[reportGeneralTypeIssues]
4444

4545
@property
4646
def last_layer(self):
@@ -75,4 +75,4 @@ def run(self, timestamp: int, is_allowed_to_preempt: bool = True):
7575
if len(self._ready_queue) == 0:
7676
self._ready_queue = self.last_layer._ready_queue
7777

78-
return self._ready_queue
78+
return self._ready_queue

modules/schedulers/mlq.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def __init__(self, processes: List[Process], processor: Processor, layers: List[
2525
self.__layers.append(layer_instance)
2626

2727
@staticmethod
28-
def layer_choices() -> List[Scheduler]:
28+
def layer_choices():
2929
return [FCFS, SJF, PriorityNP, Priority, RoundRobin, SRTF]
3030

3131
@classmethod
@@ -68,4 +68,4 @@ def run(self, timestamp: int, is_allowed_to_preempt: bool = True) -> List[Proces
6868
self._processor.on_tick(layer.decrement_time_window)
6969
break
7070

71-
return self._ready_queue
71+
return self._ready_queue

scheduling.py renamed to process_scheduling.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import os
2-
from typing import List
2+
from typing import List, Any
33

44
from models import Process, ProcessLog
55
from modules import Processor, Clock
6-
from modules.schedulers import Scheduler, FCFS, SJF, PriorityNP, Priority, RoundRobin, SRTF, MLQ, MLFQ
6+
from modules.schedulers import FCFS, SJF, PriorityNP, Priority, RoundRobin, SRTF, MLQ, MLFQ
77
from views import View, TableView, GanttView
88
from utils.io import input_bounded_num
99

1010
def create_process_execution_gantt(process_dump: List[ProcessLog], layers: List[str] = []):
1111
layer_gantts = [GanttView(name="[{}]".format(num), show_timestamps=num == len(layers)) for num, _ in enumerate(layers, start=1)]
12-
merged_gantt = GanttView(name="[A]" if len(layers) > 0 else None)
12+
merged_gantt = GanttView(name="[A]" if len(layers) > 0 else "")
1313
for log in process_dump:
1414
name = "P" + str(log.name) if type(log.name) == int else log.name
1515
time = log.end
@@ -25,8 +25,8 @@ def create_os_metrics(processes: List[Process], total_run_time: int, total_idle_
2525
metrics = ""
2626

2727
metrics += "CPU Utilization: {:.2f}%\n".format((float(total_run_time - total_idle_time) / float(total_run_time)) * 100)
28-
metrics += "Average TAT: {:.2f}\n".format(sum(p.turnaround for p in processes) / len(processes))
29-
metrics += "Average WT: {:.2f}".format(sum(p.waiting for p in processes) / len(processes))
28+
metrics += "Average TAT: {:.2f}\n".format(sum(p.turnaround for p in processes if p.turnaround is not None) / len(processes))
29+
metrics += "Average WT: {:.2f}".format(sum(p.waiting for p in processes if p.waiting is not None) / len(processes))
3030

3131
return metrics
3232

@@ -74,7 +74,7 @@ def configure_mlq(num_layers: int):
7474
if layer_scheduler == RoundRobin:
7575
time_quantum = input_bounded_num("Time quantum: ")
7676
layer_names.append(layer_scheduler.name + " | q=" + str(time_quantum))
77-
layers.append(layer_scheduler.factory(time_quantum, False))
77+
layers.append(RoundRobin.factory(time_quantum, False))
7878
else:
7979
layer_names.append(layer_scheduler.name)
8080
layers.append(layer_scheduler.factory())
@@ -108,23 +108,23 @@ def main():
108108
print("===== CPU Scheduling Simulator =====")
109109

110110
# Select a scheduler
111-
scheduler_choices: List[Scheduler] = [FCFS, SJF, PriorityNP, Priority, RoundRobin, SRTF, MLQ, MLFQ]
111+
scheduler_choices = [FCFS, SJF, PriorityNP, Priority, RoundRobin, SRTF, MLQ, MLFQ]
112112
print(View.numbered_list(s.name for s in scheduler_choices), end="\n\n")
113113
scheduler_choice = input_bounded_num("Select a scheduler: ", max=len(scheduler_choices))
114114

115-
chosen_scheduler: Scheduler = scheduler_choices[scheduler_choice - 1]
115+
chosen_scheduler = scheduler_choices[scheduler_choice - 1]
116116
has_priority_field: bool = chosen_scheduler.has_priority_field
117117
has_queue_level_field: bool = chosen_scheduler.has_queue_level_field
118118

119119
# Configure the chosen scheduler
120120
time_quantum: int = 0
121121
layer_names: List[str] = []
122-
scheduler_factory = None
122+
scheduler_factory: Any = None
123123

124124
print("\n=====", chosen_scheduler.name, "Configuration =====")
125125
if chosen_scheduler == RoundRobin:
126126
time_quantum = input_bounded_num("Time quantum: ")
127-
scheduler_factory = chosen_scheduler.factory(time_quantum, True)
127+
scheduler_factory = RoundRobin.factory(time_quantum, True)
128128
elif chosen_scheduler.is_multilevel:
129129
num_layers = input_bounded_num("Number of Layers: ")
130130

@@ -205,4 +205,4 @@ def main():
205205
print(metrics)
206206

207207
if __name__ == "__main__":
208-
main()
208+
main()

utils/io.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import List, Optional
22

3-
def input_bounded_num(prompt: object = "", min: int = 1, max: Optional[int] = None):
3+
def input_bounded_num(prompt: str = "", min: int = 1, max: Optional[int] = None):
44
""" Get a number input from the user that satisfies a certain minimum and maximum. """
55
result: Optional[int] = None
66

@@ -21,7 +21,7 @@ def input_bounded_num(prompt: object = "", min: int = 1, max: Optional[int] = No
2121

2222
return result
2323

24-
def input_choice(prompt: object = "", choices: List[str] = [], default: str = ""):
24+
def input_choice(prompt: str = "", choices: List[str] = [], default: str = ""):
2525
""" Make a user select between a set of values. """
2626
result: Optional[str] = None
2727
prompt_suffix = "(" + "/".join(choices) + (", default: " + default if default else "") + ")"
@@ -42,4 +42,4 @@ def input_choice(prompt: object = "", choices: List[str] = [], default: str = ""
4242
except:
4343
print("Please input {} only.".format("(" + "/".join(choices) + ")"))
4444

45-
return result
45+
return result

views/gantt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List, Optional
1+
from typing import List
22
from views import View
33

44
class GanttView(View):
@@ -35,4 +35,4 @@ def add_item(self, name: str, time: int):
3535
return self
3636

3737
def render(self):
38-
print(self)
38+
print(self)

views/table.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def __str__(self):
3535

3636
def add_item(self, *data: Any):
3737
self._adjust_cell_sizes_to_fit(*data)
38-
self.__data.append(data)
38+
self.__data.append(list(data))
3939
return self
4040

4141
def render(self):
42-
print(self)
42+
print(self)

views/view.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ def _format_row(self, items: List[Any], sep: str = "|"):
3636

3737
def _create_separator_line(self, joint: str = "+", line: str = "-"):
3838
return joint + joint.join(line * w for w in self._cell_widths) + joint
39-
39+
40+
@staticmethod
4041
def numbered_list(items_iter: Iterable[Any], start_at: int = 1, is_reversed: bool = False):
4142
"""
4243
Turns a set of items into a string of numbered list. The numbering is sequential,
@@ -72,4 +73,4 @@ def add_item(self):
7273
@abstractmethod
7374
def render(self):
7475
""" Render the given view to the console. """
75-
pass
76+
pass

0 commit comments

Comments
 (0)