| Total Complexity | 6 |
| Total Lines | 65 |
| Duplicated Lines | 43.08 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | import operator |
||
| 2 | from collections.abc import Iterable |
||
| 3 | |||
| 4 | import networkx as nx |
||
| 5 | import psutil |
||
| 6 | |||
| 7 | import graphinate |
||
| 8 | |||
| 9 | |||
| 10 | def processes_graph_model(): |
||
| 11 | graph_model = graphinate.model("Processes Graph") |
||
| 12 | |||
| 13 | def processes() -> Iterable[psutil.Process]: |
||
| 14 | for pid in psutil.pids(): |
||
| 15 | if psutil.pid_exists(pid): |
||
| 16 | yield psutil.Process(pid) |
||
| 17 | |||
| 18 | processes_list = [{'pid': p.pid, 'name': p.name(), 'parent_pid': p.parent().pid if p.parent() else None} for p in |
||
| 19 | processes()] |
||
| 20 | |||
| 21 | @graph_model.node(key=operator.itemgetter('pid'), label=operator.itemgetter('name')) |
||
| 22 | def process(): |
||
| 23 | yield from processes_list |
||
| 24 | |||
| 25 | @graph_model.edge() |
||
| 26 | def edge(): |
||
| 27 | for p in processes_list: |
||
| 28 | parent_pid = p.get('parent_pid') |
||
| 29 | if parent_pid: |
||
| 30 | yield {'source': p.get('pid'), 'target': parent_pid} |
||
| 31 | |||
| 32 | return graph_model |
||
| 33 | |||
| 34 | |||
| 35 | model = processes_graph_model() |
||
| 36 | |||
| 37 | View Code Duplication | if __name__ == '__main__': |
|
|
|
|||
| 38 | use_materialize = True |
||
| 39 | |||
| 40 | if use_materialize: |
||
| 41 | # Materialize the GraphModel |
||
| 42 | graphinate.materialize( |
||
| 43 | model, |
||
| 44 | builder=graphinate.builders.GraphQLBuilder, |
||
| 45 | actualizer=graphinate.graphql |
||
| 46 | ) |
||
| 47 | |||
| 48 | else: |
||
| 49 | # Or |
||
| 50 | |||
| 51 | # 1. Define Graph Builder |
||
| 52 | builder = graphinate.builders.NetworkxBuilder(model=model) |
||
| 53 | |||
| 54 | # Then |
||
| 55 | # 2. Build the Graph object |
||
| 56 | graph: nx.Graph = builder.build() |
||
| 57 | |||
| 58 | # Then |
||
| 59 | # 3. Option A - Output to console |
||
| 60 | print(graph) |
||
| 61 | |||
| 62 | # Or |
||
| 63 | # 3. Option B - Output as a plot |
||
| 64 | graphinate.materializers.plot(graph) |
||
| 65 |