text
stringlengths
1
2.12k
source
dict
javascript, api, vue.js .controls .navigate.navigate-play { width: 38px; height: 38px; } .navigate-play .fa-play { margin-left: 3px; } <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://unpkg.com/axios@0.22.0/dist/axios.min.js"></script> <script src="https://unpkg.com/vue@next"></script> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;500&display=swap" rel="stylesheet"> <div class="player-container"> <div id="audioPlayer"> <span class="volume" @click="toggleMute"> <i v-show="!muted" class="fa fa-volume-up"></i> <i v-show="muted" class="fa fa-volume-off"></i> </span> <div class="album"> <div class="album-items"> <div class="cover" :class="{'spinning' : isPlaying}"></div> <div class="info"> <h1>{{tracks[trackCount].name}}</h1> <h2>{{tracks[trackCount].artistName}}</h2> </div> </div> </div> <div class="to-bottom"> <div class="progress-bar" ref="progressBar"> <span :style="{ width: trackProgress + '%' }"></span> </div> <div class="controls"> <div class="navigate navigate-prev" :class="{'disabled' : trackCount == 0}" @click="prevTrack"> <i class="fa fa-step-backward"></i> </div> <div class="navigate navigate-play" @click="playPause"> <i v-show="!isPlaying" class="fa fa-play"></i> <i v-show="isPlaying" class="fa fa-pause"></i> </div> <div class="navigate navigate-next" :class="{'disabled' : trackCount == tracks.length - 1}" @click="nextTrack"> <i class="fa fa-step-forward"></i> </div> </div> </div> </div> </div> Concerns Is the code DRY enough? Is the code far from sticking o best practices? Is the app missing importan fetures in your oppinon? What about the app's aesthetics?
{ "domain": "codereview.stackexchange", "id": 42666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, api, vue.js", "url": null }
javascript, api, vue.js Answer: Firstly, just want to say great job in creating your audio player! (I think I may have commented on one of the earlier issues you posted). Secondly there is nothing "wrong" with your code but of course there are things that could be improved and even my suggestions may not be perfect, or could be improved upon still. What I would say though is the following: The propery trackCount would lead most people to believe that it refers to the total number of tracks. Looking more closely at your code trackIndex or even currentTrackIndex would be clearer semantically, and immediately understood by someone reading for the first time. Do not underestimate the importance of naming your variables, properties and functions clearly! I have concerns about using player: new Audio() in the component's data as Vue will try and make this HTML audio element 'reactive' which is not necessary and a waste of resources setting up watchers etc. I would instead do one of the following: Add a player property before data. This creates a static property which can be accessed in the script via this.$options.player. At the top of your created method do this.player = new Audio(); The advantage to the first option generally is that you can access the properties of $options in the template, although this probably won't affect your component. You have two repeated lines in your next/prev track methods. I would do a couple of things: setup a computed property (which you can also use in the template!): computed: { currentTrack() { return this.tracks[this.trackIndex] } } watch trackIndex: watch: { trackIndex(newTrackIndex, oldTrackIndex) { this.player.src = this.currentTrack.previewURL } } I hope these suggestions help! :)
{ "domain": "codereview.stackexchange", "id": 42666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, api, vue.js", "url": null }
swift Title: Concurrent Operation subclass combining KVO compliance and thread safety Question: This is a subclass of Operation that attempts to combine the requirements of KVO compliance and thread safety. Do I have the KVO notifications and thread safety done correctly? class ConcurrentOperation: Operation { private let stateQueue = DispatchQueue(label: "operation", attributes: .concurrent) private var _isExecuting = false private var _isFinished = false override var isExecuting: Bool { get { return stateQueue.sync { _isExecuting } } set { stateQueue.async(flags: .barrier) { self._isExecuting = newValue } } } override var isFinished: Bool { get { return stateQueue.sync { _isFinished } } set { stateQueue.async(flags: .barrier) { self._isFinished = newValue } } } override var isAsynchronous: Bool { return true } override func start() { if isCancelled { finish() return } print("starting...") willChangeValue(forKey: "isExecuting") isExecuting = true didChangeValue(forKey: "isExecuting") main() } override func main() { DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if self.isCancelled { print("cancelled") } else { print("done") } self.finish() } } func finish() { if isExecuting { willChangeValue(forKey: "isExecuting") isExecuting = false didChangeValue(forKey: "isExecuting") } if !isFinished { willChangeValue(forKey: "isFinished") isFinished = true didChangeValue(forKey: "isFinished") } } }
{ "domain": "codereview.stackexchange", "id": 42667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift", "url": null }
swift let op1 = ConcurrentOperation() let op2 = ConcurrentOperation() let opQueue = OperationQueue() opQueue.maxConcurrentOperationCount = 1 opQueue.addOperation(op1) opQueue.addOperation(op2) Answer: Yes, this looks fine re KVO and thread-safety. A few stylistic observations: I would personally move the willChangeValue and didChangeValue into the setters. It feels a little cluttered to have them sprinkled about the implementation. This pattern in your code snippet harkens back to the original Objective-C implementation, but Swift provides us opportunities to tidy up this code. I know you got your keynames right, but I always use #keyPath(isExecuting) and #keyPath(isFinished) to have the compiler enforce the string values. I would make both isExecuting and isFinished read-only properties (with private(set)) as no external code has any business changing these values. Personally, I would pull the main implementation out of ConcurrentOperation and put it into its own subclass. Once you have this ConcurrentOperation defined, you will find yourself using it everywhere you do not want to repeat all this boilerplate code in every concurrent operation subclass. Thus: class ConcurrentOperation: Operation { private let stateQueue = DispatchQueue(label: "operation", attributes: .concurrent) private var _isExecuting = false private var _isFinished = false override private(set) var isExecuting: Bool { get { stateQueue.sync { _isExecuting } } set { willChangeValue(forKey: #keyPath(isExecuting)) stateQueue.async(flags: .barrier) { self._isExecuting = newValue } didChangeValue(forKey: #keyPath(isExecuting)) } } override private(set) var isFinished: Bool { get { stateQueue.sync { _isFinished } }
{ "domain": "codereview.stackexchange", "id": 42667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift", "url": null }
swift set { willChangeValue(forKey: #keyPath(isFinished)) stateQueue.async(flags: .barrier) { self._isFinished = newValue } didChangeValue(forKey: #keyPath(isFinished)) } } override var isAsynchronous: Bool { return true } override func start() { if isCancelled { finish() return } isExecuting = true main() } override func main() { fatalError("This must be overridden") } func finish() { if isExecuting { isExecuting = false } if !isFinished { isFinished = true } } } And class TwoSecondOperation: ConcurrentOperation { override func main() { DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if self.isCancelled { print("cancelled") } else { print("done") } self.finish() } } } Going a step further, we generally strive for cancelable Operation subclasses, where possible. E.g., in this example, rather than using a closure with asyncAfter, we should instead used a DispatchWorkItem. Then we could make this operation truly cancelable (rather than having to wait two seconds before the cancelation is recognized). For example, perhaps something like the following: class TwoSecondOperationImproved: ConcurrentOperation { private var item: DispatchWorkItem? override init() { super.init() item = DispatchWorkItem { if self.isCancelled { print("cancelled") } else { print("done") } self.finish() } } override func main() { if let item = item { DispatchQueue.global().asyncAfter(deadline: .now() + 2, execute: item) } }
{ "domain": "codereview.stackexchange", "id": 42667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift", "url": null }
swift override func cancel() { super.cancel() item?.cancel() finish() } override func finish() { item = nil super.finish() } } In short, if the asynchronous task being wrapped in ConcurrentOperation offers cancelation, make sure to override cancel, too. If you prefer, you can also use locks to synchronize the properties of ConcurrentOperation: class ConcurrentOperation: Operation { private let lock = NSLock() private var _isExecuting = false private var _isFinished = false override private(set) var isExecuting: Bool { get { synchronized { _isExecuting } } set { willChangeValue(forKey: #keyPath(isExecuting)) synchronized { _isExecuting = newValue } didChangeValue(forKey: #keyPath(isExecuting)) } } override private(set) var isFinished: Bool { get { synchronized { _isFinished } } set { willChangeValue(forKey: #keyPath(isFinished)) synchronized { _isFinished = newValue } didChangeValue(forKey: #keyPath(isFinished)) } } override var isAsynchronous: Bool { return true } override func start() { if isCancelled { finish() return } isExecuting = true main() } override func main() { fatalError("This must be overridden") } func finish() { if isExecuting { isExecuting = false } if !isFinished { isFinished = true } } private func synchronized<T>(block: () throws -> T) rethrows -> T { try lock.synchronized { try block() } } } extension NSLocking { func synchronized<T>(block: () throws -> T) rethrows -> T { lock() defer { unlock() } return try block() } }
{ "domain": "codereview.stackexchange", "id": 42667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift", "url": null }
python, python-3.x, game, console, minesweeper Title: Mine sweeping game for the terminal Question: Over the holidays I was bored due to lockdown and implemented a mine sweeping game for the terminal. Any feedback is welcome. #! /usr/bin/env python3 """A mine sweeping game.""" from __future__ import annotations from argparse import ArgumentParser, Namespace from dataclasses import dataclass from enum import Enum from os import linesep from random import choice from string import digits, ascii_lowercase from sys import exit, stderr # pylint: disable=W0622 from typing import Iterator, NamedTuple, Optional __all__ = [ 'NUM_TO_STR', 'STR_TO_NUM', 'GameOver', 'SteppedOnMine', 'Cell', 'Coordinate', 'Minefield', 'ActionType', 'Action', 'print_minefield', 'read_action', 'get_args', 'visit', 'play_round', 'main' ] NUM_TO_STR = dict(enumerate(digits + ascii_lowercase)) STR_TO_NUM = {value: key for key, value in NUM_TO_STR.items()} class GameOver(Exception): """Indicates that the game has ended.""" def __init__(self, message: str, returncode: int): super().__init__(message) self.message = message self.returncode = returncode class SteppedOnMine(GameOver): """Indicates that the player stepped onto a mine.""" def __init__(self): super().__init__('You stepped onto a mine. :(', 1) @dataclass class Cell: """A cell of a minefield.""" mine: Optional[bool] = None marked: bool = False visited: bool = False def __str__(self) -> str: return self.to_string() def to_string(self, *, game_over: bool = False) -> str: """Returns a string representation.""" if self.visited: return '*' if self.mine else ' ' if self.marked: return ('!' if self.mine else 'x') if game_over else '?' if game_over and self.mine: return 'o' return ' ' if game_over else '■'
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper if game_over and self.mine: return 'o' return ' ' if game_over else '■' def toggle_marked(self) -> None: """Toggles the marker on this field.""" if self.visited: return self.marked = not self.marked class Coordinate(NamedTuple): """A 2D coordinate on a grid.""" x: int y: int def offset(self, delta_x: int, delta_y: int) -> Coordinate: """Returns a coordinate with the given offset.""" return type(self)(self.x + delta_x, self.y + delta_y) @property def neighbors(self) -> Iterator[Coordinate]: """Yield fields surrounding this position.""" for delta_y in range(-1, 2): for delta_x in range(-1, 2): if delta_x == delta_y == 0: continue # Skip the current position itself. yield self.offset(delta_x, delta_y) class Minefield(list): """A mine field.""" def __init__(self, width: int, height: int): super().__init__() self.width = width self.height = height for _ in range(height): self.append([Cell() for _ in range(width)]) def __str__(self) -> str: return self.to_string() @property def uninitialized(self) -> bool: """Checks whether all cells are uninitalized.""" return all(cell.mine is None for row in self for cell in row) @property def sweep_completed(self) -> bool: """Checks whether all cells have been visited.""" return all(cell.visited for row in self for cell in row if not cell.mine) def is_on_field(self, position: Coordinate) -> bool: """Determine whether the position is on the field.""" return 0 <= position.x < self.width and 0 <= position.y < self.height def cell_at(self, position: Coordinate) -> Cell: """Returns the cell at the given position.""" return self[position.y][position.x]
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper def get_neighbors(self, position: Coordinate) -> Iterator[Cell]: """Yield cells surrounding the given position.""" for neighbor in position.neighbors: if self.is_on_field(neighbor): yield self.cell_at(neighbor) def count_surrounding_mines(self, position: Coordinate) -> int: """Return the amount of mines surrounding the given position.""" return sum(cell.mine for cell in self.get_neighbors(position)) def stringify(self, cell: Cell, position: Coordinate, *, game_over: bool = False) -> str: """Return a str representation of the cell at the given coordiate.""" if not cell.mine and (cell.visited or game_over): if mines := self.count_surrounding_mines(position): return str(mines) return str(cell.to_string(game_over=game_over)) def disable_mine(self, position: Coordinate) -> None: """Set the cell at the given position to not have a mine.""" self.cell_at(position).mine = False def populate(self, mines: int) -> None: """Populate the minefield with mines.""" cells = [cell for row in self for cell in row if cell.mine is None] if mines > len(cells): raise ValueError('Too many mines for field.') for _ in range(mines): cell = choice(cells) cell.mine = True cells.remove(cell) for cell in cells: cell.mine = False def toggle_marked(self, position: Coordinate) -> None: """Toggels the marker on the given cell.""" self.cell_at(position).toggle_marked() def visit(self, position: Coordinate) -> None: """Visit the cell at the given position.""" if not self.is_on_field(position): return if (cell := self.cell_at(position)).visited: return if cell.marked: return cell.visited = True
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper if cell.marked: return cell.visited = True if cell.mine: raise SteppedOnMine() if self.count_surrounding_mines(position) == 0: for neighbor in position.neighbors: self.visit(neighbor) def to_string(self, *, game_over: bool = False) -> str: """Returns a string representation of the minefield.""" return linesep.join( ' '.join( self.stringify(cell, Coordinate(x, y), game_over=game_over) for x, cell in enumerate(row) ) for y, row in enumerate(self) ) class ActionType(Enum): """Game actions.""" VISIT = 'visit' MARK = 'mark' class Action(NamedTuple): """An action on a coordinate.""" action: ActionType position: Coordinate def print_minefield(minefield: Minefield, *, game_over: bool = False) -> None: """Prints the mine field with row and column markers.""" print(' |', *(f'{NUM_TO_STR[index]} ' for index in range(minefield.width)), sep='') print('-+', '-' * (minefield.width * 2 - 1), sep='') lines = minefield.to_string(game_over=game_over).split(linesep) for index, line in enumerate(lines): print(f'{NUM_TO_STR[index]}|', line, sep='') def read_action(minefield: Minefield, *, prompt: str = 'Enter action and coordinate: ' ) -> Action: """Reads an Action.""" try: text = input(prompt) except EOFError: print() return read_action(minefield, prompt=prompt) try: action, pos_x, pos_y = text.split() action = ActionType(action) except ValueError: print('Please enter: (visit|mark) <x> <y>', file=stderr) return read_action(minefield, prompt=prompt)
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper try: position = Coordinate(STR_TO_NUM[pos_x], STR_TO_NUM[pos_y]) except KeyError: print('Invalid coordinates.', file=stderr) return read_action(minefield, prompt=prompt) if minefield.is_on_field(position): return Action(action, position) print('Coordinate must lie on the minefield.', file=stderr) return read_action(minefield, prompt=prompt) def get_args(description: str = __doc__) -> Namespace: """Parses the command line arguments.""" parser = ArgumentParser(description=description) parser.add_argument('--width', type=int, metavar='x', default=8) parser.add_argument('--height', type=int, metavar='y', default=8) parser.add_argument('--mines', type=int, metavar='n', default=10) return parser.parse_args() def visit(minefield: Minefield, position: Coordinate) -> None: """Visit a field.""" minefield.visit(position) if minefield.sweep_completed: raise GameOver('All mines cleared. Great job.', 0) def play_round(minefield: Minefield, mines: int) -> None: """Play a round.""" print_minefield(minefield) action = read_action(minefield) if action.action == ActionType.VISIT: if minefield.uninitialized: minefield.disable_mine(action.position) minefield.populate(mines) return visit(minefield, action.position) return minefield.toggle_marked(action.position) def main() -> int: """Test stuff.""" args = get_args() if args.width > (maxsize := len(NUM_TO_STR)) or args.height > maxsize: print(f'Max field width and height are {maxsize}.', file=stderr) return 2 if args.mines >= (args.width * args.height): print('Too many mines for field.', file=stderr) return 2 minefield = Minefield(args.width, args.height)
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper minefield = Minefield(args.width, args.height) while True: try: play_round(minefield, args.mines) except KeyboardInterrupt: print('\nAborted by user.') return 3 except GameOver as game_over: print_minefield(minefield, game_over=True) print(game_over.message) return game_over.returncode if __name__ == '__main__': exit(main()) Answer: Your code is thoughtful and well organized. The user interface is needlessly burdensome. By far, the most common action is visiting. Don't make the user type "visit" every time. Similarly, users would appreciate the ability to abbreviate the action. With a couple lines of code you could easily support inputs like the following: visit 1 4 # Explicit is fine, for purists and over-achievers. mark 3 2 v 1 4 # For the rest of us. m 3 2 1 4 # Super users know the default action is visit.
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper Import readline, if you can. A commenter noted this, and I'm endorsing it here. At least on supported operating systems, your input-providing user will get a bunch of nice conveniences for free. Define constants for exit codes. This is just a routine suggestion to get rid of any lingering magic strings/numbers. I only noticed the exit codes, but you should give the whole program a quick once-over with this topic in mind. Coordinate.offset() seems unnecessary. It is used in only one spot, the property that yields neighboring Coordinate instances. I would just yield the instances directly. Minefield dubiously inherits from list. Conceptually, the inheritance seems strained: in what sense is it helpful to say a Minefield is a list, as opposed to just having a grid or a list or rows? More pragmatically, the inheritance seems to provide few concrete benefits: perhaps I overlooked a detail, but the only way I noticed you using the inheritance was to iterate over the rows in the minefield. If you want to be fancy, you could implement Minefield.__iter__(). Or you could just do the regular thing in the few spots it's needed: for row in self.grid. The read_action() function is overly complex and awkward to test. Collecting and validating user input is always a bit of a hassle. Why? Because functions that call input() and/or print require some hoop-jumping to test in an automated fashion. To those unavoidable difficulties you've added a recursive implementation -- which "works" but at the cost of an additional mental burden on your reader merely to avoid a simple while-true loop. My advice is that you do three things: (1) segregate the input() call to the simplest possible function (so simple that it's hardly worth testing); (2) extract as much of the algorithmic detail to an easily-tested, data-oriented function; and (3) leave the surviving remainder in read_action(). The main point is to push complexity out of the functions that are bothersome to test. Here's a sketch:
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper complexity out of the functions that are bothersome to test. Here's a sketch: def read_action(minefield: Minefield) -> Action: # This isn't algorithm-free, but it's close. prompt = 'Please enter: (visit|mark) <x> <y> ' while True: text = get_input(prompt) result = parse_action(minefield, text) if isinstance(result, Action): return result else: print(result, file=stderr)
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper def get_input(prompt: str) -> str: # Input-collection: so simple that the need for testing almost nil. try: return input(prompt) except EOFError: return '' def parse_action(minefield: Minefield, text: str) -> Union(Action, str): # Push the algorithm here, where testing is simple. try: action, pos_x, pos_y = text.split() action = ActionType(action) except ValueError: return 'Invalid input.' try: position = Coordinate(STR_TO_NUM[pos_x], STR_TO_NUM[pos_y]) except KeyError: return 'Invalid coordinates.' if minefield.is_on_field(position): return Action(action, position) else: return 'Coordinate must lie on the minefield.' The play_round() function knows too much about Minefield. If the action is a visit, the function knows to check whether the Minefield is in an uninitialized state, in which case certain preparatory operations are required. That's an example of class implementation details leaking out into the rest of the program. If certain steps are required before the first visit can occur, let Minefield handle them. A separate issue is that the function is implemented as though its return value matters, but it does not. Something along the following lines seems better. Notice also that these suggested edits are pushing the code in the same direction as some of the prior comments: simplifying functions that must deal with IO, and moving algorithmic complexity into pure data-oriented functions or into data-managing methods of a class. def play_round(minefield: Minefield, mines: int) -> None: print_minefield(minefield) action = read_action(minefield) if action.action == ActionType.VISIT: minefield.visit(position) if minefield.sweep_completed: raise GameOver('All mines cleared. Great job.', 0) else: minefield.toggle_marked(action.position)
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, python-3.x, game, console, minesweeper Minefield and Cell as strings. Why does print_minefield() exist rather than simply putting all of that logic in Minefield.to_string()? A stringified Minefield without the row/column numbers seems of questionable value, so I would combine everything. Relatedly, unless you can articulate a solid reason to yourself for the to_string() aliases, do that kind of work directly in the __str__() methods of Minefield and Cell.
{ "domain": "codereview.stackexchange", "id": 42668, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, console, minesweeper", "url": null }
python, rust, bioinformatics Title: Rust program to one hot encode genetic sequences from .fa files Question: I wanted to write some code which reads in a FASTA file and one hot encodes the sequence which is consequentially saved to a file. A FASTA file is a text based file format commonly used in bioinformatics. Here's an example: >chr1 ACGTCTCGTGC NNNNNNNNNNN ACGTTGGGGGG >chr2 AGGGTCTGGGT NNNNNNNNNNN It has a header string with > and then some genetic sequence following. Every character in that sequence represents a nucleotide. For example "A" stands for Adenine and "N" for unknown. The number of possible characters in the sequence is limited, but there are some encodings allowing different representations. But this is not that important for me, since I will probably filter beforehand anyway. The output should be a text file with the one hot encoded sequence and the header for identification. Depending on how one would choose the encoding this could look something like this for the first three nucleotides(ACG): >chr1 0,0,0,1 0,1,0,0 0,0,1,0 I wrote some Rust code together to achieve this and it works, but it seems to be pretty slow. Maybe I should also mention at this point that the FASTA files can get really big (many GB) in no time. I tried my code (cargo build --release) with an ~60MB .fa file and took about ~1m.30s and some generic Python code I wrote together in 10 minutes took only ~40s. Now I wanted to know why my Rust Code is slower then it's Python equivalent. Did I write it inn an idiomatic Rust way? I do not want to store the data in something like HDF5. I just want to understand Rust better. Especially I/O heavy text processing tasks, since these are common in bioinformatics. Here's the code I wrote: use std::fs::File; use std::io::{BufReader, Write}; use std::io::prelude::*; use std::env; use std::fs::OpenOptions; fn main() -> std::io::Result<()>{
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics fn main() -> std::io::Result<()>{ // gather cmd arguments let args: Vec<String> = env::args().collect(); let filename: &String = &args[1]; let outfile: &String = &args[2]; // Open the file to read from let file = File::open(&filename).unwrap(); // Create a buffered reader -> instead of reading everything to ram let reader = BufReader::new(file); let lines = reader.lines(); // this allows to open a file in file append mode to write (or create it) let mut to_write_file = OpenOptions::new() .append(true) .create(true) // Optionally create .open(outfile) .expect("Unable to open file"); // iterate over every line for l in lines { // check if we get a string back (Result<String, Error>) if let Ok(line_string) = l { // check for header lines if line_string.contains("chr"){ println!("Processing: {}",line_string); // write to file so we can keep track of chroms writeln!(to_write_file, "{}",line_string).unwrap(); } else { // iterate over nucleotides for character in line_string.chars() { // one hot encode the nucleotide let nucleotide: String = one_hot_encode_string(String::from(character)); writeln!(to_write_file,"{}", nucleotide)?; } } } } Ok(()) } fn one_hot_encode_string(nucleotide: String) -> String { // One hot encodes a Nucleotide: String let encoding: String; // create return variable
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics let encoding: String; // create return variable // OHE the nucleotide match nucleotide.as_str() { "A" => encoding = String::from("0,0,0,1"), "G" => encoding = String::from("0,0,1,0"), "C" => encoding = String::from("0,1,0,0"), "T" => encoding = String::from("1,0,0,0"), "N" => encoding = String::from("0,0,0,0"), _ => encoding = String::from("NA"), } encoding } Her's also the "naive" python code: import sys # one hot encode nulceotide def ohe(nucleotide: str) -> str: if nucleotide == "A": return("0,0,0,1") if nucleotide == "G": return("0,0,1,0") if nucleotide == "T": return("0,1,0,0") if nucleotide == "C": return("1,0,0,0") if nucleotide == "N": return("0,0,0,0") else: return("NA") def main() -> None: # get arguments input: str = sys.argv[1] output: str = sys.argv[2] # open in file with open(input) as in_f: # open out file with open(output, 'a') as out_f: for line in in_f: # get header if line.startswith(">"): out_f.write(f"{line.rstrip()}\n") else: # iterate over every nucleotide for character in line.rstrip(): # one hot encode character # print(ohe(character)) out_f.write(f"{ohe(character)}\n") if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics if __name__ == "__main__": main() Answer: Your programs aren't quite equivalent; one looks at whether a line starts with >, the other looks for chr in each line. That doesn't make much of a difference in the big picture, but the play area should be level, shouldn't it? Secondly, as I mentioned over on SO, you should probably avoid String::from calls wherever possible. Since those one-hot encodings are constant, you can just return a &'static str. Thirdly, and this is the thing that really makes all the difference, your Python program is implicitly using buffered writes instead of directly writing to the output file every time. Wrapping to_write_file in a BufReader::new makes quite the difference, see below. u60.fasta is an arbitrary 60 megabyte FASTA file. original (original) $ time cargo run --release -- u60.fasta /dev/null Compiling cr272415 v0.1.0 (/Users/akx/build/cr272415) Finished release [optimized] target(s) in 0.35s Running `target/release/cr272415 u60.fasta /dev/null` Processing: >NC_000001.11 Homo sapiens chromosome 1, GRCh38.p13 Primary Assembly ________________________________________________________ Executed in 6.66 secs fish external usr time 4.74 secs 113.00 micros 4.74 secs sys time 2.44 secs 799.00 micros 2.44 secs optimized ~/b/cr272415 (master) $ time cargo run --release -- u60.fasta /dev/null Compiling cr272415 v0.1.0 (/Users/akx/build/cr272415) Finished release [optimized] target(s) in 0.38s Running `target/release/cr272415 u60.fasta /dev/null` Processing: >NC_000001.11 Homo sapiens chromosome 1, GRCh38.p13 Primary Assembly ________________________________________________________ Executed in 650.30 millis fish external usr time 1.21 secs 147.00 micros 1.21 secs sys time 0.17 secs 939.00 micros 0.16 secs
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics I'm not an experienced Rustacean, so someone can probably improve on this, but the optimized version is below. Some of the changes were suggested by cargo clippy (which you should also heed :-) ). use std::env; use std::fs::File; use std::fs::OpenOptions; use std::io::{BufRead, BufReader, BufWriter, Write}; fn main() -> std::io::Result<()> { // gather cmd arguments let args: Vec<String> = env::args().collect(); let filename: &String = &args[1]; let outfile: &String = &args[2]; // Open the file to read from let file = File::open(&filename).unwrap(); // Create a buffered reader -> instead of reading everything to ram let reader = BufReader::new(file); let lines = reader.lines(); // this allows to open a file in file append mode to write (or create it) let mut to_write_file = BufWriter::new( OpenOptions::new() .append(true) .create(true) // Optionally create .open(outfile) .expect("Unable to open file"), ); // iterate over every line for line_string in lines.flatten() { // check for header lines if line_string.starts_with('>') { println!("Processing: {}", line_string); // write to file so we can keep track of chroms writeln!(to_write_file, "{}", line_string).unwrap(); } else { // iterate over nucleotides for character in line_string.chars() { // one hot encode the nucleotide let nucleotide = one_hot_encode_string(character); writeln!(to_write_file, "{}", nucleotide)?; } } } Ok(()) } fn one_hot_encode_string(nucleotide: char) -> &'static str { // One hot encodes a Nucleotide character match nucleotide { 'A' => "0,0,0,1", 'G' => "0,0,1,0", 'C' => "0,1,0,0", 'T' => "1,0,0,0", 'N' => "0,0,0,0", _ => "NA", } }
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics Edit ⚡️ Some background thread in my brain realized one more way to make this faster still: don't use writeln!. There's no need to spend time parsing format strings and allocating memory just to add a newline. If you precompose the \n into the output, you can just use BufWriter.write_all() – i.e. change the end of the program above to let nucleotide = one_hot_encode_string(character); to_write_file.write_all(nucleotide.as_ref())?; } } } Ok(()) } fn one_hot_encode_string(nucleotide: char) -> &'static str { // One hot encodes a Nucleotide character match nucleotide { 'A' => "0,0,0,1\n", 'G' => "0,0,1,0\n", 'C' => "0,1,0,0\n", 'T' => "1,0,0,0\n", 'N' => "0,0,0,0\n", _ => "NA\n", } } A benchmark run with hyperfine speaks more than a thousand words, as they say: ~/b/cr272415 (master) $ hyperfine --warmup 3 './original/release/cr272415 u60.fasta /dev/null' './opt1/release/cr272415 u60.fasta /dev/null' './opt2/release/cr272415 u60.fasta /dev/null' Benchmark 1: ./original/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 6.401 s ± 0.441 s [User: 4.004 s, System: 2.385 s] Range (min … max): 5.978 s … 7.292 s 10 runs Benchmark 2: ./opt1/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 170.8 ms ± 4.2 ms [User: 167.0 ms, System: 2.8 ms] Range (min … max): 164.5 ms … 178.4 ms 17 runs Benchmark 3: ./opt2/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 59.2 ms ± 2.0 ms [User: 55.8 ms, System: 2.5 ms] Range (min … max): 56.5 ms … 65.6 ms 45 runs Summary './opt2/release/cr272415 u60.fasta /dev/null' ran 2.89 ± 0.12 times faster than './opt1/release/cr272415 u60.fasta /dev/null' 108.21 ± 8.29 times faster than './original/release/cr272415 u60.fasta /dev/null'
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
python, rust, bioinformatics Edit ⚡️ x 2 One more thing I realized (though this could turn out to be CPU cache-inefficient in a larger program): inline the whole darned write call, and mark the constants as bytestrings to avoid .as_ref() altogether. Hyperfine says this is 1.32 ± 0.11 times faster than opt2 (the above edit). macro_rules! wf { ($s:expr) => { to_write_file.write_all($s) }; } for character in line_string.chars() { match character { 'A' => wf!(b"0,0,0,1\n"), 'G' => wf!(b"0,0,1,0\n"), 'C' => wf!(b"0,1,0,0\n"), 'T' => wf!(b"1,0,0,0\n"), 'N' => wf!(b"0,0,0,0\n"), _ => wf!(b"NA\n"), } .unwrap(); } ~/b/cr272415 (vecw *) $ ./bench.sh Benchmark 1: ./targets/original/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 6.294 s ± 0.182 s [User: 3.942 s, System: 2.340 s] Range (min … max): 6.060 s … 6.592 s 10 runs Benchmark 2: ./targets/opt1/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 176.7 ms ± 6.9 ms [User: 172.1 ms, System: 3.2 ms] Range (min … max): 166.1 ms … 188.5 ms 16 runs Benchmark 3: ./targets/opt2/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 61.5 ms ± 2.9 ms [User: 57.8 ms, System: 2.6 ms] Range (min … max): 58.4 ms … 73.8 ms 43 runs Benchmark 4: ./targets/vecw/release/cr272415 u60.fasta /dev/null Time (mean ± σ): 46.0 ms ± 2.9 ms [User: 42.6 ms, System: 2.5 ms] Range (min … max): 42.2 ms … 55.7 ms 60 runs Summary './targets/vecw/release/cr272415 u60.fasta /dev/null' ran 1.33 ± 0.11 times faster than './targets/opt2/release/cr272415 u60.fasta /dev/null' 3.84 ± 0.29 times faster than './targets/opt1/release/cr272415 u60.fasta /dev/null' 136.71 ± 9.55 times faster than './targets/original/release/cr272415 u60.fasta /dev/null'
{ "domain": "codereview.stackexchange", "id": 42669, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, rust, bioinformatics", "url": null }
java, design-patterns, spring Title: Using Factory Design Pattern in Spring Question: I organized the factory design pattern but I'm not sure if I used it right or wrong. Here's my data model; @Data @AllArgsConstructor @NoArgsConstructor abstract public class Ga implements Serializable { private static final long serialVersionUID = -1977929156280284414L; private String id; private GaStaEnum gaStaEnum; private PlaTuEnum plaTuEnum; private BoaSiEnum boaSiEnum; } @Data @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class XGa extends Ga { private static final long serialVersionUID = 3116827666531342601L; private Pla pla1; private Pla pla2; private int index; ..... And my factory pattern is like this; public class GaFactory { public static Ga createGa(GaType type) { Ga ga = null; if (X.equals(type)) { ga = new XGa(); } return ga; } } I called the factory like this; public XGaDTO init() { Ga xGa = GaFactory.createGa(X); repository.save((XGa) xGa); return mapper.toDTO((XGa) xGa); } Did I use it right? Or maybe I should add something more? Thanks for advices.
{ "domain": "codereview.stackexchange", "id": 42670, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, design-patterns, spring", "url": null }
java, design-patterns, spring Answer: TL;DR If you can't fully delegate the subclass decision to the factory and then live with whatever class it chose, then either re-factor the code to make that possible, or forget about the factory. And have the factory produce usable instances, not empty ones. I see two (related) flaws in your code. (Disclaimer: maybe the code you showed us is a stripped-down version of the real application, then maybe some of my remarks don't apply.) Uninitialized instances Your createGa() method in the GaFactory class creates a non-initialized Ga instance, one where all fields are left blank. In my understanding, a factory is meant to create usable instances, and I guess that fields like id have to be filled before a Ga instance gets meaningful. [If you order a car from a real-world factory, and you get one without engine or paint, you'd sue the factory.] Polymorphism flaw My understanding of the factory pattern is that the factory creates an instance that fulfills the caller's needs. In your case, I don't see how this could ever work the way it is intended. In init(), you have to cast the Ga instance coming from the factory to an XGa. If the repository.save() and mapper.toDTO() really need the cast, then using the factory instead of directly calling new XGa() leads to more obscure code, and to code where errors will be found not at compile-time, but at run-time. No compiler will know that GaFactory.createGa(X) creates an XGa, and not eg. a MyGa, so a small typo can easily create a ClassCastException at runtime, hopefully detected by an automated test, and not in production.
{ "domain": "codereview.stackexchange", "id": 42670, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, design-patterns, spring", "url": null }
java, design-patterns, spring If you use a factory the way you do, make sure that only code "inside the factory" has to know about the existence of subclasses like XGa or MyGa. Everything outside the factory should accept any Ga subclass. This not only applies to places like repository.save() and mapper.toDTO(), but also to the initialization phase. I guess that in your code, the only way to initialize pla1, pla2, and index, is to use a setter in the XGa subclass, again needing a cast.
{ "domain": "codereview.stackexchange", "id": 42670, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, design-patterns, spring", "url": null }
array, typescript, angular-2+ Title: Angular and Typescript page with for loop and array Question: I have a page that shows the result of a quiz and depends on the number of right answer, the user get some rewards. So, if the user get just one right answer, he will get one reward, the others will be blurred. If the user get two right answers, he will get two rewards, the others will be blurred, and so on. The total of questions is 5 and the total of rewards is 5 too. HTML <div id="container"><span>Você acertou </span><span style="color: black; text-align: center;">{{quizResult}}</span> <span id="spotlight"> pergunta(s). Agora é só aproveitar a(s) recompensa(s)!</span> </div> <span class="image"><img src="./assets/images/ticket1.png" alt="Muito abracos" id="recompensa1" [class.blur]="isBlur[0]" /></span> <span class="image"><img src="./assets/images/ticket2.png" alt="Beijo Calhiente" id="recompensa2" [class.blur]="isBlur[1]" /></span> <span class="image"><img src="./assets/images/ticket3.png" alt="Massagem" id="recompensa3" [class.blur]="isBlur[2]" /></span> <span class="image"><img src="./assets/images/ticket4.png" alt="Cafe na cama" id="recompensa4" [class.blur]="isBlur[3]" /></span> <span class="image"><img src="./assets/images/ticket5.png" alt="Jantar Romantico" id="recompensa5" [class.blur]="isBlur[4]" /></span> TYPESCRIPT import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-result', templateUrl: './result.component.html', styleUrls: ['./result.component.css'] }) export class ResultComponent implements OnInit { quizResult: number; isBlur: boolean[]; constructor() { this.quizResult = 0; this.isBlur = [] } ngOnInit(): void { this.quizResult = parseInt(localStorage.getItem("numCorrect") ?? "0", this.quizResult); const numberOfImages = document.querySelectorAll('app-result > .image').length; for (let i = 0; i < numberOfImages; i++) { this.isBlur[i] = this.quizResult < i + 1;
{ "domain": "codereview.stackexchange", "id": 42671, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, typescript, angular-2+", "url": null }
array, typescript, angular-2+ } } } CSS .blur{ filter: blur(5px); -webkit-filter: blur(5px); } Answer: First HTML formatting is unreadable. Might be because of SO, but it would probably be more readable if an element was split into multiple lines. <div id="container"> <span>Você acertou </span> <span style="color: black; text-align: center;">{{quizResult}}</span> <span id="spotlight"> pergunta(s). Agora é só aproveitar a(s) recompensa(s)!</span> </div> <span class="image"> <img src="./assets/images/ticket1.png" alt="Muito abracos" id="recompensa1" [class.blur]="isBlur[0]" /> </span> <span class="image"> <img src="./assets/images/ticket2.png" alt="Beijo Calhiente" id="recompensa2" [class.blur]="isBlur[1]" /> </span> <span class="image"> <img src="./assets/images/ticket3.png" alt="Massagem" id="recompensa3" [class.blur]="isBlur[2]" /> </span> <span class="image"> <img src="./assets/images/ticket4.png" alt="Cafe na cama" id="recompensa4" [class.blur]="isBlur[3]" /> </span> <span class="image"> <img src="./assets/images/ticket5.png" alt="Jantar Romantico" id="recompensa5" [class.blur]="isBlur[4]" /> </span> Second, there is some fishy stuff going on in your component code. export class ResultComponent implements OnInit { quizResult: number; isBlur: boolean[]; constructor() { this.quizResult = 0; this.isBlur = [] } ngOnInit(): void { this.quizResult = parseInt(localStorage.getItem("numCorrect") ?? "0", this.quizResult); // why not parseInt(string, 10)? const numberOfImages = document.querySelectorAll('app-result > .image').length; // Why are you selecting images from the DOM? you know it is 5 of them. // the length of isBlur is 0. for (let i = 0; i < numberOfImages; i++) { this.isBlur[i] = this.quizResult < i + 1; } } }
{ "domain": "codereview.stackexchange", "id": 42671, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, typescript, angular-2+", "url": null }
array, typescript, angular-2+ With that in mind you can refactor the code in the following way: export class ResultComponent implements OnInit { quizResult: number; isBlur: boolean[] = []; ngOnInit(): void { this.quizResult = parseInt(localStorage.getItem("numCorrect") ?? "0", 10) for (let i = 0; i < 5; i++) { this.isBlur[i] = this.quizResult < i + 1; } } } But you can notice, that there is a lot of duplication in HTML part. You can move this to TS code. <div id="container"> <span>Você acertou </span> <span style="color: black; text-align: center;">{{quizResult}}</span> <span id="spotlight"> pergunta(s). Agora é só aproveitar a(s) recompensa(s)!</span> </div> <span class="image" *ngFor="let question of questions"> <img [src]="question.image" [alt]="question.alt" [id]="question.id" [class.blur]="question.incorrect" /> </span> export class ResultComponent implements OnInit { quizResult: number; questions = [ { image: './assets/images/ticket1.png', alt: 'Muito abracos', id: 'recompensa1', }, ... ]; ngOnInit(): void { this.quizResult = parseInt(localStorage.getItem("numCorrect") ?? "0", 10) for (let i = 0; i < this.questions.length; i++) { this.questions[i].incorrect = this.quizResult < i + 1; } } } This now opens you to the possibility of having questions loaded from somewhere else and you are not tied to the DOM anymore for the number of questions.
{ "domain": "codereview.stackexchange", "id": 42671, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, typescript, angular-2+", "url": null }
c++ Title: A word translator into multiple languages Question: My problem is with code about translating a single word into 5 languages My code: #include <iostream> #include <map> int dict_number; static const int dict_length = 10; struct Dictionary { std::map<int, std::string> dictionary_no{ {1, "Eple"}, {2, "Banan"}, {3, "Hjem"}, {4, "Hallo"}, {5, "Kafe" }, {6, "Brød"}, {7, "Melk"}, {8, "Hamster"}, {9, "Katt"}, {10, "Hund"} }; std::map<int, std::string> dictionary_en = { {1, "Apple"}, {2, "Banana"}, {3, "Home"}, {4, "Hello"}, {5, "Cafe" }, {6, "Bread"}, {7, "Milk"}, {8, "Hamster"}, {9, "Cat"}, {10, "Dog"} }; std::map<int, std::string> dictionary_pl = { {1, "Jabłko"}, {2, "Banan"}, {3, "Dom"}, {4, "Cześć"}, {5, "Kawa" }, {6, "Chleb"}, {7, "Mleko"}, {8, "Chomik"}, {9, "Kot"}, {10, "Pies"} }; std::map<int, std::string> dictionary_de = { {1, "Apfel"}, {2, "Banane"}, {3, "Haus"}, {4, "Hallo"}, {5, "Kaffee" }, {6, "Brot"}, {7, "Milch"}, {8, "Hamster"}, {9, "Katze"}, {10, "Hund"} }; std::map<int, std::string> dictionary_ua = { {1, "Яблуко"}, {2, "Банан"}, {3, "Дім"}, {4, "Привіт"}, {5, "Кафе" }, {6, "Хліб"}, {7, "Молоко"}, {8, "Хом’як"}, {9, "Кіт"}, {10, "Пес"} }; std::map<int, std::string> dictionary_cn = { {1, "蘋果"}, {2, "香蕉"}, {3, "房子"}, {4, "你好"}, {5, "咖啡"}, {6, "麵包"}, {7, "牛奶"}, {8, "倉鼠"}, {9, "貓"}, {10, "狗"} }; }; Dictionary dictionary; enum Translation { polish, ukrainian, german, english, norwegian, chinese };
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ void translateWord(Translation translation, Translation translateTo, std::string word) { switch (translation) { case english: for (int search = 0; search < dictionary.dictionary_en.size(); search++) { if (dictionary.dictionary_en[search] == word) { dict_number = search; switch (translateTo) { case german: std::cout << dictionary.dictionary_de[dict_number] << std::endl; break; case norwegian: std::cout << dictionary.dictionary_no[dict_number] << std::endl; break; case polish: std::cout << dictionary.dictionary_pl[dict_number] << std::endl; break; case ukrainian: std::cout << dictionary.dictionary_ua[dict_number] << std::endl; break; case chinese: std::cout << dictionary.dictionary_cn[dict_number] << std::endl; break; } } } break; case german: for (int search = 0; search < dictionary.dictionary_de.size(); search++) { if (dictionary.dictionary_de[search] == word) { dict_number = search; switch (translateTo) { case english: std::cout << dictionary.dictionary_en[dict_number] << std::endl; break; case norwegian: std::cout << dictionary.dictionary_no[dict_number] << std::endl; break; case polish: std::cout << dictionary.dictionary_pl[dict_number] << std::endl; break; case ukrainian: std::cout << dictionary.dictionary_ua[dict_number] << std::endl; break; case chinese:
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ break; case chinese: std::cout << dictionary.dictionary_cn[dict_number] << std::endl; break; } } } break; case norwegian: for (int search = 0; search < dictionary.dictionary_no.size(); search++) { if (dictionary.dictionary_no[search] == word) { dict_number = search; switch (translateTo) { case german: std::cout << dictionary.dictionary_de[dict_number] << std::endl; break; case english: std::cout << dictionary.dictionary_en[dict_number] << std::endl; break; case polish: std::cout << dictionary.dictionary_pl[dict_number] << std::endl; break; case ukrainian: std::cout << dictionary.dictionary_ua[dict_number] << std::endl; break; case chinese: std::cout << dictionary.dictionary_cn[dict_number] << std::endl; break; } } } break; case polish: for (int search = 0; search < dictionary.dictionary_pl.size(); search++) { if (dictionary.dictionary_pl[search] == word) { dict_number = search; switch (translateTo) { case german: std::cout << dictionary.dictionary_de[dict_number] << std::endl; break; case norwegian: std::cout << dictionary.dictionary_no[dict_number] << std::endl; break; case english: std::cout << dictionary.dictionary_en[dict_number] << std::endl; break; case ukrainian:
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ break; case ukrainian: std::cout << dictionary.dictionary_ua[dict_number] << std::endl; break; case chinese: std::cout << dictionary.dictionary_cn[dict_number] << std::endl; break; } } } break; case ukrainian: for (int search = 0; search < dictionary.dictionary_ua.size(); search++) { if (dictionary.dictionary_ua[search] == word) { dict_number = search; switch (translateTo) { case german: std::cout << dictionary.dictionary_de[dict_number] << std::endl; break; case norwegian: std::cout << dictionary.dictionary_no[dict_number] << std::endl; break; case polish: std::cout << dictionary.dictionary_pl[dict_number] << std::endl; break; case english: std::cout << dictionary.dictionary_en[dict_number] << std::endl; break; case chinese: std::cout << dictionary.dictionary_cn[dict_number] << std::endl; break; } } } break; case chinese: for (int search = 0; search < dictionary.dictionary_cn.size(); search++) { if (dictionary.dictionary_cn[search] == word) { dict_number = search; switch (translateTo) { case english: std::cout << dictionary.dictionary_en[dict_number] << std::endl; break; case german: std::cout << dictionary.dictionary_de[dict_number] << std::endl; break; case norwegian:
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ break; case norwegian: std::cout << dictionary.dictionary_no[dict_number] << std::endl; break; case polish: std::cout << dictionary.dictionary_pl[dict_number] << std::endl; break; case ukrainian: std::cout << dictionary.dictionary_ua[dict_number] << std::endl; break; } } } break; } }
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ int main() { translateWord(english, polish, "Hello"); return 0; } Can this code be improved or shortened? Big thanks for help! Answer: Your usage of std::map is wrong here, you don't look-up by index. std::map could be used to select correct words container by language though. Keeping one container by language, you might have: #include <algorithm> #include <iostream> #include <array> enum class Language { polish, ukrainian, german, english, norwegian, chinese }; static const int dict_length = 10; // Possibly std::map<Language, std::array<std::string, dict_length>> // instead of named dictionaries. const std::array<std::string, dict_length> dictionary_no{ "Eple", "Banan", "Hjem", "Hallo", "Kafe", "Brød", "Melk", "Hamster", "Katt", "Hund" }; const std::array<std::string, dict_length> dictionary_en = { "Apple", "Banana", "Home", "Hello", "Cafe" , "Bread", "Milk", "Hamster", "Cat", "Dog" }; const std::array<std::string, dict_length> dictionary_pl = { "Jabłko", "Banan", "Dom", "Cześć", "Kawa", "Chleb", "Mleko", "Chomik", "Kot", "Pies" }; const std::array<std::string, dict_length> dictionary_de = { "Apfel", "Banane", "Haus", "Hallo", "Kaffee", "Brot", "Milch", "Hamster", "Katze", "Hund" }; const std::array<std::string, dict_length> dictionary_ua = { "Яблуко", "Банан", "Дім", "Привіт", "Кафе", "Хліб", "Молоко", "Хом’як", "Кіт", "Пес" }; const std::array<std::string, dict_length> dictionary_cn = { "蘋果", "香蕉", "房子", "你好", "咖啡", "麵包", "牛奶", "倉鼠", "貓", "狗" };
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ const std::array<std::string, dict_length>& get_dictionary(Language language) { switch (language) { case Language::polish: return dictionary_pl; case Language::ukrainian: return dictionary_ua; case Language::german: return dictionary_de; case Language::english: return dictionary_en; case Language::norwegian: return dictionary_no; case Language::chinese: return dictionary_cn; } throw std::runtime_error("Unknown dictionary"); } void translateWord(Language from, Language to, std::string word) { const auto& dict_from = get_dictionary(from); const auto& dict_to = get_dictionary(to); auto it = std::find(dict_from.begin(), dict_from.end(), word); if (it != dict_from.end()) { std::cout << dict_to[std::distance(dict_from.begin(), it)] << std::endl; } } int main() { translateWord(Language::english, Language::polish, "Hello"); return 0; } Demo but the fact that order of word should be identical is error prone IMO. having a struct struct translated_word { std::string polish; std::string ukrainian; std::string german; std::string english; std::string norwegian; std::string chinese; }; seems a grouping less error prone.
{ "domain": "codereview.stackexchange", "id": 42672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
javascript, express.js Title: Express.js and jsonplaceholder application Question: I have put together a small node application with Express.js and jsonplaceholder. On the homepage, it displays posts by all users. You can also filter posts by one user (author). In app.js I have: var createError = require('http-errors'); var express = require('express'); var axios = require('axios'); var path = require('path'); var cookieParser = require('cookie-parser'); var expressLayouts = require('express-ejs-layouts'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); global.base_url = 'https://jsonplaceholder.typicode.com'; global.title = 'Express Magazine'; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(expressLayouts); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; In routes\index.js: const express = require('express'); const indexController = require('../controllers/index'); const router = express.Router(); // Get Posts router.get('/', indexController.getHomepageData); // Get Posts By User router.get('/users/:uid/posts/', indexController.getPostsByUser); // Redirect from bad routes router.get('/users/', function(req, res) { res.redirect('/'); });
{ "domain": "codereview.stackexchange", "id": 42673, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, express.js", "url": null }
javascript, express.js // Redirect from bad routes router.get('/users/', function(req, res) { res.redirect('/'); }); router.get('/users/:uid/', function(req, res) { res.redirect('/'); }); module.exports = router; The indexController controler has the folwing code: var axios = require('axios'); var helpers = require('../utils/helpers'); /* GET home page data */ exports.getHomepageData = async (req, res, next) => { try { let [userData, postData] = await Promise.all([ axios.get(`${base_url}/users`), axios.get(`${base_url}/posts`) ]); const users = userData.data; const posts = postData.data; res.render('index', { layout: 'layout', pageTitle: 'All posts', users: users, currentUser: null, posts: posts, }); } catch (error) { res.status(500).json(error); } }; /* GET posts by user */ exports.getPostsByUser = async (req, res, next) => { try { let uid = req.params.uid; let [userData, currentUserData, postData] = await Promise.all([ axios.get(`${base_url}/users`), axios.get(`${base_url}/users/${uid}`), axios.get(`${base_url}/posts?userId=${uid}`) ]); const users = userData.data; const currentUser = currentUserData.data; const posts = postData.data; res.render('index', { layout: 'layout', users: users, posts: posts, currentUser: currentUser, pageTitle: `Posts by ${currentUser.name}`, }); } catch (error) { res.status(500).json(error); } };
{ "domain": "codereview.stackexchange", "id": 42673, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, express.js", "url": null }
javascript, express.js In the index.ejs view I use the above finctions. Sample: <% if (posts) {%> <div class="row post-grid"> <% posts.forEach(function(post) { %> <div class="col-sm-6 post"> <div class="post-container"> <h2 class="display-4 post-title"><%= post.title.toTitleCase() %></h2> <div class="short-desc"> <%= post.body.capitalizeSentence() %> </div> </div> </div> <% }); %> </div> <% } %> The application works, but I am certain there is room for improvement. Questions Is the code DRY enough? Is it missing anything essential? Answer: Is the code DRY enough? It does not seem very repetitive - looks fine to me. One could be overly pedantic and suggest that the function inside the routes be abstracted: // Redirect from bad routes router.get('/users/', function(req, res) { res.redirect('/'); }); router.get('/users/:uid/', function(req, res) { res.redirect('/'); }); to: // Redirect from bad routes const redirectToRoot = (req, res) => { res.redirect('/'); } router.get('/users/', redirectToRoot); router.get('/users/:uid/', redirectToRoot); but that may be excess work since it only appears twice. If the common function appears 3 or more times then abstracting is typically worth it.
{ "domain": "codereview.stackexchange", "id": 42673, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, express.js", "url": null }
python, tkinter, youtube Title: youtube download application using youtube_dl and tkinter Question: I program in Python as a hobby and decided to try to use tkinter to make an application. I decided to make a YouTube video/audio downloader using youtube_dl. It's really slow, and the tkinter window freezes during the downloading process. But it still completes the download. Because this is the first time using tkinter, I'm not sure my program is very pythonic. Could I maybe get some pointers on how to improve? Thanks in advance! import youtube_dl import time from tkinter import * from tkinter.ttk import Progressbar from tkinter import font as tkFont #application to download youtube song's with or without video #pretty slow but took a lot of work #application looks like it's freezing during the downloading process. this is normal. #name tk function "window" and give it a cool title. window = Tk() window.title("SUPER AWESOME YOUTUBE DOWNLOADER V1") #create window size, xy method window.geometry('575x400') #setup useless progress bar (makes sense later) progress = Progressbar(window, orient=HORIZONTAL, length=250, mode='determinate') #make background red window.configure(bg='red') def A_option(): #download song #retrieve input vid = entry1.get() #to only get audio you need specific inputs in ytlib library. no idea why this works, but i got it from the web. #used a try statement because program can be buggy sometimes. this way it will work nonetheless. #outtmpl is for the download's destination, not sure if this means the code has to change on other computers... try: ytlib = { 'format': 'bestaudio/best', 'noplaylist': True, 'outtmpl': '/python_downloads/%(title)s-%(id)s.%(ext)s', 'continue_dl': True, 'postprocessors_args': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', 'preferredquality': 'max'}] }
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube except Exception: print('something went wrong...') with youtube_dl.YoutubeDL(ytlib) as ydl: ydl.download([vid]) print("download complete") bar() window.mainloop() def bar(): #progress bar #couldn't manage to make it show the actual downloading process... #looks pretty neat so i'm keeping it progress['value'] = 20 window.update_idletasks() time.sleep(1) progress['value'] = 40 window.update_idletasks() time.sleep(1) progress['value'] = 50 window.update_idletasks() time.sleep(1) progress['value'] = 60 window.update_idletasks() time.sleep(1) progress['value'] = 80 window.update_idletasks() time.sleep(1) progress['value'] = 100 window.mainloop() def B_option(): #download video #only had to put outtmpl here because it downloads video's automatically vid = entry1.get() ytlib = { 'outtmpl': '/python_downloads/%(title)s-%(id)s.%(ext)s' } with youtube_dl.YoutubeDL(ytlib) as ydl: ydl.download([vid]) print("download complete") bar() window.mainloop() def delete(): #clears input window (didn't go automatic because i suck) entry1.delete(0, 'end') def stop(): #imidiatly terminates process print('Program finished') quit() def setup(): #here comes the sloppy part #font size foptions = tkFont.Font(family='Helvetica', size=15, weight=tkFont.NORMAL) #create a collum #determine distance inbetween rows of buttons and stuff window.columnconfigure(index=0, weight=0) window.rowconfigure(index=0, weight=0) #create label to point to input box #row is how far down the item is, column is how far right. elink = Label(window, text='Enter youtube link below:', font=foptions, bg='red') elink.grid(row=0, column=0, columnspan=2)
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube #get youtube link input here #make the entry field global, because that makes sense? global entry1 entry1 = Entry(window, width=50, font=foptions, bg='red', fg='black') entry1.grid(row=1, column=0, columnspan=2) #empty progress bar. does not really do anything usefull but looks cool and took a lot of effort. #tried to apply it to the actual progress, but i'm not that good.... #idk what "pady" does, but internet said to do so and it works. the_lie = Label(window, text='Completing download:', font=foptions, bg='red') the_lie.grid(row=4, column=0, columnspan=2) progress.grid(row=5, column=0, columnspan=2, pady=10) #buttons to the options of the app with some modifications to look slightly less bad. Button(window, text='download song', font=foptions, width=15, height=5, bg='black', fg='red', command=A_option).grid(row=2, column=0) Button(window, text='download video', font=foptions, width=15, height=5, bg='black', fg='red', command=B_option).grid(row=2, column=1) Button(window, text='clear entry', font=foptions, width=15, height=5, bg='black', fg='red', command=delete).grid(row=3, column=0) Button(window, text='exit', font=foptions, width=15, height=5, bg='black', fg='red', command=stop).grid(row=3, column=1) #always use them mainloops window.mainloop() setup() Answer: It's really slow That can't be avoided. the tkinter window freezes during the downloading process Long story short, that can't be entirely avoided unless you use something better than youtube_dl, and/or you use your own threading. My proposal includes a hack that reduces the freeze to the period between progress calls. Metacommentary i suck Don't be so hard on yourself - you're learning, and you made something that more or less works! no idea why this works, but i got it from the web. idk what "pady" does, but internet said to do so and it works.
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube idk what "pady" does, but internet said to do so and it works. If you're at all serious about learning programming, even only as a hobby, you need to jettison this attitude right now. The moment you see something you don't understand, you should avoid blindly copy-and-pasting it, and do the research to find out how and why it's written on the internet the way it is. Otherwise, you will always be in the dark. It's OK for programs to start off as frankenstein-ed bits from StackOverflow, but it isn't OK for you to avoid learning from that. Commentary: existing code Avoid import *; it pollutes your namespace. Instead, particularly for tkinter, just import the library (potentially with an as alias) and get to its symbols through a fully-qualified dot expression. Avoid globals. The easiest way to do this is to make a class. Avoid calling get and delete on an Entry; use a StringVar instead. used a try statement because program can be buggy sometimes wraps code that will never fail, so you should just delete that try. Don't spin up a new YoutubeDL each time you download; keep one of each client type (music and video) for your program instance. prints are unhelpful, since you should usually assume that your users only care about the UI. If you want to log, you can, but you should use the actual logging module. Don't sleep. Update your progress bar based on calls from YoutubeDL's progress hook. As for look slightly less bad I suppose that's in the eye of the beholder. I think the black, red and giant fonts you've used are mildly excruciating, and generally I prefer to use default UI themes. Improvements Consider: factor out the downloader params of each type to global, constant dicts Use the progress hook, and convert its dictionary to a dataclass for stronger typing Use the information from the progress hook to populate your progress title label Use a frame to allow auto-sized grid columns Prevent the user from changing settings while a download is happening
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube Suggested I can fairly guarantee that this suggested code will include syntax and concepts you've not seen before, but I consider it a learning opportunity. #!/usr/bin/env python3 # application to download youtube songs with or without video import tkinter as tk import tkinter.ttk as ttk from dataclasses import dataclass from datetime import timedelta from typing import Optional from youtube_dl import YoutubeDL # These parameters are shared by song mode. VIDEO_PARAMS = { 'outtmpl': '/python_downloads/%(title)s-%(id)s.%(ext)s' } SONG_PARAMS = { **VIDEO_PARAMS, 'format': 'bestaudio/best', 'noplaylist': True, 'continue_dl': True, 'postprocessors_args': [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', 'preferredquality': 'max', } ] } class CancelDownload(Exception): """ Thrown in the middle of our progress callback if the window has been destroyed and we need to unwind the youtube_dl stack. """ @dataclass class YTProgress: """ The youtube_dl progress hook's information dictionary is weakly-typed. This represents it as a convenience dataclass. """ status: str total_bytes: int filename: str downloaded_bytes: Optional[int] = None elapsed: Optional[float] = None tmpfilename: Optional[str] = None eta: Optional[int] = None speed: Optional[float] = None @property def is_finished(self) -> bool: return self.status == 'finished' @property def elapsed_delta(self) -> timedelta: return timedelta(seconds=round(self.elapsed)) @property def eta_delta(self) -> timedelta: return self.elapsed_delta + timedelta(seconds=self.eta) def __str__(self): if self.is_finished: # Many of the members will be None if we're finished, so just # return the status. return self.status
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube # Put as much detail here as you want. return ( f'{self.status}' f': {self.downloaded_bytes/self.total_bytes:.1%}' f', {self.downloaded_bytes/2**20:.1f}/{self.total_bytes/2**20:.1f} MiB' f', {self.speed/2**10:.0f} KiB/s' f', {self.elapsed_delta}/{self.eta_delta}' ) class DownloaderUI: """ One instance of this class will have - a reference to a parent Tk that will close on exit; - references to a container frame and its widgets; and - an instance of YoutubeDL for each of song and video modes. """ def __init__(self, parent: tk.Tk) -> None: self.parent = parent # Use a frame container to allow grid auto-sizing self.frame = frame = tk.Frame(parent) frame.pack_configure( fill=tk.X, expand=tk.YES, anchor=tk.N, # north ) for x in range(2): frame.grid_columnconfigure(index=x, weight=1) self.link_var, self.entry, *buttons = self.make_settings_widgets(frame) self.settings_widgets = (self.entry, *buttons) tk.Button( frame, text='Exit', command=self.quit, ).grid(row=3, column=1, sticky=tk.EW, padx=5, pady=5) # east-west edges parent.wm_protocol('WM_DELETE_WINDOW', self.quit) self.progress_widgets = self.make_progress_widgets(frame) self.progress_title, self.progress = self.progress_widgets self.hide_progress() def quit(self) -> None: # This could be reworked so that only the frame is destroyed, and a # callback offered for the owner. # `frame` is nulled out here to let ongoing downloader callbacks know # that they can no longer use widgets. self.frame = None self.parent.destroy()
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube def make_settings_widgets(self, frame: tk.Widget) -> tuple[ tk.StringVar, # link var tk.Entry, # link entry tk.Button, # download song button tk.Button, # download video button tk.Button, # clear entry button ]: tk.Label( frame, text='Enter YouTube link below:' ).grid(row=0, column=0, columnspan=2, sticky=tk.EW) link_var = tk.StringVar(frame, name='link') entry = tk.Entry(frame, textvariable=link_var) entry.grid(row=1, column=0, columnspan=2, sticky=tk.EW) download_song_button = tk.Button( frame, text='Download song', command=self.download_song, ) download_song_button.grid(row=2, column=0, sticky=tk.EW, padx=5, pady=5) download_video_button = tk.Button( frame, text='Download video', command=self.download_video, ) download_video_button.grid(row=2, column=1, sticky=tk.EW, padx=5, pady=5) clear_entry_button = tk.Button( frame, text='Clear entry', command=self.clear_entry, ) clear_entry_button.grid(row=3, column=0, sticky=tk.EW, padx=5, pady=5) return link_var, entry, download_song_button, download_video_button, clear_entry_button @staticmethod def make_progress_widgets(frame: tk.Widget) -> tuple[tk.Label, ttk.Progressbar]: progress_title = tk.Label(frame) progress_title.grid(row=4, column=0, columnspan=2, sticky=tk.EW) progress = ttk.Progressbar(frame, orient=tk.HORIZONTAL, mode='determinate') progress.grid(row=5, column=0, columnspan=2, sticky=tk.EW) return progress_title, progress
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube return progress_title, progress def show_progress(self) -> None: # When the downloader is running, don't let the user change any # settings or start any new downloads, and show the progress widgets. for widget in self.progress_widgets: widget.grid() for widget in self.settings_widgets: widget.configure(state=tk.DISABLED) def hide_progress(self) -> None: # When the downloader isn't running, let the user change settings, and # hide the progress widgets. for widget in self.progress_widgets: widget.grid_remove() for widget in self.settings_widgets: widget.configure(state=tk.NORMAL) def clear_entry(self) -> None: # Do this via Tk string variable, not widget config() or delete(). self.link_var.set('') def __enter__(self) -> 'DownloaderUI': # This is called when the owner uses our class in a `with`. Since we # have YoutubeDL instances that also expect `with` context management, # call it here. self.yt_song = YoutubeDL(SONG_PARAMS) self.yt_video = YoutubeDL(VIDEO_PARAMS) for yt in (self.yt_song, self.yt_video): yt.__enter__() yt.add_progress_hook(self.yt_progress) return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: # This is called when the owner's `with()` completes on our class # instance. Chain the exit call to our downloader instances. for yt in (self.yt_song, self.yt_video): yt.__exit__() def yt_progress(self, kwargs: dict[str, object]) -> None: # Invoked by YoutubeDL during download. It gives us a weakly-typed pile # of dictionary soup; convert this to a dataclass. Ignore underscored # keys. progress = YTProgress(**{ k: v for k, v in kwargs.items() if not k.startswith('_') })
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube # If our frame was destroyed, we need to stop the download. The only # practical way to do this while keeping the process alive is to raise # an exception from within the progress callback, which unwinds the # stack all the way down to the download() call. if self.frame is None: raise CancelDownload() # If the download is finished, hide our progress controls. if progress.is_finished: self.hide_progress() else: self.progress.configure( value=progress.downloaded_bytes, maximum=progress.total_bytes, ) # Use the __str__ definition on our progress object to set the title text. self.progress_title.configure(text=str(progress)) # This is a hack: since youtube_dl has no asynchronous support, and # since I don't want to get into threading into this post, during each # progress callback we give tk the opportunity to process its message # queue. This means that the window will only freeze between progress # calls, not for the entire duration of the download. self.frame.update() def download(self, yt: YoutubeDL) -> None: self.show_progress() try: yt.download([self.link_var.get()]) # If the above line didn't throw, that means the download completed # gracefully and we should hide our progress widgets. self.hide_progress() except CancelDownload: # The frame was destroyed and the download was cancelled. pass
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
python, tkinter, youtube def download_song(self) -> None: # tk callbacks should be short-lived. Unless we get into threading, we # don't have that option; so we just need to sit here and download # until the download completes or is cancelled. To periodically # un-freeze the window, the inner progress callback issues update()s. self.download(self.yt_song) def download_video(self) -> None: self.download(self.yt_video) def main() -> None: # Parent window owned(ish) by us. To make it truly owned by us and not # DownloaderUI, we would need a hook to notice when the frame is destroyed. window = tk.Tk() window.title('Super Awesome YouTube Downloader V2') window.geometry('400x200') with DownloaderUI(window) as downloader: downloader.frame.mainloop() # Don't run main() if someone is importing us; only if we're being run at the # top level. if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 42674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, youtube", "url": null }
c++, algorithm, c++20 Title: 3D Discrete Cosine Transformation Implementation in C++ Question: This is a follow-up question for Parallel 3D Discrete Cosine Transformation Implementation in Matlab and Operator overloading in Image class implementation in C++. I am trying to implement 3D Discrete Cosine Transformation calculation in C++. The formula of 3D Discrete Cosine Transformation is as follows. The 3D discrete cosine transformation $$X(k_{1}, k_{2}, k_{3})$$ of size $$N_{1} \times N_{2} \times N_{3}$$ is \begin{equation} \begin{split} {X(k_{1}, k_{2}, k_{3})} = {\frac {8}{N_{1} N_{2} N_{3}}} \epsilon_{k_{1}} \epsilon_{k_{2}} \epsilon_{k_{3}} \sum_{{n_1 = 0}}^{N_1 - 1} \sum_{{n_2 = 0}}^{N_2 - 1} \sum_{{n_3 = 0}}^{N_3 - 1} x(n_{1}, n_{2}, n_{3}) \\ \times \cos({\frac {\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \\ \times \cos({\frac {\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \\ \times \cos({\frac {\pi}{2N_{3}} (2n_{3} + 1)k_{3}}) \end{split} \label{eq:3DDCTMainFormula} \end{equation} where \begin{equation} \begin{split} k_{1} = 0, 1, \dots, N_{1} - 1 \\ k_{2} = 0, 1, \dots, N_{2} - 1 \\ k_{3} = 0, 1, \dots, N_{3} - 1 \\ \epsilon_{k_{i}} = \begin{cases} \frac{1}{\sqrt{2}} & \text{for $k_{i} = 0$} \\ 1 & \text{otherwise} \end{cases} i = 1, 2, 3 \end{split} \label{eq:3DDCTMainFormulaDetail} \end{equation} The experimental implementation
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 dct3_detail template function implementation: template<arithmetic ElementT = double, arithmetic OutputT = ElementT> constexpr static Image<ElementT> dct3_detail(std::vector<Image<ElementT>> input, int plane_index) { std::size_t N3 = input.size(); OutputT alpha1 = (plane_index == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); y++) { OutputT alpha2 = (y == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); for (std::size_t x = 0; x < output.getWidth(); x++) { OutputT sum{}; OutputT alpha3 = (x == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); for (std::size_t inner_z = 0; inner_z < N3; inner_z++) { auto plane = input[inner_z]; auto N1 = static_cast<OutputT>(plane.getWidth()); auto N2 = static_cast<OutputT>(plane.getHeight()); for (std::size_t inner_y = 0; inner_y < plane.getHeight(); inner_y++) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); inner_x++) { auto l1 = (std::numbers::pi / (2 * N1) * (2 * static_cast<OutputT>(inner_x) + 1) * x); auto l2 = (std::numbers::pi / (2 * N2) * (2 * static_cast<OutputT>(inner_y) + 1) * y); auto l3 = (std::numbers::pi / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(inner_z) + 1) * static_cast<OutputT>(plane_index)); sum += static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3); } } }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 } } } auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); output.at(x, y) = 8 * alpha1 * alpha2 * alpha3 * sum / (N1 * N2 * N3); } } return output; }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 dct3 template function implementation: template<arithmetic ElementT = double, arithmetic OutputT = ElementT> constexpr static std::vector<Image<ElementT>> dct3(std::vector<Image<ElementT>> input) { std::vector<Image<ElementT>> output; for (std::size_t i = 0; i < input.size(); i++) { output.push_back(dct3_detail(input, i)); } return output; } arithmetic concept: template <typename T> concept arithmetic = std::is_arithmetic_v<T>; Full Testing Code The full tests for dct3 template function: #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <cmath> #include <concepts> #include <exception> #include <execution> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <numbers> #include <numeric> #include <ranges> #include <string> #include <type_traits> #include <utility> #include <vector> using BYTE = unsigned char; struct RGB { BYTE channels[3]; }; using GrayScale = BYTE; namespace TinyDIP { #define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());} // Reference: https://stackoverflow.com/a/58067611/6667035 template <typename T> concept arithmetic = std::is_arithmetic_v<T>; template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {}
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Image(std::vector<ElementT> input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const noexcept { return height; } constexpr auto getSize() noexcept { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data; void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } };
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 template<arithmetic ElementT = double, arithmetic OutputT = ElementT> constexpr static Image<ElementT> dct3_detail(std::vector<Image<ElementT>> input, int plane_index) { std::size_t N3 = input.size(); OutputT alpha1 = (plane_index == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); y++) { OutputT alpha2 = (y == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); for (std::size_t x = 0; x < output.getWidth(); x++) { OutputT sum{}; OutputT alpha3 = (x == 0) ? (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))) : (static_cast<OutputT>(1.0)); for (std::size_t inner_z = 0; inner_z < N3; inner_z++) { auto plane = input[inner_z]; auto N1 = static_cast<OutputT>(plane.getWidth()); auto N2 = static_cast<OutputT>(plane.getHeight()); for (std::size_t inner_y = 0; inner_y < plane.getHeight(); inner_y++) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); inner_x++) { auto l1 = (std::numbers::pi / (2 * N1) * (2 * static_cast<OutputT>(inner_x) + 1) * x); auto l2 = (std::numbers::pi / (2 * N2) * (2 * static_cast<OutputT>(inner_y) + 1) * y); auto l3 = (std::numbers::pi / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(inner_z) + 1) * static_cast<OutputT>(plane_index)); sum += static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3);
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 std::cos(l1) * std::cos(l2) * std::cos(l3); } } } auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); output.at(x, y) = 8 * alpha1 * alpha2 * alpha3 * sum / (N1 * N2 * N3); } } return output; }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 template<arithmetic ElementT = double, arithmetic OutputT = ElementT> constexpr static std::vector<Image<ElementT>> dct3(std::vector<Image<ElementT>> input) { std::vector<Image<ElementT>> output; for (std::size_t i = 0; i < input.size(); i++) { output.push_back(dct3_detail(input, i)); } return output; } } template<typename ElementT> void print3(std::vector<TinyDIP::Image<ElementT>> input) { for (std::size_t i = 0; i < input.size(); i++) { input[i].print(); std::cout << "*******************\n"; } } void dct3Test() { std::size_t N1 = 10, N2 = 10, N3 = 10; std::vector<TinyDIP::Image<double>> test_input; for (std::size_t z = 0; z < N3; z++) { test_input.push_back(TinyDIP::Image<double>(N1, N2)); } for (std::size_t z = 1; z <= N3; z++) { for (std::size_t y = 1; y <= N2; y++) { for (std::size_t x = 1; x <= N1; x++) { test_input[z - 1].at(y - 1, x - 1) = x * 100 + y * 10 + z; } } } print3(test_input); auto test_output = TinyDIP::dct3(test_input); print3(test_output); } int main() { auto start = std::chrono::system_clock::now(); dct3Test(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; }
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 The output of the testing code above: 111 121 131 141 151 161 171 181 191 201 211 221 231 241 251 261 271 281 291 301 311 321 331 341 351 361 371 381 391 401 411 421 431 441 451 461 471 481 491 501 511 521 531 541 551 561 571 581 591 601 611 621 631 641 651 661 671 681 691 701 711 721 731 741 751 761 771 781 791 801 811 821 831 841 851 861 871 881 891 901 911 921 931 941 951 961 971 981 991 1001 1011 1021 1031 1041 1051 1061 1071 1081 1091 1101 ******************* 112 122 132 142 152 162 172 182 192 202 212 222 232 242 252 262 272 282 292 302 312 322 332 342 352 362 372 382 392 402 412 422 432 442 452 462 472 482 492 502 512 522 532 542 552 562 572 582 592 602 612 622 632 642 652 662 672 682 692 702 712 722 732 742 752 762 772 782 792 802 812 822 832 842 852 862 872 882 892 902 912 922 932 942 952 962 972 982 992 1002 1012 1022 1032 1042 1052 1062 1072 1082 1092 1102 ******************* 113 123 133 143 153 163 173 183 193 203 213 223 233 243 253 263 273 283 293 303 313 323 333 343 353 363 373 383 393 403 413 423 433 443 453 463 473 483 493 503 513 523 533 543 553 563 573 583 593 603 613 623 633 643 653 663 673 683 693 703 713 723 733 743 753 763 773 783 793 803 813 823 833 843 853 863 873 883 893 903 913 923 933 943 953 963 973 983 993 1003 1013 1023 1033 1043 1053 1063 1073 1083 1093 1103 ******************* 114 124 134 144 154 164 174 184 194 204 214 224 234 244 254 264 274 284 294 304 314 324 334 344 354 364 374 384 394 404 414 424 434 444 454 464 474 484 494 504 514 524 534 544 554 564 574 584 594 604 614 624 634 644 654 664 674 684 694 704 714 724 734 744 754 764 774 784 794 804 814 824 834 844 854 864 874 884 894 904 914 924 934 944 954 964 974 984 994 1004 1014 1024 1034 1044 1054 1064 1074 1084 1094 1104
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* 115 125 135 145 155 165 175 185 195 205 215 225 235 245 255 265 275 285 295 305 315 325 335 345 355 365 375 385 395 405 415 425 435 445 455 465 475 485 495 505 515 525 535 545 555 565 575 585 595 605 615 625 635 645 655 665 675 685 695 705 715 725 735 745 755 765 775 785 795 805 815 825 835 845 855 865 875 885 895 905 915 925 935 945 955 965 975 985 995 1005 1015 1025 1035 1045 1055 1065 1075 1085 1095 1105 ******************* 116 126 136 146 156 166 176 186 196 206 216 226 236 246 256 266 276 286 296 306 316 326 336 346 356 366 376 386 396 406 416 426 436 446 456 466 476 486 496 506 516 526 536 546 556 566 576 586 596 606 616 626 636 646 656 666 676 686 696 706 716 726 736 746 756 766 776 786 796 806 816 826 836 846 856 866 876 886 896 906 916 926 936 946 956 966 976 986 996 1006 1016 1026 1036 1046 1056 1066 1076 1086 1096 1106 ******************* 117 127 137 147 157 167 177 187 197 207 217 227 237 247 257 267 277 287 297 307 317 327 337 347 357 367 377 387 397 407 417 427 437 447 457 467 477 487 497 507 517 527 537 547 557 567 577 587 597 607 617 627 637 647 657 667 677 687 697 707 717 727 737 747 757 767 777 787 797 807 817 827 837 847 857 867 877 887 897 907 917 927 937 947 957 967 977 987 997 1007 1017 1027 1037 1047 1057 1067 1077 1087 1097 1107 ******************* 118 128 138 148 158 168 178 188 198 208 218 228 238 248 258 268 278 288 298 308 318 328 338 348 358 368 378 388 398 408 418 428 438 448 458 468 478 488 498 508 518 528 538 548 558 568 578 588 598 608 618 628 638 648 658 668 678 688 698 708 718 728 738 748 758 768 778 788 798 808 818 828 838 848 858 868 878 888 898 908 918 928 938 948 958 968 978 988 998 1008 1018 1028 1038 1048 1058 1068 1078 1088 1098 1108
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* 119 129 139 149 159 169 179 189 199 209 219 229 239 249 259 269 279 289 299 309 319 329 339 349 359 369 379 389 399 409 419 429 439 449 459 469 479 489 499 509 519 529 539 549 559 569 579 589 599 609 619 629 639 649 659 669 679 689 699 709 719 729 739 749 759 769 779 789 799 809 819 829 839 849 859 869 879 889 899 909 919 929 939 949 959 969 979 989 999 1009 1019 1029 1039 1049 1059 1069 1079 1089 1099 1109 ******************* 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350 360 370 380 390 400 410 420 430 440 450 460 470 480 490 500 510 520 530 540 550 560 570 580 590 600 610 620 630 640 650 660 670 680 690 700 710 720 730 740 750 760 770 780 790 800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990 1000 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100 1110
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* 1726.75 -80.7207 2.5284e-13 -8.64604 -7.77618e-14 -2.82843 1.59162e-13 -1.14371 -1.43473e-13 -0.320717 -807.207 2.57244e-14 -1.24763e-13 -1.00325e-13 4.82332e-14 -7.91025e-14 -9.83958e-14 1.62707e-13 5.91661e-14 6.73658e-14 3.81988e-13 -1.54346e-14 -1.28622e-14 -1.92933e-15 1.41484e-14 -3.85866e-15 -1.28622e-15 3.21555e-15 -5.46643e-15 8.84276e-15 -86.4604 -1.22191e-14 -4.50177e-15 -8.36043e-15 5.14488e-15 1.92933e-15 7.07421e-15 7.71732e-15 2.57244e-15 -2.41166e-15 -5.54792e-14 6.4311e-15 1.92933e-15 -1.28622e-15 -2.57244e-15 3.85866e-15 -4.50177e-15 7.71732e-15 -3.21555e-15 -2.21873e-14 -28.2843 -5.14488e-15 1.28622e-15 -4.50177e-15 3.21555e-15 -5.78799e-15 -7.39576e-15 9.9682e-15 -1.28622e-15 9.64665e-15 1.64164e-13 -7.71732e-15 4.50177e-15 2.57244e-14 -6.4311e-16 3.21555e-16 -1.28622e-15 3.85866e-15 -4.50177e-15 -3.85866e-15 -11.4371 2.18657e-14 -1.57562e-14 -3.21555e-15 1.60777e-15 1.70424e-14 -3.21555e-16 -4.66255e-15 -1.60777e-15 -9.56626e-15 -3.77668e-13 8.68198e-15 1.28622e-15 -5.78799e-15 -1.92933e-15 -1.447e-15 -5.14488e-15 2.73322e-15 2.81361e-15 1.00888e-14 -3.20717 5.30566e-15 8.03887e-16 5.30566e-15 -1.68816e-14 -3.5371e-15 -1.63993e-14 7.39576e-15 1.2822e-14 1.18171e-14
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -8.07207 2.3152e-14 -7.71732e-15 -5.14488e-15 1.92933e-15 -6.4311e-16 -3.85866e-15 1.02898e-14 4.50177e-15 4.82332e-16 -2.4824e-13 5.45697e-15 -5.45697e-15 1.18234e-14 -9.09495e-16 8.18545e-15 0 -4.54747e-15 4.09273e-15 -3.86535e-15 -4.50177e-14 3.63798e-15 -1.81899e-15 6.36646e-15 1.81899e-15 6.36646e-15 3.63798e-15 -4.54747e-15 -4.54747e-15 -2.27374e-16 6.4311e-15 -9.09495e-16 0 1.81899e-15 -9.09495e-16 0 -8.18545e-15 1.81899e-15 -4.54747e-15 4.09273e-15 -1.54346e-14 -8.18545e-15 -1.81899e-15 -1.81899e-15 6.36646e-15 4.54747e-15 7.27596e-15 -1.81899e-15 -2.27374e-15 2.27374e-15 -6.4311e-16 4.54747e-15 -3.63798e-15 -2.72848e-15 8.18545e-15 4.54747e-15 -5.91172e-15 -2.27374e-15 -6.13909e-15 -5.00222e-15 1.02898e-14 6.36646e-15 1.81899e-15 -9.09495e-16 4.54747e-15 5.00222e-15 4.09273e-15 9.09495e-16 -2.27374e-16 8.6402e-15 -1.31838e-14 -9.09495e-16 5.45697e-15 -1.36424e-15 -9.09495e-16 -2.72848e-15 -5.91172e-15 5.68434e-15 6.13909e-15 -8.18545e-15 1.86502e-14 -5.00222e-15 -9.09495e-16 -4.54747e-16 -9.54969e-15 -4.77485e-15 -4.54747e-16 -9.09495e-16 5.00222e-15 3.41061e-15 1.63993e-14 5.68434e-15 -6.82121e-15 -9.09495e-16 -9.77707e-15 -7.04858e-15 2.95586e-15 2.95586e-15 1.02318e-15 1.39266e-15
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* 3.31056e-13 -5.14488e-15 -1.41484e-14 -9.64665e-15 1.28622e-14 -6.4311e-15 6.4311e-15 3.21555e-15 -4.18021e-15 1.12544e-15 -1.06756e-13 -1.09139e-14 -1.81899e-15 -9.09495e-16 -7.27596e-15 -9.09495e-16 -1.81899e-15 -4.54747e-15 4.54747e-15 -7.50333e-15 -4.1159e-14 5.45697e-15 -3.63798e-15 -1.81899e-15 -5.45697e-15 -4.54747e-15 2.72848e-15 -2.27374e-15 9.09495e-16 -2.72848e-15 -5.14488e-15 -1.45519e-14 -7.27596e-15 -9.09495e-16 -2.72848e-15 9.09495e-15 0 -2.72848e-15 -9.09495e-16 -1.11413e-14 -3.21555e-15 3.63798e-15 1.00044e-14 -3.63798e-15 -4.54747e-15 -8.18545e-15 -4.54747e-15 -3.18323e-15 3.18323e-15 -5.22959e-15 -1.41484e-14 6.36646e-15 0 9.09495e-16 -1.81899e-15 -8.18545e-15 -2.27374e-15 -7.7307e-15 1.59162e-15 -8.6402e-15 1.92933e-14 1.81899e-15 -2.72848e-15 -1.81899e-15 2.27374e-15 -7.27596e-15 -2.72848e-15 2.27374e-15 1.81899e-15 3.18323e-15 1.60777e-15 -9.09495e-16 4.54747e-15 2.27374e-15 0 5.91172e-15 -2.72848e-15 2.04636e-15 3.18323e-15 -5.91172e-15 -1.54346e-14 3.18323e-15 -1.36424e-15 4.54747e-16 1.22782e-14 -4.3201e-15 8.41283e-15 0 -1.13687e-15 6.82121e-16 -6.27032e-15 -4.54747e-16 6.82121e-16 -4.54747e-16 2.27374e-16 -2.38742e-15 -1.13687e-15 2.04636e-15 -6.82121e-16 -6.16751e-15
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -0.864604 -9.64665e-15 6.4311e-16 7.07421e-15 0 -7.07421e-15 1.35053e-14 -3.85866e-15 -6.4311e-16 -2.41166e-15 -2.71392e-13 -8.18545e-15 -3.63798e-15 3.63798e-15 -8.18545e-15 -1.09139e-14 2.72848e-15 -3.63798e-15 -9.09495e-16 7.7307e-15 -5.14488e-15 0 -9.09495e-15 -4.54747e-15 -2.72848e-15 -5.45697e-15 -2.72848e-15 -3.63798e-15 -6.36646e-15 -2.27374e-16 -4.6947e-14 0 5.45697e-15 -4.54747e-15 -9.09495e-16 2.72848e-15 -4.54747e-15 -1.36424e-15 6.36646e-15 -1.18234e-14 1.09329e-14 -8.18545e-15 5.45697e-15 -2.72848e-15 9.09495e-16 8.18545e-15 -1.09139e-14 3.18323e-15 2.27374e-15 5.45697e-15 1.54346e-14 -1.81899e-15 -9.09495e-16 2.72848e-15 4.54747e-15 -2.72848e-15 -6.36646e-15 3.63798e-15 9.09495e-16 3.86535e-15 5.78799e-15 -9.09495e-15 -7.27596e-15 -9.09495e-16 -3.63798e-15 4.54747e-15 1.22782e-14 -1.36424e-15 -2.27374e-16 5.68434e-16 -1.28622e-14 5.45697e-15 5.91172e-15 6.82121e-15 -6.36646e-15 2.27374e-15 -2.27374e-15 1.36424e-15 3.86535e-15 2.6148e-15 -5.46643e-15 2.72848e-15 -4.54747e-15 4.54747e-15 -2.04636e-15 -1.81899e-15 3.86535e-15 2.72848e-15 1.13687e-15 -1.47793e-15 -1.78463e-14 8.6402e-15 -2.04636e-15 -2.27374e-15 1.28466e-14 2.38742e-15 -3.41061e-16 -1.02318e-15 -2.04636e-15 -9.37916e-16
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -4.09273e-14 1.1576e-14 1.09329e-14 3.85866e-15 -3.85866e-15 3.85866e-15 6.4311e-15 1.1576e-14 -5.14488e-15 -9.32509e-15 -5.14488e-15 -6.36646e-15 -1.81899e-15 0 -4.54747e-15 -4.54747e-15 0 -5.45697e-15 -5.00222e-15 2.27374e-15 -2.37951e-14 0 9.09495e-16 -3.63798e-15 -1.00044e-14 -9.09495e-16 3.63798e-15 5.91172e-15 5.00222e-15 -1.25056e-14 6.4311e-16 9.09495e-16 7.27596e-15 -9.09495e-16 4.54747e-15 8.18545e-15 -1.63709e-14 5.00222e-15 -4.54747e-16 1.81899e-15 -1.02898e-14 -4.54747e-15 -5.45697e-15 3.63798e-15 2.72848e-15 -1.81899e-15 1.09139e-14 -8.18545e-15 4.3201e-15 5.22959e-15 -2.25088e-14 -1.81899e-15 -8.18545e-15 0 1.81899e-15 1.81899e-15 1.36424e-15 1.81899e-15 9.09495e-16 1.13687e-15 1.80071e-14 -3.63798e-15 -5.00222e-15 9.09495e-16 5.45697e-15 6.82121e-15 -4.54747e-15 -9.54969e-15 3.86535e-15 -2.27374e-15 -1.38269e-14 9.09495e-16 -3.63798e-15 -2.72848e-15 -1.81899e-15 2.72848e-15 -3.86535e-15 -1.81899e-15 -3.29692e-15 -7.56017e-15 -2.95831e-14 5.45697e-15 -2.27374e-15 2.50111e-15 -1.36424e-15 1.11413e-14 9.54969e-15 5.34328e-15 -1.02318e-15 -1.04023e-14 -1.09329e-14 -1.59162e-15 -9.09495e-16 -1.10276e-14 4.20641e-15 6.36646e-15 3.86535e-15 1.59162e-15 -7.04858e-15 1.29319e-14
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -0.282843 -9.00354e-15 -7.71732e-15 -3.21555e-15 9.64665e-15 -5.78799e-15 2.25088e-15 3.5371e-15 -1.92933e-15 4.50177e-15 -1.08686e-13 2.72848e-15 -5.45697e-15 8.18545e-15 8.18545e-15 9.09495e-16 -4.54747e-16 3.18323e-15 -5.22959e-15 4.54747e-16 4.75901e-14 -4.54747e-15 3.63798e-15 -9.09495e-16 0 -6.36646e-15 8.6402e-15 -1.81899e-15 -2.95586e-15 -8.6402e-15 -3.08693e-14 -1.81899e-15 2.72848e-15 -9.09495e-16 1.00044e-14 0 6.36646e-15 -9.09495e-16 -1.36424e-15 1.29603e-14 3.21555e-15 -1.81899e-15 2.72848e-15 1.81899e-15 3.63798e-15 0 2.27374e-15 -3.63798e-15 0 -6.13909e-15 -3.47279e-14 -1.81899e-15 -5.45697e-15 0 9.09495e-16 5.00222e-15 4.54747e-16 1.13687e-15 -5.22959e-15 2.16005e-15 -2.57244e-15 -2.27374e-15 5.00222e-15 5.45697e-15 2.27374e-15 7.27596e-15 9.09495e-16 -8.6402e-15 -9.09495e-16 -1.20508e-14 -1.41484e-14 3.18323e-15 -5.91172e-15 4.54747e-16 8.18545e-15 -3.18323e-15 -2.27374e-16 -4.3201e-15 3.29692e-15 -1.81899e-15 4.82332e-16 2.72848e-15 -1.13687e-14 5.22959e-15 6.13909e-15 4.09273e-15 5.00222e-15 -1.7053e-15 -2.38742e-15 1.47793e-15 6.4311e-15 7.61702e-15 2.16005e-15 -4.54747e-16 2.27374e-16 -6.36646e-15 2.95586e-15 0 3.9222e-15 9.6918e-15
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* 1.64164e-13 -1.54346e-14 3.21555e-15 1.41484e-14 -3.21555e-15 5.46643e-15 -5.14488e-15 -1.28622e-15 -7.07421e-15 0 -1.02898e-14 1.00044e-14 5.45697e-15 0 -7.27596e-15 -7.7307e-15 4.09273e-15 -4.54747e-15 2.95586e-15 1.59162e-14 3.85866e-15 1.09139e-14 6.36646e-15 9.09495e-16 4.09273e-15 -3.63798e-15 9.09495e-16 4.54747e-16 9.09495e-16 1.36424e-15 2.12226e-14 -3.63798e-15 1.81899e-15 -3.63798e-15 -1.00044e-14 -2.72848e-15 5.91172e-15 -3.63798e-15 5.68434e-15 1.87583e-14 -4.88764e-14 3.63798e-15 -7.7307e-15 -5.45697e-15 -1.09139e-14 -9.54969e-15 -2.72848e-15 -7.7307e-15 9.32232e-15 -4.09273e-15 -7.71732e-15 8.6402e-15 -9.54969e-15 -3.63798e-15 -8.6402e-15 -9.09495e-16 -9.09495e-16 -2.27374e-16 3.18323e-15 -4.77485e-15 -2.57244e-15 5.91172e-15 -7.7307e-15 2.27374e-15 -5.91172e-15 5.91172e-15 -2.04636e-15 1.81899e-15 4.20641e-15 -5.85487e-15 -2.89399e-15 -1.36424e-15 5.91172e-15 -7.7307e-15 7.50333e-15 -1.13687e-15 4.54747e-16 -1.81899e-15 6.36646e-15 -1.20508e-14 -5.94877e-15 1.13687e-15 -6.82121e-16 9.54969e-15 2.72848e-15 5.91172e-15 -3.86535e-15 7.95808e-16 -2.04636e-15 -4.20641e-15 -2.06599e-14 -6.48015e-15 4.3201e-15 3.97904e-15 2.72848e-15 -3.63798e-15 7.7307e-15 -5.68434e-17 2.70006e-15 6.96332e-15
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -0.114371 2.44382e-14 -3.21555e-16 -8.36043e-15 7.39576e-15 8.68198e-15 -4.50177e-15 -1.60777e-16 -1.92933e-15 -1.21387e-14 2.08046e-13 -1.00044e-14 1.81899e-15 2.27374e-15 1.81899e-15 -4.54747e-15 -4.54747e-15 5.68434e-15 7.04858e-15 1.00044e-14 -4.9841e-14 -2.72848e-15 9.09495e-15 9.09495e-16 -6.36646e-15 4.54747e-16 5.45697e-15 1.81899e-15 4.54747e-16 8.6402e-15 3.85866e-14 5.45697e-15 -4.54747e-16 -4.09273e-15 -3.63798e-15 2.27374e-15 -5.00222e-15 -9.09495e-16 1.13687e-15 -1.37561e-14 6.75265e-15 -2.72848e-15 -3.63798e-15 3.63798e-15 -9.09495e-16 -9.09495e-16 -2.04636e-15 1.13687e-15 2.6148e-15 1.53477e-15 1.1576e-14 -4.09273e-15 -7.7307e-15 5.45697e-15 3.63798e-15 9.09495e-16 -2.95586e-15 2.50111e-15 -2.16005e-15 -1.00044e-14 -1.06113e-14 5.91172e-15 6.82121e-15 -9.54969e-15 3.86535e-15 -1.13687e-15 9.09495e-15 -3.86535e-15 8.6402e-15 5.22959e-15 -8.52121e-15 3.63798e-15 2.04636e-15 4.77485e-15 -3.18323e-15 1.59162e-15 -2.72848e-15 7.04858e-15 -5.22959e-15 1.33014e-14 8.03887e-15 -5.22959e-15 5.00222e-15 -1.13687e-15 -2.72848e-15 1.19371e-14 -4.66116e-15 -7.95808e-16 7.21911e-15 -6.39488e-15 -8.03887e-16 -8.07177e-15 2.27374e-15 5.68434e-16 -3.63798e-15 6.13909e-15 -9.09495e-16 8.69704e-15 -2.84217e-15 8.14282e-15
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -6.29825e-14 8.03887e-15 -8.36043e-15 -3.5371e-15 -6.4311e-15 4.34099e-15 -1.02898e-14 -6.4311e-16 -3.45672e-15 2.23079e-14 6.75265e-14 7.7307e-15 -9.09495e-16 4.54747e-16 5.91172e-15 3.86535e-15 -8.6402e-15 6.82121e-15 -9.09495e-16 6.13909e-15 -4.1159e-14 3.18323e-15 2.27374e-15 -2.27374e-15 9.54969e-15 -1.59162e-15 -4.3201e-15 2.50111e-15 1.36424e-15 5.22959e-15 2.25088e-15 -1.00044e-14 -4.54747e-15 2.72848e-15 5.22959e-15 -7.27596e-15 9.32232e-15 -1.13687e-15 4.54747e-16 -1.47793e-15 -1.67209e-14 -2.72848e-15 1.81899e-15 2.50111e-15 6.82121e-15 5.68434e-15 -1.59162e-15 1.93268e-15 -2.16005e-15 -1.67688e-14 -4.66255e-15 6.36646e-15 4.54747e-15 1.59162e-15 7.95808e-15 -4.54747e-15 4.54747e-16 -2.50111e-15 -3.41061e-16 -9.43601e-15 -7.23499e-15 7.04858e-15 9.32232e-15 -4.54747e-16 6.36646e-15 -1.04592e-14 7.50333e-15 8.07177e-15 -6.59384e-15 1.25056e-15 2.47597e-14 1.38698e-14 -5.45697e-15 2.50111e-15 -6.82121e-16 1.28466e-14 -1.47793e-15 -3.75167e-15 3.12639e-15 -1.84741e-15 1.96952e-14 -5.45697e-15 -3.75167e-15 -1.09139e-14 -3.63798e-15 -3.18323e-15 -1.00613e-14 -4.77485e-15 2.04636e-15 1.6172e-14 9.36529e-15 9.09495e-16 3.52429e-15 4.66116e-15 -1.3415e-14 -1.02318e-14 -3.78009e-15 1.90425e-15 7.24754e-15 -1.09424e-14
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 ******************* -0.0320717 1.43092e-14 4.34099e-15 6.27032e-15 -9.80743e-15 8.36043e-15 -5.94877e-15 -4.90371e-15 1.25004e-14 1.95345e-14 5.75583e-14 -7.04858e-15 4.54747e-16 4.54747e-15 3.86535e-15 -1.13687e-14 6.59384e-15 2.95586e-15 -9.09495e-16 4.83169e-16 1.94541e-14 -1.81899e-15 -5.22959e-15 0 3.41061e-15 -3.97904e-15 -3.18323e-15 -1.59162e-15 4.54747e-16 -6.62226e-15 -1.12544e-15 -2.27374e-15 -2.95586e-15 5.00222e-15 3.97904e-15 -1.02318e-15 1.7053e-15 -4.20641e-15 -1.36424e-15 3.60956e-15 1.92933e-15 -1.13687e-15 9.09495e-16 -1.93268e-15 9.89075e-15 -1.31877e-14 1.13687e-15 6.82121e-15 -7.50333e-15 -1.02602e-14 -9.00354e-15 4.20641e-15 8.98126e-15 -4.09273e-15 -1.13687e-15 2.04636e-15 1.81899e-15 4.54747e-15 -1.53477e-15 8.78231e-15 -1.80875e-14 -4.20641e-15 5.91172e-15 6.25278e-15 8.18545e-15 6.82121e-16 3.97904e-15 -2.84217e-16 -8.78231e-15 4.23483e-15 -1.17368e-14 4.66116e-15 5.45697e-15 -6.0254e-15 -1.36424e-15 2.50111e-15 6.82121e-16 5.74119e-15 1.93268e-15 4.50484e-15 4.22041e-15 1.93268e-15 -6.82121e-16 1.93268e-15 1.13687e-16 4.54747e-16 1.98952e-16 -5.3717e-15 1.15676e-14 -2.07478e-15 9.305e-15 -1.19371e-15 4.66116e-15 4.74643e-15 3.32534e-15 3.35376e-15 6.79279e-15 3.90799e-15 -1.8332e-15 -3.41061e-16 ******************* Computation finished at Wed Dec 29 00:34:06 2021 elapsed time: 0.0305631 A Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? Parallel 3D Discrete Cosine Transformation Implementation in Matlab and Operator overloading in Image class implementation in C++ What changes has been made in the code since last question? I am trying to implement 3D Discrete Cosine Transformation calculation in C++ in this post. Why a new review is being asked for? If there is any possible improvement, please let me know.
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: Here is what I noticed on a first viewing (of only the code of dct3 and dct3_detail, not the test code really). I haven't thought really about correctness or performance, just the things I noticed reading the code: dct3 and dct3_detail should not be static. Without very specific reasons, such as requiring different function pointers between translation units, there is no benefit to declaring a function template with internal linkage (i.e. static). It may even make the linker's work harder, since it forces it to consider instantiations with the same template arguments in different translation units as different functions. dct3 and dct3_detail should take the input parameter with type const std::vector<Image<ElementT>>& since they do not modify the input. With the current non-reference type, each call to these functions will make a complete copy of the input. In dct3: It is known up-front how large the output vector will be. Sufficient memory for that can be reserved up-front to avoid the reallocations which it would otherwise perform: output.reserve(input.size()); OutputT is not used at all. dct3_detail is called without specifying it and because it doesn't appear in its parameters, the call dct3_detail(input, i) will always use the default OutputT = ElementT. If this is unintended, you should explicitly specify the template argument in the call: dct3_detail<ElementT, OutputT>(input, i) Also note that you could simplify this to dct3_detail<OutputT>(input, i) if you swapped the template parameters of dct3_detail. I suppose in dct3 it should then also be std::vector<Image<OutputT>> output; and the two return types should also be fixed accordingly. The type of plane_index should be std::size_t. At least I see no reason for it to be anything else.
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 The type of plane_index should be std::size_t. At least I see no reason for it to be anything else. In std::size_t N3 = input.size(); you could also write auto N3 = input.size();. You seem to use the auto _ = declaration form everywhere else, so that would be more consistent. The same for OutputT alpha1 = . It seems very unlikely to me that any arithmetic type makes sense for OutputT. It seems to me, that OutputT should be constrained to floating type, i.e. std::floating_point or at least a non-floating-point type shouldn't be used in the intermediate steps of the calculation. (static_cast<OutputT>(1.0) / static_cast<OutputT>(std::sqrt(2))): C++ has a constant defined for sqrt(2) with highest possible precision for every floating point type and 1/sqrt(2) is just sqrt(2)/2, so assuming you followed point 7, you can use instead std::numbers::sqrt2_v<OutputT> / 2. static_cast<OutputT>(1.0) can be written simpler as OutputT{1.0} with the added benefit that this form is required to produce a diagnostic if the value in the braces cannot be represented in the OutputT type. It seems that you don't really access input in dct3_detail except as input[plane_index]. The only exception is input[0].getWidth(), but it appears that the result is required to be independent of the index anyway, right? If so, don't pass input and plane_index to dct3_detail. Just pass the element you currently want to use as a reference: constexpr Image<OutputT> dct3_detail(const Image<ElementT>& input_element) { // input[plane_index] -> input_element // input[0] -> input_element } //... for (auto& input_element : input) { output.push_back(dct3_detail(input_element)); } std::numbers::pi should probably be std::numbers::pi_v<OutputT> to match the precision of the requested output type.
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
c++, algorithm, c++20 In the test code the Image class is not constexpr friendly. It can never be used in a constexpr function. For templates this is not strictly checked, but because every specialization of dct3_detail and dct3 use Image, no specialization satisfies the constexpr conditions. Marking a function template with this property as constexpr anyway technically makes the program ill-formed, no diagnostic required. I suggest you either define Image in such a way that it can be used in constant expressions or you remove constexpr from the functions. std::cos is also not constexpr and for similar reasons as above, as long as you use it, you should not mark the functions constexpr. You are getting N1 and N2 twice, although my interpretation is that their values are fixed. You also seem to get them without type conversion multiple times in the loops. I would just get them once at the beginning of dct3_detail, once in unconverted form an once in converted form. It might be a performance benefit to get them even only once in the whole calculation.
{ "domain": "codereview.stackexchange", "id": 42675, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++20", "url": null }
javascript, array, react.js, factors Title: Exponentiate common factors with JavaScript Question: I've created a function that exponentiates common factors. I'd like to optimize/simplify it because, as you can see, it's very messy and not very performant function App() { return ( <View results={ [2, 2, 3, 8, 8, 8, 100] } //only an example ) } function View({ results }) { const defaultView = results.reduce((previous, current) => previous.includes(current) ? ((previous[previous.length - 1] = [current, 2]), previous) : previous.some(element => current === element[0]) ? (previous[previous.length - 1][1]++, previous) : [...previous, current], []).map((element, index) => <li key={`${index} : ${element}`}> { Array.isArray(element) ? <>{element[0]}<sup>{element[1]}</sup></> : element } </li> ) } thanks Answer: You can avoid the edge cases by uniformly using the format [data, count], rather than special casing the count-of-1 case. Your reduction will then look like this: arr = [2, 2, 3, 8, 8, 8, 100] arr.reduce( (m, x) => { const prev = m[m.length-1] return x == prev[0] ? (prev[1]++, m) : (m.push([x, 1]), m) }, [[]] ).slice(1) // [ [ 2, 2 ], [ 3, 1 ], [ 8, 3 ], [ 100, 1 ] ] Now in your view you can branch on "is the count > 1" rather than on "is it an array". Arguably, the ternary with side-effects inside using the comma operator is too clever, but it seemed like you were going for terseness. It easy enough to expand that out into a traditional if statement though. Also, you can reformat it into a 1-liner, but I prefer the clearer formatting at the expense of more lines.
{ "domain": "codereview.stackexchange", "id": 42676, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, array, react.js, factors", "url": null }
java, timer Title: Simple stop watch class Question: I've made a little library where I add some functionalities from time to time that I miss in the Java standard library. I am sad that the Java library for example has no stop watch class that allows me to measure time without the need to deal with details of a time library. When I write library functionalities, I have the following requirements to myself: Keep it simple, stupid. The code has to be on point and should only do what is really needed. The code has to be very readable, even if this leads to some more code lines. The task has to be solved efficiently. Memory and calculation time should not be wasted. If the standard library or other stuff like that is needed, only use stable, long-lasting and modern technologies, prioritized in this order. So this class was born. What do you think about it? Did I meet my own requirements? import java.time.Instant; import java.time.Duration; public class StopWatch { private Instant startDate; private Instant stopDate; public StopWatch() { reset(); } public void start() { if (startDate == null) { startDate = Instant.now(); } } public void stop() { if (stopDate == null && startDate != null) { stopDate = Instant.now(); } } public void reset() { startDate = null; stopDate = null; } public long getMilli() { if (startDate != null && stopDate != null) { Duration duration = Duration.between(startDate, stopDate); long nanos = duration.getSeconds() * 1000000000 + duration.getNano(); return nanos / 1000000; } return 0; } }
{ "domain": "codereview.stackexchange", "id": 42677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, timer", "url": null }
java, timer Purpose The code following now is not part of the code that should be reviewed. Some people wanted me to show the use case and that it is: I have a class thats objects calculate prime numbers. I want to measure how much time it needs to calculate these numbers, so therefore i need a stopwatch class for preventing overbloating my code with date-time-apis of my programming language. Main.java public class Main { public static void main(String[] args) throws Exception { StopWatch sw = new StopWatch(); sw.start(); PrimeNumberCalculator pnc = new PrimeNumberCalculator(); pnc.setCurrentNumber(10000); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { pnc.calculateNextPrime(); sb.append((i+1) + ";" + pnc.getCurrentPrimeNumber() + "\n"); } sw.stop(); System.out.println(sb.toString()); System.out.println(sw.getMilli()); } }
{ "domain": "codereview.stackexchange", "id": 42677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, timer", "url": null }
java, timer PrimeNumberCalculator.java public class PrimeNumberCalculator { private long currentNumber; private long currentPrimeNumber; public PrimeNumberCalculator(long currentNumber) { this.currentNumber = currentNumber; } public PrimeNumberCalculator() { this(3); currentPrimeNumber = 2; } public long getCurrentPrimeNumber() { return currentPrimeNumber; } public void setCurrentNumber(long currentNumber) { this.currentNumber = currentNumber; } public void calculateNextPrime() { boolean isPrime; do { isPrime = true; for (long i = 2; i < currentNumber; i++) { if (currentNumber % i == 0 && currentNumber != 2) { isPrime = false; break; } } if (isPrime) { currentPrimeNumber = currentNumber; } currentNumber++; } while (!isPrime); } } The class is also needed in my own Minesweeper implementation, where players can play against the time and be ranked in criterias of time needed. Answer: For a library class, JavaDocs should be given (well, here the interface is so small and well-named that one can easily guess the tasks of the methods, but anyway). As already said, the getMilli() method should be replaced with a getDuration() one. Your conversion to millis not only includes ugly computation code, but also cripples the available resolution. And if some user wants milliseconds, there's the Duration.toMillis() method.
{ "domain": "codereview.stackexchange", "id": 42677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, timer", "url": null }
c#, performance, multithreading Title: sum of array using multithreading Question: I implement sum element of array using multi threading but my question is when my program work with one thread the time is better than using 6 thread . I am using a CPU with 8 threads.What am I wrong public static int threadss = 7; public const int count = 1000000; public static List<int> a = new List<int>(); public static int numberofthreads; public static long[] sum=new long[threadss]; public static long total_sum=0; public static long part = 0; static void Main(string[] args) { Random r = new Random(); for (int i = 1; i <= count; i++) { a.Add(i); } numberofthreads = threadss; var watch = new System.Diagnostics.Stopwatch(); watch.Start(); Thread[] threadsarray = new Thread[numberofthreads]; List<Thread> threads = new List<Thread>(); for (int i = 0; i < numberofthreads; i++) { threadsarray[i] = new Thread(new ParameterizedThreadStart(myThreadMethod)); threadsarray[i].Start(i); } for (int i = 0; i < numberofthreads; i++) { threadsarray[i].Join(); } for(int i= 0; i < numberofthreads; i++) { total_sum += sum[i]; } watch.Stop(); Console.WriteLine("Time is " + watch.ElapsedMilliseconds.ToString()); Console.WriteLine("sum is "+ total_sum); } static void myThreadMethod(object threadid) { int thid = (int)threadid; for (int i = (thid * (a.Count / numberofthreads));i < (thid + 1) * a.Count / numberofthreads; i++) { sum[thid] += a[i]; } }
{ "domain": "codereview.stackexchange", "id": 42678, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, multithreading", "url": null }
c#, performance, multithreading Answer: Running your code in Release build after a tweak like i < count instead of i <= count and increased array size by 10 times, and assign 1 for each array element (needed for further comparison): Time is 177 sum is 10000000 Then I've made some changes public const int numberofthreads = 7; public const int count = 10000000; static void Main(string[] args) { int[] a = new int[count]; for (int i = 0; i < count; i++) { a[i] = 1; } var watch = new Stopwatch(); watch.Start(); long sum1 = ThreadSum(a); watch.Stop(); Console.WriteLine("Time is " + watch.ElapsedMilliseconds); Console.WriteLine("sum is " + sum1); Console.ReadKey(); } static long ThreadSum(int[] array) { long total_sum = 0; long[] sum = new long[numberofthreads]; Thread[] threadsarray = new Thread[numberofthreads]; for (int i = 0; i < numberofthreads; i++) { int tmp = i; threadsarray[i] = new Thread(() => MyThreadMethod(tmp, array, sum)); threadsarray[i].Start(); } for (int i = 0; i < numberofthreads; i++) { threadsarray[i].Join(); } for (int i = 0; i < numberofthreads; i++) { total_sum += sum[i]; } return total_sum; } static void MyThreadMethod(int threadid, int[] array, long[] sum) { int thid = threadid; for (int i = thid * (array.Length / numberofthreads); i < (thid + 1) * array.Length / numberofthreads; i++) { sum[thid] += array[i]; } } Time is 6 sum is 10000000
{ "domain": "codereview.stackexchange", "id": 42678, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, multithreading", "url": null }
c#, performance, multithreading Time is 6 sum is 10000000 Interesting. That's mostly faster because I'm using Array instead of List for the source data. Let's make some more optimisations like using pooled threads. static long ThreadSum(int[] array) { long total_sum = 0; long[] sum = new long[numberofthreads]; Task[] tasks = new Task[numberofthreads]; for (int i = 0; i < numberofthreads; i++) { int tmp = i; tasks[i] = Task.Run(() => MyThreadMethod(tmp, array, sum)); } Task.WaitAll(tasks); for (int i = 0; i < numberofthreads; i++) { total_sum += sum[i]; } return total_sum; } No progress Time is 6 sum is 10000000 ...because internal threading overhead here is the same. But in wide thread use i recommend Task.Run instead of new Thread. Ok, let's do that in the old way static long Sum(int[] array) { long sum = 0; for (int i = 1; i < count; i++) { sum += array[i]; } return sum; } Time is 5 sum is 10000000 One thread is almost faster than 7 threads. :) That's because of the same threading overhead. Creating thread is expensive operation. But what about SIMD? static long SimdSum(int[] array) { Vector<int> sumVector = Vector<int>.Zero; ReadOnlySpan<Vector<int>> vectors = MemoryMarshal.Cast<int, Vector<int>>(array); for (int i = 0; i < vectors.Length; i++) { sumVector += vectors[i]; } long sum = Vector.Dot(sumVector, Vector<int>.One); for (int i = array.Length - array.Length % Vector<int>.Count; i < array.Length; i++) { sum += array[i]; } return sum; } My Vector<int> length is 8, then it works like 8 threads but on one thread because SIMD instruction calculates 8 ints at once. Time is 2 sum is 10000000
{ "domain": "codereview.stackexchange", "id": 42678, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, multithreading", "url": null }
c#, performance, multithreading Looks like it the fastest for now. Probably there's more ways to optimize that but I think, that's enough. The main issue that threading here isn't effective because computation time for the each Thread is too small. Also, I suggest to say hello to Benchmark.NET, it can measure methods performance more accurately.
{ "domain": "codereview.stackexchange", "id": 42678, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, multithreading", "url": null }
python, template, tkinter, gui, factory-method Title: Python - Tkinter - periodic table of chemical elements Question: Inspired by a question on StackOverflow I decided to code a GUI that is simple, efficent and can be used in other projects as well. I wanted to share this code since it probably is usefull to other people as well. You may want to share some practical hints how to make this code even better. The code produces a table of frames and shows the information, I did gather for about 5 hours from wikipedia, in the final output. The frames are made clickable to make the usecase wider then without. I hope you enjoy this bit of code. Database: symbols = ['H','He','Li','Be','B','C','N','O','F','Ne', 'Na','Mg','Al','Si','P','S','Cl','Ar','K', 'Ca', 'Sc', 'Ti', 'V','Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe','Cs', 'Ba','La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh','Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'] keywords =['name','index','elementkategorie','gruppe','periode','block', 'atommasse','aggregatzustand','dichte','elektronegativität']
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method values = [['Wasserstoff',1,'Nichtmetalle',1,1,'s',1.01,'gasförmig',0.08,2.2],#H ['Helium',2,'Edelgase',18,1,'s',4.00,'gasförmig',0.18,'n.A'],#He ['Lithium',3,'Alkalimetalle',1,2,'s',6.94,'fest',0.53,0.98],#Li ['Beryllium',4,'Erdalkalimetalle',2,2,'s',9.01,'fest',1.84,1.57],#Be ['Bor',5,'Halbmetalle',13,2,'p',10.81,'fest',2.46,2.04],#B ['Kohlenstoff',6,'Nichtmetalle',14,2,'p',12.01,'fest',2.26,2.55],#C ['Stickstoff',7,'Nichtmetalle',15,2,'p',14.00,'gasförmig',1.17,3.04],#N ['Sauerstoff',8,'Nichtmetalle',16,2,'p',15.99,'gasförmig',1.43,3.44],#O ['Fluor',9,'Halogene',17,2,'p',18.99,'gasförmig',1.70,3.98],#F ['Neon',10,'Edelgase',18,2,'p',20.17,'gasförmig',0.90,'n.A'],#Ne ['Natrium',11,'Alkalimetalle',1,3,'s',22.99,'fest',0.97,0.93],#Na ['Magnesium',12,'Erdalkalimetalle',2,3,'s',24.31,'fest',1.74,1.31],#Mg ['Aluminium',13,'Metalle',13,3,'p',26.98,'fest',2.69,1.61],#Al ['Silicium',14,'Halbmetalle',14,3,'p',28.08,'fest',2.34,1.90],#Si ['Phosphor',15,'Nichtmetalle',15,3,'p',30.97,'fest',2.4,2.19],#P ['Schwefel',16,'Nichtmetalle',16,3,'p',32.06,'fest',2.07,2.58],#S ['Chlor',17,'Halogene',17,3,'p',35.45,'gasförmig',3.22,3.16],#Cl ['Argon',18,'Edelgase',18,3,'p',39.95,'gasförmig',1.78,'n.A'],#Ar ['Kalium',19,'Alkalimetalle',1,4,'s',39.09,'fest',0.86,0.82],#K ['Calicium',20,'Erdalkalimetalle',2,4,'s',40.08,'fest',1.55,1.00],#Ca ['Scandium',21,'Übergangsmetalle',3,4,'d',44.96,'fest',2.99,1.36],#Sc ['Titan',22,'Übergangsmetalle',4,4,'d',47.87,'fest',4.5,1.54],#Ti ['Vandium',23,'Übergangsmetalle',5,4,'d',50.94,'fest',6.11,1.63],#V ['Chrom',24,'Übergangsmetalle',6,4,'d',51.99,'fest',7.14,1.66],#Cr ['Mangan',25,'Übergangsmetalle',7,4,'d',54.94,'fest',7.43,1.55],#Mn
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Mangan',25,'Übergangsmetalle',7,4,'d',54.94,'fest',7.43,1.55],#Mn ['Eisen',26,'Übergangsmetalle',8,4,'d',55.85,'fest',7.87,1.83],#Fe ['Cobalt',27,'Übergangsmetalle',9,4,'d',58.93,'fest',8.90,1.88],#Co ['Nickel',28,'Übergangsmetalle',10,4,'d',58.69,'fest',8.90,1.91],#Ni ['Kupfer',29,'Übergangsmetalle',11,4,'d',63.54,'fest',8.92,1.90],#Cu ['Zink',30,'Übergangsmetalle',12,4,'d',65.38,'fest',7.14,1.65],#Zn ['Gallium',31,'Metalle',13,4,'p',69.72,'fest',5.90,1.81],#Ga ['Germanium',32,'Halbmetalle',14,4,'p',72.63,'fest',5.32,2.01],#Ge ['Arsen',33,'Halbmetalle',15,4,'p',74.92,'fest',5.73,2.18],#As ['Selen',34,'Halbmetalle',16,4,'p',78.97,'fest',4.82,2.55],#Se ['Brom',35,'Halogene',17,4,'p',79.90,'flüssig',3.12,2.96],#Br ['Krypton',36,'Edelgase',18,4,'p',83.80,'gasförmig',3.75,3.00],#Kr ['Rubidium',37,'Alkalimetalle',1,5,'s',85.47,'fest',1.53,0.82],#Rb ['Strontium',38,'Erdalkalimetalle',2,5,'s',87.62,'fest',2.63,0.95],#Sr ['Yttrium',39,'Übergangsmetalle',3,5,'d',88.91,'fest',4.47,1.22],#Y ['Zirconium',40,'Übergangsmetalle',4,5,'d',91.22,'fest',6.50,1.33],#Zr ['Niob',41,'Übergangsmetalle',5,5,'d',92.90,'fest',8.57,1.6],#Nb ['Molybdän',42,'Übergangsmetalle',6,5,'d',95.95,'fest',10.28,2.16],#Mo ['Technetium',43,'Übergangsmetalle',7,5,'d',98.90,'fest',11.5,1.9],#Tc ['Ruthenium',44,'Übergangsmetalle',8,5,'d',101.07,'fest',12.37,2.2],#Ru ['Rhodium',45,'Übergangsmetalle',9,5,'d',102.90,'fest',12.38,2.28],#Rh ['Palladium',46,'Übergangsmetalle',10,5,'d',106.42,'fest',11.99,2.20],#Pd ['Silber',47,'Übergangsmetalle',11,5,'d',107.87,'fest',10.49,1.93],#Ag ['cadmium',48,'Übergangsmetalle',12,5,'d',112.41,'fest',8.65,1.69],#Cd ['Indium',49,'Metalle',13,5,'p',114.82,'fest',7.31,1.78],#In
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Indium',49,'Metalle',13,5,'p',114.82,'fest',7.31,1.78],#In ['Zinn',50,'Metalle',14,5,'p',118.71,'fest',5.77,1.96],#Sn ['Antimon',51,'Halbmetalle',15,5,'p',121.76,'fest',6.70,2.05],#Sb ['Tellur',52,'Halbmetalle',16,5,'p',127.60,'fest',6.24,2.10],#Te ['Iod',53,'Halogene',17,5,'p',126.90,'fest',4.94,2.66],#I ['Xenon',54,'Edelgase',18,5,'p',131.29,'gasförmig',5.90,2.6],#Xe ['Caesium',55,'Alkalimetalle',1,6,'s',132.91,'fest',1.90,0.79],#Cs ['Barium',56,'Erdalkalimetalle',2,6,'s',137.33,'fest',3.62,0.89],#Ba ['Lanthan',57,'Übergangsmetalle',3,6,'d',138.90,'fest',6.17,1.1],#La ['Cer',58,'Lanthanoide','La',6,'f',140.12,'fest',6.77,1.12],#Ce ['Praseodym',59,'Lanthanoide','La',6,'f',140.91,'fest',6.48,1.13],#Pr ['Neodym',60,'Lanthanoide','La',6,'f',144.24,'fest',7.00,1.14],#Nd ['Promethium',61,'Lanthanoide','La',6,'f',146.91,'fest',7.2,'n.A.'],#Pm ['Samarium',62,'Lanthanoide','La',6,'f',150.36,'fest',7.54,1.17],#Sm ['Europium',63,'Lanthanoide','La',6,'f',151.96,'fest',5.25,'n.A'],#Eu ['Gadolinium',64,'Lanthanoide','La',6,'f',157.25,'fest',7.89,1.20],#Gd ['Terbium',65,'Lanthanoide','La',6,'f',158.93,'fest',8.25,'n.A'],#Tb ['Dysprosium',66,'Lanthanoide','La',6,'f',162.50,'fest',8.56,1.22],#Dy ['Holmium',67,'Lanthanoide','La',6,'f',164.93,'fest',8.78,1.23],#Ho ['Erbium',68,'Lanthanoide','La',6,'f',167.26,'fest',9.05,1.24],#Er ['Thulium',69,'Lanthanoide','La',6,'f',168.93,'fest',9.32,1.25],#Tm ['Ytterbium',70,'Lanthanoide','La',6,'f',173.05,'fest',6.97,'n.A'],#Yb ['Lutetium',71,'Lanthanoide','La',6,'f',174.97,'fest',9.84,1.27],#Lu ['Hafnium',72,'Übergangsmetalle',4,6,'d',178.49,'fest',13.28,1.3],#Hf ['Tantal',73,'Übergangsmetalle',5,6,'d',180.95,'fest',16.65,1.5],#Ta
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Tantal',73,'Übergangsmetalle',5,6,'d',180.95,'fest',16.65,1.5],#Ta ['Wolfram',74,'Übergangsmetalle',6,6,'d',183.84,'fest',19.25,2.36],#W ['Rhenium',75,'Übergangsmetalle',7,6,'d',186.21,'fest',21.00,1.9],#Re ['Osmium',76,'Übergangsmetalle',8,6,'d',190.23,'fest',22.59,2.2],#Os ['Irdium',77,'Übergangsmetalle',9,6,'d',192.22,'fest',22.56,2.2],#Ir
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Platin',78,'Übergangsmetalle',10,6,'d',195.08,'fest',21.45,2.2],#Pt ['Gold',79,'Übergangsmetalle',11,6,'d',196.97,'fest',19.32,2.54],#Au ['Quecksilber',80,'Übergangsmetalle',12,6,'d',200.59,'flüssig',13.55,2.00],#Hg ['Thalium',81,'Metalle',13,6,'p',204.38,'fest',11.85,1.62],#Tl ['Blei',82,'Metalle',14,6,'p',207.20,'fest',11.34,2.33],#Pb ['Bismut',83,'Metalle',15,6,'p',208.98,'fest',9.78,2.02],#Bi ['Polonium',84,'Metalle',16,6,'p',209.98,'fest',9.20,2.0],#Po ['Astat',85,'Halogene',17,6,'p',209.99,'fest','n.A',2.2],#At ['Radon',86,'Edelgase',18,6,'p',222.00,'gasförmig',9.73,'n.A'],#Rn
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Francium',87,'Alkalimetalle',1,7,'s',223.02,'fest','n.A',0.7],#Fr ['Radium',88,'Erdalkalimetalle',2,7,'s',226.03,'fest',5.5,0.9],#Ra ['Actinium',89,'Übergangsmetalle',3,7,'d',227.03,'fest',10.07,1.1],#Ac ['Thorium',90,'Actinoide','Ac',7,'f',232.04,'fest',11.72,1.3],#Th ['Protactinium',91,'Actinoide','Ac',7,'f',231.04,'fest',15.37,1.5],#Pa ['Uran',92,'Actinoide','Ac',7,'f',238.03,'fest',19.16,1.38],#U ['Neptunium',93,'Actinoide','Ac',7,'f',237.05,'fest',20.45,1.36],#Np ['Plutonium',94,'Actinoide','Ac',7,'f',244.06,'fest',19.82,1.28],#Pu ['Americium',95,'Actinoide','Ac',7,'f',243.06,'fest',13.67,1.3],#Am ['Curium',96,'Actinoide','Ac',7,'f',247.07,'fest',13.51,1.3],#Cm ['Berkelium',97,'Actinoide','Ac',7,'f',247,'fest',14.78,1.3],#Bk ['Californium',98,'Actinoide','Ac',7,'f',251,'fest',15.1,1.3],#Cf ['Einsteinium',99,'Actinoide','Ac',7,'f',252,'fest',8.84,'n.A'],#Es ['Fermium',100,'Actinoide','Ac',7,'f',257.10,'fest','n.A','n.A'],#Fm ['Medelevium',101,'Actinoide','Ac',7,'f',258,'fest','n.A','n.A'],#Md ['Nobelium',102,'Actinoide','Ac',7,'f',259,'fest','n.A.','n.A'],#No ['Lawrencium',103,'Actinoide','Ac',7,'f',266,'fest','n.A','n.A'],#Lr ['Rutherdordium',104,'Übergangsmetalle',4,7,'d',261.11,'fest',17.00,'n.A'],#Rf ['Dubnium',105,'Übergangsmetalle',5,7,'d',262.11,'n.A','n.A','n.A'],#Db ['Seaborgium',106,'Übergangsmetalle',6,7,'d',263.12,'n.A','n.A','n.A'],#Sg ['Bohrium',107,'Übergangsmetalle',7,7,'d',262.12,'n.A','n.A','n.A'],#Bh ['Hassium',108,'Übergangsmetalle',8,7,'d',265,'n.A','n.A','n.A'],#Hs ['Meitnerium',109,'Unbekannt',9,7,'d',268,'n.A','n.A','n.A'],#Mt ['Darmstadtium',110,'Unbekannt',10,7,'d',281,'n.A','n.A','n.A'],#Ds ['Roentgenium',111,'Unbekannt',11,7,'d',280,'n.A','n.A','n.A'],#Rg
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Roentgenium',111,'Unbekannt',11,7,'d',280,'n.A','n.A','n.A'],#Rg ['Copernicium',112,'Unbekannt',12,7,'d',277,'n.A','n.A','n.A'],#Cn
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method ['Nihonium',113,'Unbekannt',13,7,'p',287,'n.A','n.A','n.A'],#Nh ['Flerovium',114,'Unbekannt',14,7,'p',289,'n.A','n.A','n.A'],#Fl ['Moscovium',115,'Unbekannt',15,7,'p',288,'n.A','n.A','n.A'],#Mc ['Livermorium',116,'Unbekannt',16,7,'p',293,'n.A','n.A','n.A'],#Lv ['Tenness',117,'Unbekannt',17,7,'p',292,'n.A','n.A','n.A'],#Ts ['Oganesson',118,'Unbekannt',18,7,'p',294,'fest',6.6,'n.A']#Og ] kategorie_farben = {'Alkalimetalle' : '#fe6f61', 'Erdalkalimetalle':'#6791a7', 'Übergangsmetalle':'#83b8d0', 'Metalle':'#cae2ed', 'Halbmetalle':'#a7d6bc', 'Nichtmetalle':'#ffde66', 'Halogene':'#e9aa63', 'Edelgase':'#e29136', 'Unbekannt':'#cec0bf', 'Lanthanoide':'#696071', 'Actinoide':'#5b4c68'} Code: import tkinter as tk root = tk.Tk() class Element(tk.Frame): la_offset = 2;ac_offset=2;offset=2 def __init__(self,master,symbol,**kwargs): tk.Frame.__init__(self,master, relief = 'raised') self.kwargs = kwargs self.command= kwargs.pop('command', lambda:print('No command')) self.WIDTH,self.HEIGHT,self.BD = 100,100,3 self.CMP = self.BD*2 bg = kategorie_farben.get(kwargs.get('elementkategorie')) self.configure(width=self.WIDTH,height=self.HEIGHT,bd=self.BD, bg=bg) self.grid_propagate(0) self.idx = tk.Label(self,text=kwargs.get('index'),bg=bg) self.u = tk.Label(self,text=kwargs.get('atommasse'),bg=bg)
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method self.name = tk.Label(self,text=kwargs.get('name'),bg=bg) self.symb = tk.Label(self,text=symbol,font=('bold'),fg=self.get_fg(),bg=bg) self.e = tk.Label(self,text=kwargs.get('elektronegativität'),bg=bg) self.d = tk.Label(self,text=kwargs.get('dichte'),bg=bg) self.grid_columnconfigure(1, weight=2) self.grid_rowconfigure(1, weight=2) self.idx.grid(row=0,column=0,sticky='w') self.u.grid(row=0,column=2,sticky='e') mid_x = self.WIDTH/2-self.name.winfo_reqwidth()/2 mid_y = self.HEIGHT/2-self.name.winfo_reqheight()/2 offset= 15 self.name.place(in_=self,x=mid_x-self.CMP,y=mid_y-self.CMP+offset) mid_x = self.WIDTH/2-self.symb.winfo_reqwidth()/2 mid_y = self.HEIGHT/2-self.symb.winfo_reqheight()/2 self.symb.place(in_=self,x=mid_x-self.CMP,y=mid_y-self.CMP-offset/2) self.e.grid(row=2,column=0,sticky='w') self.d.grid(row=2,column=2,sticky='e')
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method r,c = kwargs.pop('periode'),kwargs.pop('gruppe') if c in ('La','Ac'): if c == 'La': c =Element.la_offset+Element.offset;Element.la_offset +=1 r += self.offset if c == 'Ac': c =Element.ac_offset+Element.offset;Element.ac_offset +=1 r += Element.offset self.grid(row=r,column=c,sticky='nswe') self.bind('<Enter>', self.in_active) self.bind('<Leave>', self.in_active) self.bind('<ButtonPress-1>', self.indicate) self.bind('<ButtonRelease-1>', self.execute) [child.bind('<ButtonPress-1>', self.indicate) for child in self.winfo_children()] [child.bind('<ButtonRelease-1>', self.execute) for child in self.winfo_children()] def in_active(self,event): if str(event.type) == 'Enter': self.flag = True if str(event.type) == 'Leave': self.flag = False;self.configure(relief='raised') def indicate(self,event): self.configure(relief='sunken') def execute(self,event): if self.flag: self.command();self.configure(relief='raised') else: self.configure(relief='raised') def get_fg(self): if self.kwargs.get('aggregatzustand') == 'fest': return 'black' if self.kwargs.get('aggregatzustand') == 'flüssig': return 'blue' if self.kwargs.get('aggregatzustand') == 'gasförmig': return 'red' if self.kwargs.get('aggregatzustand') == 'n.A': return 'grey' def test(): print('testing..') for idx,symbol in enumerate(symbols): kwargs = {} for k,v in zip(keywords,values[idx]): kwargs.update({k:v}) Element(root,symbol,command=test,**kwargs) root.mainloop() Answer: I hope you enjoy this bit of code.
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method I did! Your symbols, keywords and values should have capitalised variable names since they're global constants. However, life would be easier if your symbols were integrated into your values, and keywords prepended with symbol. Even better: none of this actually belongs in your code, and should be cut out to a database file. JSON is easiest but there are others; for instance CSV would be higher-density (but has weaker typing). You have not enough German in some parts, and too much German in others. Your localised data (e.g. Stickstoff) are fine. Schema (e.g. elementkategorie) and code (e.g. kategorie_farben) should not be localised and should be in English. Your floating-point rendering should use localised formats; in your case it will turn your decimal point into a comma. Don't write n.A in your database; use None and convert that to a string on render. Don't store root in the global namespace. Don't leave **kwargs as a dictionary; instead make a simple @dataclass or named tuple. Don't over-abbreviate variables like BD which should be BORDER. Likewise, over-abbreviated tk keyword arguments like bg have a full-form background which should be used instead. Rather than strings like e, prefer constants in tk like tk.E. Your if c in ('La','Ac'): is redundant and can be deleted. Your flag, <Enter> and <Leave> aren't doing anything so in my suggested code I deleted them. Refactor your get_fg to be a dictionary lookup. Prefer the "has-a" pattern over the "is-a" pattern for your element frame class; in other words, instantiate a frame instead of inheriting one. Consider adding a (German!) title to your window. Factor out your creation of a middle-placed label for name and symbol to a function. Better yet: don't call place, and just represent your name and symbol labels as rows within the grid that span the width of the grid and are sticky to both east and west. Consider resizing your chart to the window by use of a container frame and pack_configure.
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method Consider resizing your chart to the window by use of a container frame and pack_configure. You should name all of your widgets. If you don't, a name will be generated for you internally and this will make debugging more difficult. Your element grid coordinate calculations are non-reentrant and can be performed only once per process run, since your offset variables are stored as statics. You should refactor this; the nicest way is an iterator function that keeps these offsets as locals and throws them away once all elements have been placed. Rather than binding your mouse events to all children of your element frame, consider just calling a bindtags to pass all events from the child labels to the parent frame. Typo: it's "rutherfordium".
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method I thought about calling the according wikipedia site
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method This is easy via webbrowser. Suggested elements.json [ { "symbol": "H", "name": "Wasserstoff", "number": 1, "category": "Nichtmetalle", "group": 1, "period": 1, "block": "s", "mass": 1.01, "phase": "gasförmig", "density": 0.08, "electronegativity": 2.2 }, { "symbol": "He", "name": "Helium", "number": 2, "category": "Edelgase", "group": 18, "period": 1, "block": "s", "mass": 4.0, "phase": "gasförmig", "density": 0.18, "electronegativity": null }, { "symbol": "Li", "name": "Lithium", "number": 3, "category": "Alkalimetalle", "group": 1, "period": 2, "block": "s", "mass": 6.94, "phase": "fest", "density": 0.53, "electronegativity": 0.98 }, { "symbol": "Be", "name": "Beryllium", "number": 4, "category": "Erdalkalimetalle", "group": 2, "period": 2, "block": "s", "mass": 9.01, "phase": "fest", "density": 1.84, "electronegativity": 1.57 }, { "symbol": "B", "name": "Bor", "number": 5, "category": "Halbmetalle", "group": 13, "period": 2, "block": "p", "mass": 10.81, "phase": "fest", "density": 2.46, "electronegativity": 2.04 }, { "symbol": "C", "name": "Kohlenstoff", "number": 6, "category": "Nichtmetalle", "group": 14, "period": 2, "block": "p", "mass": 12.01, "phase": "fest", "density": 2.26, "electronegativity": 2.55 }, { "symbol": "N", "name": "Stickstoff", "number": 7, "category": "Nichtmetalle", "group": 15, "period": 2, "block": "p", "mass": 14.0, "phase": "gasförmig", "density": 1.17, "electronegativity": 3.04 }, { "symbol": "O", "name": "Sauerstoff", "number": 8, "category": "Nichtmetalle", "group": 16, "period": 2, "block": "p", "mass": 15.99, "phase": "gasförmig", "density": 1.43,
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }
python, template, tkinter, gui, factory-method "period": 2, "block": "p", "mass": 15.99, "phase": "gasförmig", "density": 1.43, "electronegativity": 3.44 }, { "symbol": "F", "name": "Fluor", "number": 9, "category": "Halogene", "group": 17, "period": 2, "block": "p", "mass": 18.99, "phase": "gasförmig", "density": 1.7, "electronegativity": 3.98 }, { "symbol": "Ne", "name": "Neon", "number": 10, "category": "Edelgase", "group": 18, "period": 2, "block": "p", "mass": 20.17, "phase": "gasförmig", "density": 0.9, "electronegativity": null }, { "symbol": "Na", "name": "Natrium", "number": 11, "category": "Alkalimetalle", "group": 1, "period": 3, "block": "s", "mass": 22.99, "phase": "fest", "density": 0.97, "electronegativity": 0.93 }, { "symbol": "Mg", "name": "Magnesium", "number": 12, "category": "Erdalkalimetalle", "group": 2, "period": 3, "block": "s", "mass": 24.31, "phase": "fest", "density": 1.74, "electronegativity": 1.31 }, { "symbol": "Al", "name": "Aluminium", "number": 13, "category": "Metalle", "group": 13, "period": 3, "block": "p", "mass": 26.98, "phase": "fest", "density": 2.69, "electronegativity": 1.61 }, { "symbol": "Si", "name": "Silicium", "number": 14, "category": "Halbmetalle", "group": 14, "period": 3, "block": "p", "mass": 28.08, "phase": "fest", "density": 2.34, "electronegativity": 1.9 }, { "symbol": "P", "name": "Phosphor", "number": 15, "category": "Nichtmetalle", "group": 15, "period": 3, "block": "p", "mass": 30.97, "phase": "fest", "density": 2.4, "electronegativity": 2.19 }, { "symbol": "S", "name": "Schwefel", "number": 16, "category": "Nichtmetalle", "group": 16, "period": 3, "block": "p",
{ "domain": "codereview.stackexchange", "id": 42679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, template, tkinter, gui, factory-method", "url": null }