From 67ef29231f79eb42fa224701b2cdaa8f776ef004 Mon Sep 17 00:00:00 2001 From: AlexandreSajus Date: Sun, 12 Dec 2021 16:37:21 +0100 Subject: [PATCH] :hammer: switched autopep8 to black --- coverage_score.py | 12 +- opencodeblocks/blocks/sliderblock.py | 21 ++-- .../blocks/widgets/blocksizegrip.py | 31 ++--- .../blocks/widgets/blocksplitter.py | 2 +- opencodeblocks/blocks/widgets/blocktitle.py | 12 +- opencodeblocks/core/serializable.py | 12 +- opencodeblocks/graphics/theme_manager.py | 12 +- opencodeblocks/graphics/worker.py | 17 +-- opencodeblocks/qss/dark_resources.py | 12 +- opencodeblocks/scene/scene.py | 112 +++++++++--------- pylint_score.py | 14 +-- tests/integration/utils.py | 1 - utils.py | 4 +- 13 files changed, 133 insertions(+), 129 deletions(-) diff --git a/coverage_score.py b/coverage_score.py index 516a2625..abf9031b 100644 --- a/coverage_score.py +++ b/coverage_score.py @@ -7,14 +7,14 @@ from xml.dom import minidom from utils import score_to_rgb_color -if __name__ == '__main__': - file = minidom.parse('coverage.xml') - coverage = file.getElementsByTagName('coverage') - coverage = float(coverage[0].attributes['line-rate'].value) +if __name__ == "__main__": + file = minidom.parse("coverage.xml") + coverage = file.getElementsByTagName("coverage") + coverage = float(coverage[0].attributes["line-rate"].value) coverage_min, coverage_max = 0, 1 - if sys.argv[1] == '--score': + if sys.argv[1] == "--score": print(f"{coverage:.1%}") - elif sys.argv[1] == '--color': + elif sys.argv[1] == "--color": print(score_to_rgb_color(coverage, coverage_min, coverage_max)) else: raise ValueError(f"Unknowed argument: {sys.argv[1]}") diff --git a/opencodeblocks/blocks/sliderblock.py b/opencodeblocks/blocks/sliderblock.py index 21505b78..123034a6 100644 --- a/opencodeblocks/blocks/sliderblock.py +++ b/opencodeblocks/blocks/sliderblock.py @@ -36,7 +36,7 @@ def __init__(self, **kwargs): self.edge_size * 2, self.title_widget.height() + self.edge_size * 2, self.edge_size * 2, - self.edge_size * 2 + self.edge_size * 2, ) self.layout.addWidget(self.slider) self.layout.addLayout(self.variable_layout) @@ -44,7 +44,7 @@ def __init__(self, **kwargs): self.holder.setWidget(self.root) def valueChanged(self): - """ This is called when the value of the slider changes """ + """This is called when the value of the slider changes""" python_code = f"{self.var_name} = {self.value}" self.variable_value.setText(f"{self.value}") @@ -54,32 +54,35 @@ def valueChanged(self): @property def value(self): - """ The value of the slider """ + """The value of the slider""" return str(self.slider.value() / 100) + @value.setter def value(self, value: str): self.slider.setValue(int(float(value) * 100)) @property def var_name(self): - """ The name of the python variable associated with the slider """ + """The name of the python variable associated with the slider""" return self.variable_text.text() + @var_name.setter def var_name(self, value: str): self.variable_text.setText(value) def serialize(self): - """ Return a serialized version of this widget """ + """Return a serialized version of this widget""" base_dict = super().serialize() base_dict["value"] = self.value base_dict["var_name"] = self.var_name return base_dict - def deserialize(self, data: OrderedDict, - hashmap: dict = None, restore_id: bool = True): - """ Restore a slider block from it's serialized state """ - for dataname in ['value','var_name']: + def deserialize( + self, data: OrderedDict, hashmap: dict = None, restore_id: bool = True + ): + """Restore a slider block from it's serialized state""" + for dataname in ["value", "var_name"]: if dataname in data: setattr(self, dataname, data[dataname]) diff --git a/opencodeblocks/blocks/widgets/blocksizegrip.py b/opencodeblocks/blocks/widgets/blocksizegrip.py index c08ee4b9..6b65fa53 100644 --- a/opencodeblocks/blocks/widgets/blocksizegrip.py +++ b/opencodeblocks/blocks/widgets/blocksizegrip.py @@ -1,4 +1,3 @@ - """ Implements the SizeGrip Widget for the Blocks. @@ -12,14 +11,14 @@ class OCBSizeGrip(QSizeGrip): - """ A grip to resize a block """ + """A grip to resize a block""" def __init__(self, block: QGraphicsItem, parent: QWidget = None): """ - Constructor for BlockSizeGrip + Constructor for BlockSizeGrip - block is the QGraphicsItem holding the QSizeGrip. - It's usually an OCBBlock + block is the QGraphicsItem holding the QSizeGrip. + It's usually an OCBBlock """ super().__init__(parent) self.mouseX = 0 @@ -28,23 +27,25 @@ def __init__(self, block: QGraphicsItem, parent: QWidget = None): self.resizing = False def mousePressEvent(self, mouseEvent: QMouseEvent): - """ Start the resizing """ + """Start the resizing""" self.mouseX = mouseEvent.globalX() self.mouseY = mouseEvent.globalY() self.resizing = True - def mouseReleaseEvent(self, mouseEvent: QMouseEvent): # pylint:disable=unused-argument - """ Stop the resizing """ + def mouseReleaseEvent( + self, mouseEvent: QMouseEvent + ): # pylint:disable=unused-argument + """Stop the resizing""" self.resizing = False self.block.scene().history.checkpoint("Resized block", set_modified=True) @property def _zoom(self) -> float: - """ Returns how much the scene is """ + """Returns how much the scene is""" return self.block.scene().views()[0].zoom def mouseMoveEvent(self, mouseEvent: QMouseEvent): - """ Performs resizing of the root widget """ + """Performs resizing of the root widget""" transformed_pt1 = self.block.mapFromScene(QPoint(0, 0)) transformed_pt2 = self.block.mapFromScene(QPoint(1, 1)) @@ -58,14 +59,8 @@ def mouseMoveEvent(self, mouseEvent: QMouseEvent): # relative to the grip, so if the grip moves, the deltaX and deltaY changes. # This creates a shaking effect when resizing. We use global to not # have this effect. - new_width = max( - self.block.width + int(delta_x), - self.block.min_width - ) - new_height = max( - self.block.height + int(delta_y), - self.block.min_height - ) + new_width = max(self.block.width + int(delta_x), self.block.min_width) + new_height = max(self.block.height + int(delta_y), self.block.min_height) self.parent().setGeometry(0, 0, new_width, new_height) self.block.update_all() diff --git a/opencodeblocks/blocks/widgets/blocksplitter.py b/opencodeblocks/blocks/widgets/blocksplitter.py index c9b0de53..a7eee746 100644 --- a/opencodeblocks/blocks/widgets/blocksplitter.py +++ b/opencodeblocks/blocks/widgets/blocksplitter.py @@ -27,5 +27,5 @@ def __init__(self, block: QWidget, orientation: int, parent: QWidget): self.block = block def createHandle(self): - """ Return the middle handle of the splitter """ + """Return the middle handle of the splitter""" return OCBSplitterHandle(self.orientation(), self) diff --git a/opencodeblocks/blocks/widgets/blocktitle.py b/opencodeblocks/blocks/widgets/blocktitle.py index 95c1fd3a..f9a50e18 100644 --- a/opencodeblocks/blocks/widgets/blocktitle.py +++ b/opencodeblocks/blocks/widgets/blocktitle.py @@ -24,7 +24,7 @@ def __init__( size: int = 12, parent: QWidget = None, ): - """ Create a new title for an OCBBlock """ + """Create a new title for an OCBBlock""" Serializable.__init__(self) QLineEdit.__init__(self, text, parent) self.clickTime = None @@ -33,7 +33,7 @@ def __init__( self.setCursorPosition(0) def init_ui(self, color: str, font: str, size: int): - """ Apply the style given to the title """ + """Apply the style given to the title""" self.color = color self.setStyleSheet( f""" @@ -74,7 +74,7 @@ def mouseDoubleClickEvent(self, event: QMouseEvent): self.setFocus(Qt.MouseFocusReason) def serialize(self) -> OrderedDict: - """ Return a serialized version of this widget """ + """Return a serialized version of this widget""" return OrderedDict( [ ("color", self.color), @@ -83,10 +83,8 @@ def serialize(self) -> OrderedDict: ] ) - def deserialize( - self, data: OrderedDict, hashmap: dict = None, restore_id=True - ): - """ Restore a title from serialized data """ + def deserialize(self, data: OrderedDict, hashmap: dict = None, restore_id=True): + """Restore a title from serialized data""" if restore_id: self.id = data.get("id", id(self)) self.init_ui(data["color"], data["font"], data["size"]) diff --git a/opencodeblocks/core/serializable.py b/opencodeblocks/core/serializable.py index 52c8675f..f997d270 100644 --- a/opencodeblocks/core/serializable.py +++ b/opencodeblocks/core/serializable.py @@ -6,19 +6,21 @@ from typing import OrderedDict -class Serializable(): +class Serializable: - """ Serializable base for serializable objects. """ + """Serializable base for serializable objects.""" def __init__(self): self.id = id(self) def serialize(self) -> OrderedDict: - """ Serialize the object as an ordered dictionary. """ + """Serialize the object as an ordered dictionary.""" raise NotImplementedError() - def deserialize(self, data: OrderedDict, hashmap: dict = None, restore_id=True) -> None: - """ Deserialize the object from an ordered dictionary. + def deserialize( + self, data: OrderedDict, hashmap: dict = None, restore_id=True + ) -> None: + """Deserialize the object from an ordered dictionary. Args: data: Dictionnary containing data do deserialize from. diff --git a/opencodeblocks/graphics/theme_manager.py b/opencodeblocks/graphics/theme_manager.py index 9c088271..f1a7f89d 100644 --- a/opencodeblocks/graphics/theme_manager.py +++ b/opencodeblocks/graphics/theme_manager.py @@ -15,12 +15,12 @@ class ThemeManager(QObject): - """ Class loading theme files and providing the options set in those files """ + """Class loading theme files and providing the options set in those files""" themeChanged = pyqtSignal() def __init__(self, parent=None): - """ Load the default themes and the fonts available to construct the ThemeManager """ + """Load the default themes and the fonts available to construct the ThemeManager""" super().__init__(parent) self._preferred_fonts = ["Inconsolata", "Roboto Mono", "Courier"] self.recommended_font_family = "Monospace" @@ -39,7 +39,7 @@ def __init__(self, parent=None): full_path = os.path.join(theme_path, p) if os.path.isfile(full_path) and full_path.endswith(".theme"): name = os.path.splitext(os.path.basename(p))[0] - with open(full_path, 'r', encoding="utf-8") as f: + with open(full_path, "r", encoding="utf-8") as f: theme = Theme(name, f.read()) self._themes.append(theme) @@ -53,11 +53,11 @@ def selected_theme_index(self, value: int): self.themeChanged.emit() def list_themes(self) -> List[str]: - """ List the themes """ + """List the themes""" return [theme.name for theme in self._themes] def current_theme(self) -> Theme: - """ Return the current theme """ + """Return the current theme""" return self._themes[self.selected_theme_index] @@ -65,7 +65,7 @@ def current_theme(self) -> Theme: def theme_manager(): - """ Retreive the theme manager of the application """ + """Retreive the theme manager of the application""" global theme_handle if theme_handle is None: theme_handle = ThemeManager() diff --git a/opencodeblocks/graphics/worker.py b/opencodeblocks/graphics/worker.py index abb6185a..774aa3c4 100644 --- a/opencodeblocks/graphics/worker.py +++ b/opencodeblocks/graphics/worker.py @@ -8,7 +8,8 @@ class WorkerSignals(QObject): - """ Defines the signals available from a running worker thread. """ + """Defines the signals available from a running worker thread.""" + stdout = pyqtSignal(str) image = pyqtSignal(str) finished = pyqtSignal() @@ -17,10 +18,10 @@ class WorkerSignals(QObject): class Worker(QRunnable): - """ Worker thread """ + """Worker thread""" def __init__(self, kernel, code): - """ Initialize the worker object. """ + """Initialize the worker object.""" super().__init__() self.kernel = kernel @@ -28,7 +29,7 @@ def __init__(self, kernel, code): self.signals = WorkerSignals() async def run_code(self): - """ Run the code in the block """ + """Run the code in the block""" # Execute the code self.kernel.client.execute(self.code) done = False @@ -37,17 +38,17 @@ async def run_code(self): # Save kernel message and send it to the GUI output, output_type, done = self.kernel.update_output() if done is False: - if output_type == 'text': + if output_type == "text": self.signals.stdout.emit(output) - elif output_type == 'image': + elif output_type == "image": self.signals.image.emit(output) - elif output_type == 'error': + elif output_type == "error": self.signals.error.emit() self.signals.finished.emit() self.signals.finished_block.emit() def run(self): - """ Execute the run_code method asynchronously. """ + """Execute the run_code method asynchronously.""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.run_code()) diff --git a/opencodeblocks/qss/dark_resources.py b/opencodeblocks/qss/dark_resources.py index a41ea54a..1c2aad50 100644 --- a/opencodeblocks/qss/dark_resources.py +++ b/opencodeblocks/qss/dark_resources.py @@ -492,7 +492,7 @@ \x00\x00\x01\x68\xe2\x98\x0e\xbe\ " -qt_version = [int(v) for v in QtCore.qVersion().split('.')] +qt_version = [int(v) for v in QtCore.qVersion().split(".")] if qt_version < [5, 8, 0]: rcc_version = 1 qt_resource_struct = qt_resource_struct_v1 @@ -502,13 +502,15 @@ def qInitResources(): - QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, - qt_resource_name, qt_resource_data) + QtCore.qRegisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data + ) def qCleanupResources(): - QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, - qt_resource_name, qt_resource_data) + QtCore.qUnregisterResourceData( + rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data + ) qInitResources() diff --git a/opencodeblocks/scene/scene.py b/opencodeblocks/scene/scene.py index 9069e309..ff2b85cb 100644 --- a/opencodeblocks/scene/scene.py +++ b/opencodeblocks/scene/scene.py @@ -25,13 +25,19 @@ class OCBScene(QGraphicsScene, Serializable): - """ Scene for the OCB Window. """ - - def __init__(self, parent=None, - background_color: str = "#393939", - grid_color: str = "#292929", grid_light_color: str = "#2f2f2f", - width: int = 64000, height: int = 64000, - grid_size: int = 20, grid_squares: int = 5): + """Scene for the OCB Window.""" + + def __init__( + self, + parent=None, + background_color: str = "#393939", + grid_color: str = "#292929", + grid_light_color: str = "#2f2f2f", + width: int = 64000, + height: int = 64000, + grid_size: int = 20, + grid_squares: int = 5, + ): Serializable.__init__(self) QGraphicsScene.__init__(self, parent=parent) @@ -42,8 +48,7 @@ def __init__(self, parent=None, self.grid_squares = grid_squares self.width, self.height = width, height - self.setSceneRect(-self.width // 2, -self.height // - 2, self.width, self.height) + self.setSceneRect(-self.width // 2, -self.height // 2, self.width, self.height) self.setBackgroundBrush(self._background_color) self._has_been_modified = False @@ -54,7 +59,7 @@ def __init__(self, parent=None, @property def has_been_modified(self): - """ True if the scene has been modified, False otherwise. """ + """True if the scene has been modified, False otherwise.""" return self._has_been_modified @has_been_modified.setter @@ -64,11 +69,11 @@ def has_been_modified(self, value: bool): callback() def addHasBeenModifiedListener(self, callback: FunctionType): - """ Add a callback that will trigger when the scene has been modified. """ + """Add a callback that will trigger when the scene has been modified.""" self._has_been_modified_listeners.append(callback) def sortedSelectedItems(self) -> List[Union[OCBBlock, OCBEdge]]: - """ Returns the selected blocks and selected edges in two separate lists. """ + """Returns the selected blocks and selected edges in two separate lists.""" selected_blocks, selected_edges = [], [] for item in self.selectedItems(): if isinstance(item, OCBBlock): @@ -78,12 +83,12 @@ def sortedSelectedItems(self) -> List[Union[OCBBlock, OCBEdge]]: return selected_blocks, selected_edges def drawBackground(self, painter: QPainter, rect: QRectF): - """ Draw the Scene background """ + """Draw the Scene background""" super().drawBackground(painter, rect) self.drawGrid(painter, rect) def drawGrid(self, painter: QPainter, rect: QRectF): - """ Draw the background grid """ + """Draw the background grid""" left = int(math.floor(rect.left())) top = int(math.floor(rect.top())) right = int(math.ceil(rect.right())) @@ -118,51 +123,51 @@ def drawGrid(self, painter: QPainter, rect: QRectF): painter.drawLines(*lines_light) def save(self, filepath: str): - """ Save the scene into filepath. """ + """Save the scene into filepath.""" self.save_to_ipyg(filepath) self.has_been_modified = False def save_to_ipyg(self, filepath: str): - """ Save the scene into filepath as interactive python graph (.ipyg). """ - if '.' not in filepath: - filepath += '.ipyg' + """Save the scene into filepath as interactive python graph (.ipyg).""" + if "." not in filepath: + filepath += ".ipyg" - extention_format = filepath.split('.')[-1] - if extention_format != 'ipyg': + extention_format = filepath.split(".")[-1] + if extention_format != "ipyg": raise NotImplementedError(f"Unsupported format {extention_format}") - with open(filepath, 'w', encoding='utf-8') as file: + with open(filepath, "w", encoding="utf-8") as file: file.write(json.dumps(self.serialize(), indent=4)) def load(self, filepath: str): - """ Load a saved scene. + """Load a saved scene. Args: filepath: Path to the file to load. """ - if filepath.endswith('.ipyg'): + if filepath.endswith(".ipyg"): data = self.load_from_ipyg(filepath) else: - extention_format = filepath.split('.')[-1] + extention_format = filepath.split(".")[-1] raise NotImplementedError(f"Unsupported format {extention_format}") self.deserialize(data) self.history.checkpoint("Loaded scene") self.has_been_modified = False def load_from_ipyg(self, filepath: str): - """ Load an interactive python graph (.ipyg) into the scene. + """Load an interactive python graph (.ipyg) into the scene. Args: filepath: Path to the .ipyg file to load. """ - with open(filepath, 'r', encoding='utf-8') as file: + with open(filepath, "r", encoding="utf-8") as file: data = json.loads(file.read()) return data def clear(self): - """ Clear the scene from all items. """ + """Clear the scene from all items.""" self.has_been_modified = False return super().clear() @@ -176,36 +181,37 @@ def serialize(self) -> OrderedDict: edges.append(item) blocks.sort(key=lambda x: x.id) edges.sort(key=lambda x: x.id) - return OrderedDict([ - ('id', self.id), - ('blocks', [block.serialize() for block in blocks]), - ('edges', [edge.serialize() for edge in edges]), - ]) + return OrderedDict( + [ + ("id", self.id), + ("blocks", [block.serialize() for block in blocks]), + ("edges", [edge.serialize() for edge in edges]), + ] + ) def create_graph(self) -> nx.DiGraph: - """ Create a networkx graph from the scene. """ + """Create a networkx graph from the scene.""" edges = [] for item in self.items(): if isinstance(item, OCBEdge): edges.append(item) graph = nx.DiGraph() for edge in edges: - graph.add_edge(edge.source_socket.block, - edge.destination_socket.block) + graph.add_edge(edge.source_socket.block, edge.destination_socket.block) return graph - def create_block_from_file( - self, filepath: str, x: float = 0, y: float = 0): - """ Create a new block from a .ocbb file """ - with open(filepath, 'r', encoding='utf-8') as file: + def create_block_from_file(self, filepath: str, x: float = 0, y: float = 0): + """Create a new block from a .ocbb file""" + with open(filepath, "r", encoding="utf-8") as file: data = json.loads(file.read()) data["position"] = [x, y] data["sockets"] = {} self.create_block(data, None, False) - def create_block(self, data: OrderedDict, hashmap: dict = None, - restore_id: bool = True) -> OCBBlock: - """ Create a new block from an OrderedDict """ + def create_block( + self, data: OrderedDict, hashmap: dict = None, restore_id: bool = True + ) -> OCBBlock: + """Create a new block from an OrderedDict""" block = None @@ -215,34 +221,34 @@ def create_block(self, data: OrderedDict, hashmap: dict = None, for block_name in block_files: block_module = getattr(blocks, block_name) if isinstance(block_module, ModuleType): - if hasattr(block_module, data['block_type']): - block_constructor = getattr(blocks, data['block_type']) + if hasattr(block_module, data["block_type"]): + block_constructor = getattr(blocks, data["block_type"]) if block_constructor is None: - raise NotImplementedError( - f"{data['block_type']} is not a known block type") + raise NotImplementedError(f"{data['block_type']} is not a known block type") block = block_constructor() block.deserialize(data, hashmap, restore_id) self.addItem(block) if hashmap is not None: - hashmap.update({data['id']: block}) + hashmap.update({data["id"]: block}) return block - def deserialize(self, data: OrderedDict, - hashmap: dict = None, restore_id: bool = True): + def deserialize( + self, data: OrderedDict, hashmap: dict = None, restore_id: bool = True + ): self.clear() hashmap = hashmap if hashmap is not None else {} if restore_id: - self.id = data['id'] + self.id = data["id"] # Create blocks - for block_data in data['blocks']: + for block_data in data["blocks"]: self.create_block(block_data, hashmap, restore_id) # Create edges - for edge_data in data['edges']: + for edge_data in data["edges"]: edge = OCBEdge() edge.deserialize(edge_data, hashmap, restore_id) self.addItem(edge) - hashmap.update({edge_data['id']: edge}) + hashmap.update({edge_data["id"]: edge}) diff --git a/pylint_score.py b/pylint_score.py index 4f8a91eb..cf64757e 100644 --- a/pylint_score.py +++ b/pylint_score.py @@ -53,21 +53,19 @@ def register(linter): linter.register_reporter(MyReporterClass) -if __name__ == '__main__': - options = [ - 'opencodeblocks', - "--output-format=pylint_score.MyReporterClass" - ] +if __name__ == "__main__": + options = ["opencodeblocks", "--output-format=pylint_score.MyReporterClass"] results = Run(options, exit=False) score = results.linter.stats.global_note score_min = 8.0 score_max = 10 - if sys.argv[1] == '--score': + if sys.argv[1] == "--score": print(f"{score:.2f}") if score < score_min or score > score_max: raise Exception( - f'Insufficient score with pylint: {score:.2f}<{score_min:.2f}') - elif sys.argv[1] == '--color': + f"Insufficient score with pylint: {score:.2f}<{score_min:.2f}" + ) + elif sys.argv[1] == "--color": print(score_to_rgb_color(score, score_min=score_min, score_max=score_max)) else: raise ValueError(f"Unknowed argument: {sys.argv[1]}") diff --git a/tests/integration/utils.py b/tests/integration/utils.py index 956a7f7f..810106d5 100644 --- a/tests/integration/utils.py +++ b/tests/integration/utils.py @@ -21,7 +21,6 @@ class CheckingQueue(Queue): - def check_equal(self, a, b, msg=""): self.put([CHECK_MSG, a, b, msg]) diff --git a/utils.py b/utils.py index 48dfb332..aef55d62 100644 --- a/utils.py +++ b/utils.py @@ -7,12 +7,12 @@ def interpolate(weight, x, y): - return x * weight + (1-weight) * y + return x * weight + (1 - weight) * y def score_to_rgb_color(score, score_min, score_max): normalized_score = max(0, (score - score_min) / (score_max - score_min)) hsv_color = (interpolate(normalized_score, 0.33, 0), 1, 1) rgb_color = hsv_to_rgb(*hsv_color) - rgb_color = tuple(int(255*value) for value in rgb_color) + rgb_color = tuple(int(255 * value) for value in rgb_color) return f"rgb{rgb_color}"