text
stringlengths
1
2.12k
source
dict
java, beginner, snake-game, javafx public class GameBoard extends Pane { private final SnakeGame GAME; private final int TILE_SIZE; private final int TILES_IN_ROW; private final int TILES_IN_COLUMN; private final int ROW_SIZE; private final int COLUMN_SIZE; private final int TOTAL_TILES; private ArrayList<Point2D> emptyTiles; private final Snake SNAKE; private final Fruit FRUIT; private int dX; private int dY; public GameBoard(SnakeGame game, int tileSize, int tilesInRow, int tilesInColumn) { GAME = game; TILE_SIZE = tileSize; TILES_IN_ROW = tilesInRow; TILES_IN_COLUMN = tilesInColumn; ROW_SIZE = TILE_SIZE * TILES_IN_ROW; COLUMN_SIZE = TILE_SIZE * TILES_IN_COLUMN; TOTAL_TILES = TILES_IN_ROW * TILES_IN_COLUMN; setPrefSize(ROW_SIZE, COLUMN_SIZE); SNAKE = new Snake(this, TILE_SIZE, 3, Color.GREENYELLOW); FRUIT = new Fruit(TILE_SIZE, Color.RED); getChildren().add(FRUIT); setGameBoard(); } public void setGameBoard() { dY = TILE_SIZE; emptyTiles = createEmptyTilesList(); SNAKE.setEmptyTiles(emptyTiles); FRUIT.setEmptyTiles(emptyTiles); SNAKE.generateSnake(); FRUIT.spawnFruit(); } public void resetGameBoard() { dX = 0; dY = 0; getChildren().removeAll(SNAKE); SNAKE.clear(); setGameBoard(); } public ArrayList<Point2D> createEmptyTilesList() { ArrayList<Point2D> emptyTiles = new ArrayList<>(); for (int tile = 1, x = 0, y = 0; tile <= TOTAL_TILES; tile++) { emptyTiles.add(new Point2D(x, y)); x += TILE_SIZE; if (tile % TILES_IN_ROW == 0) { x = 0; y += TILE_SIZE; } } return emptyTiles; } public boolean isDirectionValid() {
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx } return emptyTiles; } public boolean isDirectionValid() { //the snake shouldn't move in the opposite direction return GAME.getKeyX() + dX != 0 && GAME.getKeyY() + dY != 0; } public boolean ateFruit() { Rectangle head = SNAKE.getSnakeHead(); return head.getX() == FRUIT.getX() && head.getY() == FRUIT.getY(); } public boolean willHitWall() { Rectangle head = SNAKE.getSnakeHead(); return head.getX() + dX < 0 || head.getX() + dX >= this.getWidth() || head.getY() + dY < 0 || head.getY() + dY >= this.getHeight(); } public boolean willHitBody() { Rectangle head = SNAKE.getSnakeHead(); for (Rectangle body : SNAKE) { if (head.getX() + dX == body.getX() && head.getY() + dY == body.getY()) return true; } return false; } class SnakeMovement extends TimerTask {
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx @Override public void run() { Platform.runLater(() -> { if (isDirectionValid()) { dX = GAME.getKeyX(); dY = GAME.getKeyY(); } if (ateFruit()) { FRUIT.spawnFruit(); SNAKE.addHead(); GAME.increaseScore(); } if (willHitWall() || willHitBody()) { GAME.endGame(); return; } SNAKE.moveSnake(dX, dY); }); } } }
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx Snake.java import java.util.ArrayList; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class Snake extends ArrayList<Rectangle> { private final int SNAKE_BLOCK_SIZE; private final int SNAKE_INITIAL_LENGTH; private final Color SNAKE_COLOR; private final GameBoard GAME_BOARD; private ArrayList<Point2D> emptyTiles; public Snake(GameBoard gameBoard, int snakeBlockSize, int snakeInitialLength, Color snakeColor) { GAME_BOARD = gameBoard; SNAKE_BLOCK_SIZE = snakeBlockSize; SNAKE_INITIAL_LENGTH = snakeInitialLength; SNAKE_COLOR = snakeColor; } public Rectangle createBodyPart() { Rectangle body = new Rectangle(SNAKE_BLOCK_SIZE, SNAKE_BLOCK_SIZE, SNAKE_COLOR); GAME_BOARD.getChildren().add(body); return body; } public void generateSnake() { for (int tile = SNAKE_INITIAL_LENGTH - 1; tile >= 0; tile--) { Rectangle body = createBodyPart(); int startX = (int)GAME_BOARD.getPrefWidth() / 2; //0 is the head and 2 is the tail, if snake's initial length is 3, //startY will be 40, 20, and 0, for elements 0, 1, and 2 respectively //since the snake is moving downward int startY = tile * SNAKE_BLOCK_SIZE; body.setX(startX); body.setY(startY); emptyTiles.remove(new Point2D(startX, startY)); add(body); } } public void moveSnake(int dX, int dY) { Rectangle head = getSnakeHead(); boolean isHeadAdded = head.getX() == get(1).getX() && head.getY() == get(1).getY(); double oldX = head.getX();
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx double oldX = head.getX(); double oldY = head.getY(); double newX = oldX + dX; double newY = oldY + dY; head.setX(newX); head.setY(newY); //the head now occupies this tile emptyTiles.remove(new Point2D(newX, newY)); //when a new head is added, the rest of the body stays still for one task //so there is no need to go through the loop, and the tail's place shouldn't //be added to emptyTiles if (isHeadAdded) { return; } for (int i = 1; i < size(); i++) { Rectangle body = get(i); double currentX = body.getX(); double currentY = body.getY(); body.setX(oldX); body.setY(oldY); oldX = currentX; oldY = currentY; } //the old tile of the tail is now empty emptyTiles.add(new Point2D(oldX, oldY)); } public void addHead() { Rectangle oldHead = getSnakeHead(); Rectangle newHead = createBodyPart(); //the new head is set on the same tile as the old head initially //but it will be moved in the moveSnake method afterwards newHead.setX(oldHead.getX()); newHead.setY(oldHead.getY()); setSnakeHead(newHead); } public Rectangle getSnakeHead() { return get(0); } public void setSnakeHead(Rectangle newHead) { add(0, newHead); } public void setEmptyTiles(ArrayList<Point2D> emptyTiles) { this.emptyTiles = emptyTiles; } }
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx Fruit.java import java.util.ArrayList; import java.util.Random; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class Fruit extends Rectangle { private ArrayList<Point2D> emptyTiles; public Fruit(int blockSize, Color color) { super(blockSize, blockSize, color); } public Point2D generateRandomTile() { Random random = new Random(); int randomIndex = random.nextInt(emptyTiles.size()); return emptyTiles.get(randomIndex); } public void spawnFruit() { Point2D randomTile = generateRandomTile(); this.setX(randomTile.getX()); this.setY(randomTile.getY()); } public void setEmptyTiles(ArrayList<Point2D> emptyTiles) { this.emptyTiles = emptyTiles; } } snake_game.css #root { -fx-background-color: black; } #scoreBar { -fx-alignment: center; -fx-padding: 10px; -fx-border-style: solid; -fx-border-width: 0px 0px 2px 0px; -fx-border-color: white; } #scoreIndicator { -fx-text-fill: white; -fx-font-size: 15px; -fx-font-family: monospace; } #replay { -fx-background-color: transparent; -fx-text-fill: white; -fx-font-size: 15px; -fx-font-family: monospace; } Answer: On originally writing this answer I had ignored your CSS because you hadn't yet included it. You should be using your own package declarations. Many more of your class members should be final. I think GAME_BOARD should just be gameBoard; in fact the only variable in the entire application that currently merits all-caps is TILE_SIZE. TILE_SIZE should be made a static. This is personal preference, but I prefer one-type many-declarations instead of many-type many-declarations, as in private int keyX, keyY;
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx But those aren't really keys, right? They're direction deltas, so should be renamed. They should also not have duplicated state between your game and board classes. Given that your board concerns itself with game coordinates, I think these are best left to the board class and removed from the game class. Rather than the game class offering getKey methods, it would call setDirection on the board as appropriate. The game class has no constructor, which makes it impossible to make many things final. Much of your initialisation currently in start can be moved to a default constructor. Don't pass Score: 0 to your label upon creation; do that in one place only, called for both initialisation and updates. Your setId calls aren't strictly necessary. Passing TILE_SIZE to your GameBoard class smells of a problem. You are conflating display/screen coordinates with game/scene coordinates. You should have your inner game logic assume that one distance unit equals one tile, and then change your projection by making your own Camera and applying it to a board-only subscene. Among other things, this will simplify your takeInput by making all delta values either -1, 0, or 1. System.exit is the nuclear option, and you should probably prefer the JavaFX-specific Platform.exit instead. startGame and restartGame should really just be the same thing. GameBoard should be disposable; i.e. on every game reset you should be able to throw this instance away. To be able to do this, the pane object will need to persist, initialised and passed in from the game class. One way to represent removal of child widgets from this pane on reset is to implement AutoCloseable. setGameBoard and resetGameBoard should just be folded into the constructor.
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx setGameBoard and resetGameBoard should just be folded into the constructor. createEmptyTilesList is more complicated than it needs to be - you can just have a nested iteration over y and x; no need for modular math. Also, it would benefit you to represent this collection as a set instead of a list, especially if you leverage it for collision detection. Doing so would avoid the gymnastics of boundary comparison and body part iteration, and would use one set membership check. The management and updating of this empty-tiles set should be pulled away from the snake and fruit classes and owned by GameBoard. You should not use a lambda in runLater. Move that to a separate member function. Often you'll want to follow the has-a pattern instead of is-a pattern, i.e. the snake class "has a" collection of body parts, and not "is a" collection of body parts. This helps with coupling. This algorithm: for (int i = 1; i < size(); i++) { Rectangle body = get(i); double currentX = body.getX(); double currentY = body.getY(); body.setX(oldX); body.setY(oldY); oldX = currentX; oldY = currentY; }
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx is not efficient - you're moving every single body segment. Instead, you should be able to re-interpret the snake's body part collection as a queue, and only change the beginning and end. I leave this as an exercise to you. Suggested SnakeGame.java package com.stackexchange.snake; import java.util.Timer; import java.util.TimerTask; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Camera; import javafx.scene.ParallelCamera; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.stage.Stage; public class SnakeGame extends Application { private static final int TILE_SIZE = 20, ROWS = 25, COLUMNS = 30; private final BorderPane root = new BorderPane(); private final Pane boardPane = new Pane(); private final Label scoreIndicator = new Label(); private final Button replay = new Button("Replay"); // (Re)assigned on reset private Timer timer; private GameBoard gameBoard; private int score; public SnakeGame() { replay.setOnAction(e -> restartGame()); Region filler = new Region(); HBox.setHgrow(filler, Priority.ALWAYS); HBox scoreBar = new HBox(); scoreBar.getChildren().addAll(scoreIndicator, filler, replay); root.setTop(scoreBar); boardPane.setOnKeyPressed(this::takeInput); // Values lower than 1 magnify the scene. // E.g. with a TILE_SIZE of 20 and COLUMNS of 30, // width = 600 (screen coordinates) // columns = 30 (scene coordinates) // scale = 30/(20*30) = 1/20 Camera camera = new ParallelCamera(); double scale = 1./TILE_SIZE; camera.setScaleX(scale); camera.setScaleY(scale);
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx SubScene boardScene = new SubScene( boardPane, TILE_SIZE * COLUMNS, TILE_SIZE * ROWS ); boardScene.setCamera(camera); root.setCenter(boardScene); } @Override public void start(Stage stage) { Scene scene = new Scene(root); restartGame(); stage.setScene(scene); stage.setTitle("Snake Game"); stage.setResizable(false); stage.setOnCloseRequest(e -> Platform.exit()); stage.show(); } public void restartGame() { resetScore(); if (gameBoard != null) gameBoard.close(); gameBoard = new GameBoard(boardPane, this, ROWS, COLUMNS); boardPane.requestFocus(); replay.setVisible(false); TimerTask task = gameBoard.new SnakeMovement(); timer = new Timer(); timer.scheduleAtFixedRate(task, 100, 100); } public void endGame() { timer.cancel(); replay.setVisible(true); } public void resetScore() { score = 0; updateScore(); } public void increaseScore() { score++; updateScore(); } private void updateScore() { scoreIndicator.setText("Score: " + score); } private void takeInput(KeyEvent e) { switch (e.getCode()) { case DOWN -> { gameBoard.setDirection(0, 1); } case UP -> { gameBoard.setDirection(0, -1); } case RIGHT -> { gameBoard.setDirection(1, 0); } case LEFT -> { gameBoard.setDirection(-1, 0); } } } public static void main(String[] args) { launch(args); } } GameBoard.java package com.stackexchange.snake; import java.util.*; import javafx.application.Platform; import javafx.geometry.Point2D; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle;
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx public class GameBoard implements AutoCloseable { private final Pane pane; private final SnakeGame game; private final Snake snake; private final Fruit fruit; private final Set<Point2D> emptyTiles; private final int tilesInRow, tilesInCol; private int dX = 0, dY = 1, dXQueued = dX, dYQueued = dY; public GameBoard(Pane pane, SnakeGame game, int tilesInRow, int tilesInColumn) { this.pane = pane; this.game = game; this.tilesInRow = tilesInRow; this.tilesInCol = tilesInColumn; pane.setPrefSize(tilesInRow, tilesInColumn); emptyTiles = getBoardTiles(); snake = new Snake(3, tilesInColumn/2, Color.GREENYELLOW); pane.getChildren().addAll(snake.getRectangles()); emptyTiles.removeAll(snake.getPoints()); fruit = new Fruit(Color.RED); fruit.moveToRandom(emptyTiles); pane.getChildren().add(fruit); emptyTiles.remove(fruit.getPoint()); } @Override public void close() { pane.getChildren().removeAll(snake.getRectangles()); pane.getChildren().remove(fruit); } public Set<Point2D> getBoardTiles() { Set<Point2D> tiles = new HashSet<>(); for (int y = 0; y < tilesInRow; y++) { for (int x = 0; x < tilesInCol; x++) { tiles.add(new Point2D(x, y)); } } return tiles; } public void setDirection(int dXNew, int dYNew) { // the snake shouldn't move in the opposite direction if (dXNew != -dX && dYNew != -dY) { dXQueued = dXNew; dYQueued = dYNew; } } public boolean ateFruit() { Rectangle head = snake.getHead(); return head.getX() == fruit.getX() && head.getY() == fruit.getY(); }
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx public boolean willHit() { Rectangle head = snake.getHead(); Point2D newLoc = new Point2D( head.getX() + dX, head.getY() + dY ); return !( newLoc.equals(fruit.getPoint()) || emptyTiles.contains(newLoc) ); } class SnakeMovement extends TimerTask { private void delayed() { dX = dXQueued; dY = dYQueued; if (ateFruit()) { fruit.moveToRandom(emptyTiles); emptyTiles.remove(fruit.getPoint()); snake.addHead(); pane.getChildren().add(snake.getHead()); game.increaseScore(); } if (willHit()) game.endGame(); else snake.moveSnake(dX, dY, emptyTiles); } @Override public void run() { Platform.runLater(this::delayed); } } } Fruit.java package com.stackexchange.snake; import java.util.Random; import java.util.Set; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class Fruit extends Rectangle { private static final Random random = new Random(); public Fruit(Color color) { super(1, 1, color); } public void moveToRandom(Set<Point2D> emptyTiles) { int i = 0, randomIndex = random.nextInt(emptyTiles.size()); for (Point2D tile: emptyTiles) { if (i == randomIndex) { setX(tile.getX()); setY(tile.getY()); break; } i++; } } public Point2D getPoint() { return new Point2D(getX(), getY()); } } Snake.java package com.stackexchange.snake; import java.util.*; import java.util.stream.Collectors; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle;
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx public class Snake { private final Color color; private final List<Rectangle> rectangles = new ArrayList<>(); public Snake(int initialLength, int startX, Color color) { this.color = color; for (int startY = initialLength - 1; startY >= 0; startY--) { // 0 is the head and 2 is the tail, if snake's initial length is 3, // startY will be 40, 20, and 0, for elements 0, 1, and 2 respectively // since the snake is moving downward rectangles.add(createBodyPart(startX, startY)); } } public List<Rectangle> getRectangles() { return Collections.unmodifiableList(rectangles); } public Set<Point2D> getPoints() { return rectangles.stream() .map(rect -> new Point2D(rect.getX(), rect.getY())) .collect(Collectors.toSet()); } private Rectangle createBodyPart(double x, double y) { Rectangle body = new Rectangle(x, y, 1, 1); body.setFill(color); return body; } public void moveSnake(int dX, int dY, Set<Point2D> emptyTiles) { Rectangle head = getHead(), second = rectangles.get(1); boolean isHeadAdded = head.getX() == second.getX() && head.getY() == second.getY(); double oldX = head.getX(), newX = oldX + dX, oldY = head.getY(), newY = oldY + dY; head.setX(newX); head.setY(newY); // the head now occupies this tile emptyTiles.remove(new Point2D(newX, newY)); // when a new head is added, the rest of the body stays still for one task // so there is no need to go through the loop, and the tail's place shouldn't // be added to emptyTiles if (isHeadAdded) return; for (int i = 1; i < rectangles.size(); i++) { Rectangle body = rectangles.get(i);
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
java, beginner, snake-game, javafx double currentX = body.getX(), currentY = body.getY(); body.setX(oldX); body.setY(oldY); oldX = currentX; oldY = currentY; } // the old tile of the tail is now empty emptyTiles.add(new Point2D(oldX, oldY)); } public void addHead() { // the new head is set on the same tile as the old head initially // but it will be moved in the moveSnake method afterwards Rectangle oldHead = getHead(), newHead = createBodyPart(oldHead.getX(), oldHead.getY()); rectangles.add(0, newHead); } public Rectangle getHead() { return rectangles.get(0); } } Output
{ "domain": "codereview.stackexchange", "id": 43484, "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, beginner, snake-game, javafx", "url": null }
python, performance, reinventing-the-wheel, matrix, scipy Title: Approximation of the multiplicative matrix inverse (linalg.inv ()) Question: I am trying to compute the multiplicative inverse of a large matrix (~ >40,000x40,000). This can be done with e.g. numpy.linalg.inv or scipy.linalg.inv. Unfortunately, the calculation fails on the HPC to which I have access. numpy.linalg.inv(I-A) or scipy.linalg.inv(I-A) is equivalent to (I-A)^-1 which can be approximated via I + A + AA + AAA + AAAA ... or I + A + A^2 + A^3 + A^4 .... As I cannot run linalg.inv I wrote a function to approximate it. However, running my function with the full matrix proved to be extremely slow. I'm therefore wondering whether my code is simply inefficient/flawed. import numpy as np import scipy.sparse from scipy import linalg # Transactions T = scipy.sparse.csr_matrix( np.array([ [8, 5], [4, 2] ]) ) # Total output x = np.array( [16,12] ) # Technical coefficients A = scipy.sparse.csr_matrix(T / x) def getL( A, # Technical coefficient matrix log = False, iterations = 25 # Iterations ): """ Approximate (I - A)^-1. This function is an alternative to the execution of np.linalg.inv(I - A). L = (I-A)^-1 L = (I-A)^-1 ≈ I + A + AA + AAA + AAAA ... ≈ I + A + A^2 + A^3 + A^4 ... Parameters ---------- A : Matrix (e.g. np.array or scipy.sparse.csr_matrix) Technical coefficient matrix. log : Boolean, optional Print production layer sum to file. The default is False. iterations: Integer, optional Number of iterations. Returns ------- L : Matrix (e.g. np.array or scipy.sparse.csr_matrix) Leontief inverse. Approximation of (I - A)^-1.
{ "domain": "codereview.stackexchange", "id": 43485, "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, performance, reinventing-the-wheel, matrix, scipy", "url": null }
python, performance, reinventing-the-wheel, matrix, scipy """ # Zeroth production layer I = scipy.sparse.identity( A.shape[0], format = 'csc' ) L = I.copy() # First production layer layer = A.copy() # ... add the ensuing production layer until # L_i.sum() is less than 0.001% of L.sum() i = 0 while i <= iterations: L += layer layer = layer @ A if log: print(f"... layer {i} ...") i += 1 # Log if log: print(f"getL coverage [%]: {1-(layer.sum()/L.sum())}") return L # Calculate L L_getL = getL(A, iterations = 50, log = True) L_SciPy = scipy.linalg.inv( np.identity(A.shape[0]) - A.todense() ) # Compare the approaches print(L_getL.todense()) print(L_SciPy) Answer: Guess number one: you've started with a sparse matrix (good), but then you're failing to call into the sparse matrix linalg methods (almost certainly ungood). Also avoid a dense T / x; you can stay sparse by multiplying with a sparse diagonal matrix from x. Try: import numpy as np import scipy.linalg import scipy.sparse import scipy.sparse.linalg T = scipy.sparse.csc_matrix( # Transactions np.array([ [8, 5], [4, 2], ]) ) x = np.array([16, 12]) # Total output A = T * scipy.sparse.diags(1/x) # Technical coefficients L_dense = scipy.linalg.inv( np.eye(*A.shape) - A.todense() ) L_sparse = scipy.sparse.linalg.inv( scipy.sparse.eye(*A.shape, format='csc') - A ) print(L_dense) print(L_sparse.todense()) [[2.66666667 1.33333333] [0.8 1.6 ]] [[2.66666667 1.33333333] [0.8 1.6 ]] Note the use of CSC format instead of your CSR; SciPy asks for this during the inverse for efficiency reasons.
{ "domain": "codereview.stackexchange", "id": 43485, "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, performance, reinventing-the-wheel, matrix, scipy", "url": null }
c Title: Printing an array of numbers without duplicates Question: I had to make a program that have an array of numbers, and then I need to make a function that get the arr[0] and the length of the array, and then it will print all the numbers without the duplicate ones. I made this program and it worked well but I feel like I used too many variables for this program. (I started to learn in the last few weeks so in my opinion it does not look very good) #include <stdio.h> #define N 10 void print_set(int *arr, int n) { int i = 1; int duplicate_num, check_num, count; printf(" %d", *arr); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). arr++; while (i < n) { if (*arr != duplicate_num) { printf(" %d", *arr); check_num = *arr; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). while (i < n) { if (*arr == check_num) { *arr = duplicate_num; } arr++; i++; count++; } i = i - count; arr = arr - count; count = 0; } arr++; i++; } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(&arr[0], N); return 0; } output for this program: 4 6 9 8 1 I'll be happy to see any good methods to make this program less messy.
{ "domain": "codereview.stackexchange", "id": 43486, "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 Answer: The method you used to solve this problem is correct and the implementation is correct. The changes I suggest below are about making the code correct and making the code easier to read so that someone reading the code (including you in the future) will understand how this problem is solved. The first thing I notice is that you are modifying both the array index i and the address of the first element arr in order to track your current location in the array. So, you have to modify i and arr at the same time. This is unnecessary. You only need to modify i and then use arr[i] to get the number at that index. So, let's replace every instance of *arr with arr[i] and deleted all of the lines that modify arr. #include <stdio.h> #define N 10 void print_set(int *arr, int n) { int i = 1; int duplicate_num, check_num, count; printf(" %d", arr[0]); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). while (i < n) { if (arr[i] != duplicate_num) { printf(" %d", arr[i]); check_num = arr[i]; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). while (i < n) { if (arr[i] == check_num) { arr[i] = duplicate_num; } i++; count++; } i = i - count; count = 0; } i++; } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; }
{ "domain": "codereview.stackexchange", "id": 43486, "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() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; } Next, the variables duplicate_num and check_num are not initialized with values. In fact, duplicate_num is never assigned a value, so using it in the if (arr[i] != duplicate_num) and arr[i] = duplicate_num is undefined behavior. See the note at the very bottom of this answer for how the compiler can help you find these problems. I see that duplicate_num is used as a marker for array values that have been seen before, therefore it needs to be a value that cannot appear in the array. Since you print arr[0] outside the loop, that is actually a good value. Making this change: #include <stdio.h> #define N 10 void print_set(int *arr, int n) { int i = 1; int duplicate_num = arr[0], check_num, count; printf(" %d", arr[0]); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). while (i < n) { if (arr[i] != duplicate_num) { printf(" %d", arr[i]); check_num = arr[i]; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). while (i < n) { if (arr[i] == check_num) { arr[i] = duplicate_num; } i++; count++; } i = i - count; count = 0; } i++; } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; }
{ "domain": "codereview.stackexchange", "id": 43486, "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() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; } The variable check_num is always assigned a value before it is used, so it is less of a problem. Still, you always need to make sure that you never use a variable until after it has been assigned a value. Now, the variable count seems unnecessary. You are using it to get back to the initial value of i after marking all the duplicate numbers in the rest of the list. Instead, let's use a second index j to loop through the rest of the list so we don't need to reset the value of i afterwards. #include <stdio.h> #define N 10 void print_set(int *arr, int n) { int i = 1, j = 0; int duplicate_num = arr[0], check_num; printf(" %d", arr[0]); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). while (i < n) { if (arr[i] != duplicate_num) { printf(" %d", arr[i]); check_num = arr[i]; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). for (j = i; j < n; j++) { if (arr[j] == check_num) { arr[j] = duplicate_num; } } } i++; } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; } Now we see that i is only modified at the end of the loop block. Let's make this a standard for-loop. #include <stdio.h> #define N 10
{ "domain": "codereview.stackexchange", "id": 43486, "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 #define N 10 void print_set(int *arr, int n) { int i = 0, j = 0; int duplicate_num = arr[0], check_num; printf(" %d", arr[0]); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). for (i = 1; i < n; ++i) { if (arr[i] != duplicate_num) { printf(" %d", arr[i]); check_num = arr[i]; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). for (j = i; j < n; j++) { if (arr[j] == check_num) { arr[j] = duplicate_num; } } } } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; } Finally, if you are using a modern version of C, you can declare your variables where you need them, rather than at the top of the function. Let's move the variable declarations to where the variable is first needed. #include <stdio.h> #define N 10 void print_set(int *arr, int n) { int duplicate_num = arr[0]; printf(" %d", arr[0]); //printing the first number (arr[0]). //starting to check the other number. if they new I'll print them. (start from arr[1]). for (int i = 1; i < n; ++i) { if (arr[i] != duplicate_num) { printf(" %d", arr[i]); int check_num = arr[i]; // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too). for (int j = i; j < n; j++) { if (arr[j] == check_num) { arr[j] = duplicate_num; } } } } } int main() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; }
{ "domain": "codereview.stackexchange", "id": 43486, "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() { int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6}; print_set(arr, N); return 0; } Note: Learn about compiling your programs with warnings turned on in order to have the compiler display messsages about these and other problems. For gcc and clang: -Wall ("Warn on all problems") and -Wextra ("Warn on an extra set of problems"). For Microsoft Visual Studio: Project -> Properties -> C/C++ -> Warning Level = Level3 (/W3)
{ "domain": "codereview.stackexchange", "id": 43486, "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 }
python, python-3.x Title: Simple backup script with file removal after 7 days Question: Here is the script that I would like reviewed for the following: Best practices and design pattern usage Correctness in unanticipated cases Possible error checking Any streamline updates/ideas are welcome! import os import tarfile import time # Create backup filename timestr = time.strftime("%Y-%m-%d:%H%M%S") output_filename = "minecraft-backup-" +timestr backup_filename = output_filename + '.tar.gz' # Locataion of final backup files destination_dir = "/Users/username/Desktop/backup/" destination_file = destination_dir + backup_filename # Directory to backup backup_dir = '/Users/username/.config/' # Backup files with tarfile.open(destination_file, "w:gz") as tar: for fn in os.listdir(backup_dir): p = os.path.join(backup_dir, fn) tar.add(p, arcname=fn) # Remove files older than 7 days current_time = time.time() daysToDelete = 7 for dirpath,_,filenames in os.walk(destination_dir): for f in filenames: fileWithPath = os.path.abspath(os.path.join(dirpath, f)) creation_time = os.path.getctime(fileWithPath) print("file available:",fileWithPath) if (current_time - creation_time) // (24 * 3600) >= daysToDelete: os.unlink(fileWithPath) print('{} removed'.format(fileWithPath)) print("\n") ``` Answer: For many of your file manipulation operations prefer pathlib over os. You can pull in your filename formatting including time to one f-string. Prefer datetime over time, and prefer timedelta over a day integer. Note that the colon in your filename is not Windows-compatible. If you're able, use something like an underscore instead. tar has built-in support for recursive directory archiving, so you should probably just do that instead of looping. Suggested import os import tarfile from datetime import datetime, timedelta from pathlib import Path
{ "domain": "codereview.stackexchange", "id": 43487, "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", "url": null }
python, python-3.x now = datetime.now() backup_filename = f'minecraft-backup-{now:%Y-%m-%d_%H%M%S}.tar.gz' backup_dir = Path('~/.config').expanduser() destination_dir = Path('~/Desktop/backup').expanduser() destination_dir.mkdir(exist_ok=True) destination_file = destination_dir / backup_filename with tarfile.open(destination_file, 'w:gz') as tar: tar.add(backup_dir) # Remove files older than 7 days time_to_delete = timedelta(days=7) for dirname, _, filenames in os.walk(destination_dir): dirpath = Path(dirname) for f in filenames: file_with_path = dirpath / f print('file available:', file_with_path) creation_time = datetime.fromtimestamp( os.path.getctime(file_with_path) ) if now - creation_time >= time_to_delete: # file_with_path.unlink() print(file_with_path, 'removed')
{ "domain": "codereview.stackexchange", "id": 43487, "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", "url": null }
c++, beginner, datetime, c++17 Title: Convert string to date C++ Question: New to C++ here, by combining different pieces of code I've found, i came with this solution below to convert a date in string to a date object. It works as I want but I'm not certain to do the simplest thing. #include <iostream> #include <iomanip> #include <sstream> #include <chrono> #include <ctime> int main(void) { std::wstring date_time_format = L"%m/%d/%Y"; std::wistringstream ss{ L"4/28/2022" }; std::tm dt; ss >> std::get_time(&dt, date_time_format.c_str()); std::time_t final_time; final_time = std::mktime(&dt); std::tm *ltm = localtime(&final_time); std::cout << "Year:" << 1900 + ltm->tm_year<<std::endl; std::cout << "Month: "<< 1 + ltm->tm_mon<< std::endl; std::cout << "Day: "<< ltm->tm_mday << std::endl; }
{ "domain": "codereview.stackexchange", "id": 43488, "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++, beginner, datetime, c++17", "url": null }
c++, beginner, datetime, c++17 Answer: Unnecessary use of wide strings In your example, there is no need to use wide strings for date_time_format and ss. Just use std::string and std::istringstream and drop the L prefix for the string literals. Missing std:: You are using localtime() without std:: in front. If you include the C++ versions of the C header files, then there is no guarantee that the C functions will be available in the global namespace. Use '\n' instead of std::endl Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and has a negative impact on performance. Missing error checking If you are trying to parse strings you don't have full control over, the parsing might fail. You should check that ss is still in a good state after trying to parse the date. Consider using C++20 If you are stuck with C++17 or earlier, then the code you wrote is the only standards compliant way to parse time. However, the situation has improved in C++20 with the introduction of std::chrono::parse() and other calendar features. If you are lucky and your compiler and standard library support it already, you can write: #include <iostream> #include <sstream> #include <chrono> int main() { std::string date_time_format = "%m/%d/%Y"; std::istringstream ss{ "4/28/2022" }; std::chrono::year_month_day date; ss >> std::chrono::parse(date_time_format, date); if (!ss) { /* failed to parse date */ ... } std::cout << "Year: " << date.year() << '\n'; std::cout << "Month: " << date.month() << '\n'; std::cout << "Day: " << date.day() << '\n'; }
{ "domain": "codereview.stackexchange", "id": 43488, "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++, beginner, datetime, c++17", "url": null }
python, web-scraping, pandas, beautifulsoup, selenium Title: Crawler/scraper for soccer match results Question: I wrote this code some time ago as part of the web-scraping learning. Every now and then I find mistakes in it, as well as I have doubts. Feedback please, is this code compliant with the common best practices? Any comments will be useful. # crawler_her_sel.py # -*- coding: utf-8 -*- import time from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup import pandas as pd # Variable with the URL of the website. my_url = "https://www.flashscore.com/" # Preparing of the browser for the work. options = Options() options.add_argument("--headless") driver = Firefox(options=options) driver.get(my_url) # Prepare the blank dictionary to fill in for pandas. dictionary_of_matches = {} # Preparation of lists with scraped data. list_of_countries = [] list_of_leagues = [] list_of_home_teams = [] list_of_scores_for_home = [] list_of_scores_for_away = [] list_of_away_teams = [] # Wait for page to fully render try: element = WebDriverWait(driver, 25).until( EC.presence_of_element_located((By.CLASS_NAME, "adsclick"))) finally: # Loads the website code as the BeautifulSoup object. pageSource = driver.page_source bsObj = BeautifulSoup(pageSource, "lxml") # Determining the number of the football matches with the help of # the BeautifulSoup. games_1 = bsObj.find_all("div", {"class": "event__participant event__participant--home"}) games_2 = bsObj.find_all("div", {"class": "event__participant event__participant--home fontBold"}) games_3 = bsObj.find_all("div", {"class": "event__participant event__participant--away"}) games_4 = bsObj.find_all("div", {"class": "event__participant event__participant--away fontBold"})
{ "domain": "codereview.stackexchange", "id": 43489, "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, web-scraping, pandas, beautifulsoup, selenium", "url": null }
python, web-scraping, pandas, beautifulsoup, selenium # Determining the number of the countries for the given football # matches. countries = driver.find_elements(By.CLASS_NAME, "event__title--type") # Determination of the number that determines the number of # the loop iterations. sum_to_iterate = len(countries) + len(games_1) + len(games_2) + len(games_3) + len(games_4) for ind in range(1, (sum_to_iterate+1)): # Scraping of the country names. try: country = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[2]/div/span[1]').text list_of_countries.append(country) except: country = "" list_of_countries.append(country) # Scraping of the league names. try: league = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[2]/div/span[2]').text list_of_leagues.append(league) except: league = "" list_of_leagues.append(league) # Scraping of the home team names. try: home_team = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[3]').text list_of_home_teams.append(home_team) except: home_team = "" list_of_home_teams.append(home_team) # Scraping of the home team scores. try: score_for_home_team = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[5]').text list_of_scores_for_home.append(score_for_home_team) except: score_for_home_team = "" list_of_scores_for_home.append(score_for_home_team)
{ "domain": "codereview.stackexchange", "id": 43489, "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, web-scraping, pandas, beautifulsoup, selenium", "url": null }
python, web-scraping, pandas, beautifulsoup, selenium # Scraping of the away team scores. try: score_for_away_team = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[6]').text list_of_scores_for_away.append(score_for_away_team) except: score_for_away_team = "" list_of_scores_for_away.append(score_for_away_team) # Scraping of the away team names. try: away_team = driver.find_element(By.XPATH, '//div[@class="sportName soccer"]/div['+str(ind)+ ']/div[4]').text list_of_away_teams.append(away_team) except: away_team = "" list_of_away_teams.append(away_team) # Add lists with the scraped data to the dictionary in the correct # order. dictionary_of_matches["Countries"] = list_of_countries dictionary_of_matches["Leagues"] = list_of_leagues dictionary_of_matches["Home_teams"] = list_of_home_teams dictionary_of_matches["Scores_for_home_teams"] = list_of_scores_for_home dictionary_of_matches["Scores_for_away_teams"] = list_of_scores_for_away dictionary_of_matches["Away_teams"] = list_of_away_teams # Creating of the frame for the data with the help of the pandas # package. df_res = pd.DataFrame(dictionary_of_matches) # Saving of the properly formatted data to the csv file. The date # and the time of the scraping are hidden in the file name. name_of_file = lambda: "flashscore{}.csv".format(time.strftime( "%Y%m%d-%H.%M.%S")) df_res.to_csv(name_of_file(), encoding="utf-8") driver.quit()
{ "domain": "codereview.stackexchange", "id": 43489, "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, web-scraping, pandas, beautifulsoup, selenium", "url": null }
python, web-scraping, pandas, beautifulsoup, selenium driver.quit() Answer: Are you using Python2? If not the utf-8 declaration on top of your page isn't needed. Obviously there is a lot of duplication as you repeat the same code to do the same thing. All you need is to write an ad hoc function that accepts an xpath expression and returns a string (or a list). This would reduce your code base instantly. You already have an xpath expression at line 56 to fetch the list of countries: countries = driver.find_elements(By.CLASS_NAME, "event__title--type") Then you should already have a list that can be iterated. Thus, further scraping of country names in a loop probably is not necessary. Same thing for the other items. Do you really need that loop? You are just doing xpath selection. And it would make more sense to fetch the different types of items separately and not within the same loop, since their respective lengths can vary. Note that you are using a Selenium function here, whereas BS exposes a similar function (find_all). Indeed you already use BS find_all before. Then I would suggest sticking to BS. Using both at the same time can be a source of confusion. This code is wasteful because you could fetch several tags at the same time: games_1 = bsObj.find_all("div", {"class": "event__participant event__participant--home"}) games_2 = bsObj.find_all("div", {"class": "event__participant event__participant--home fontBold"}) games_3 = bsObj.find_all("div", {"class": "event__participant event__participant--away"}) games_4 = bsObj.find_all("div", {"class": "event__participant event__participant--away fontBold"}) This should accomplish the same thing: games = bsObj.find_all("div", {"class":[ "event__participant event__participant--home", "event__participant event__participant--home fontBold", "event__participant event__participant--away", "event__participant event__participant--away fontBold" ]}
{ "domain": "codereview.stackexchange", "id": 43489, "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, web-scraping, pandas, beautifulsoup, selenium", "url": null }
python, web-scraping, pandas, beautifulsoup, selenium This is a list, but you could even use a regular expression for more flexibility. A more Pythonic loop would not use range but look like: countries = driver.find_elements(By.CLASS_NAME, "event__title--type") for country in countries: ... As regards naming of variables: the list_ prefix isn't meaningful eg: prefix list_of_countries. countries is enough and to the point. A good IDE should tell you the variable data type anyway. The finally statement at line 38 is misplaced. The code in a finally block is always executed, even after an exception occurs. This is not what you want. Instead, add an except block and stop your application if page loading fails. Because if it does, then the rest of the code cannot complete and it would be pointless to proceed. The way you use the except clause is problematic because you are ignoring any errors that may occur, and clearly a web scraping application can fail in so many ways. That makes debugging difficult too. I really recommend that you stop in case of error, because your application is bound to behave unpredictably, or return garbage in this case. Some types of exceptions can be anticipated and handled gracefully but you're not doing any of that presently. Don't mask the exception, show the details so you can figure out what went wrong. To build the file name, an F-string would be more appropriate, provided that you run Python >= 3.6. The lambda expression is not needed. Using Pandas to generate a CSV file is overkill because you are not doing any sophisticated data processing that would mandate using that library. The built-in csv module should be sufficient for your needs.
{ "domain": "codereview.stackexchange", "id": 43489, "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, web-scraping, pandas, beautifulsoup, selenium", "url": null }
c++, beginner, algorithm, sorting Title: Bogo Sort Algorithm Question: I am a beginner programmer and have written a program that sorts a number of integers of your choosing using bogo sort. Are there any improvements that could be made to make this code more efficient (ironic, but you get the idea)? Are there any ways to make this code easier to read for someone else? #include <iostream> #include <time.h> using namespace std; int findModulus(int quotient, int divisor); int main() { cout << "Hello, welcome to the Bogo Sort Algorithm!" << endl; srand(time(NULL)); //First sections establishes the dimensions of the matrices int entryNum ; cout << "Number of values: "; cin >> entryNum; int seq[entryNum]; int plchlderSeq[entryNum]; bool seqIsSorted; int chosenOrder[entryNum]; int chosenOrderPreOp[entryNum]; int numbers[entryNum]; int i,j,k; cout << "Input the values: "; for(i=1; i<=entryNum; i++){ cin >> seq[i-1]; } do{ seqIsSorted = true;
{ "domain": "codereview.stackexchange", "id": 43490, "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++, beginner, algorithm, sorting", "url": null }
c++, beginner, algorithm, sorting do{ seqIsSorted = true; for(i=1; i<=entryNum; i++){ numbers[i-1] = i ; } //this section is for randomising the order of (1, ... , entryNum), remove comments to see it in action for(i=1; i<=entryNum; i++){ chosenOrderPreOp[i-1] = findModulus(rand(),entryNum-i+1); //cout << chosenOrderPreOp[i-1] << "\n"; chosenOrder[i-1] = numbers[chosenOrderPreOp[i-1]]; //cout << chosenOrder[i-1] << "\n"; for(j = chosenOrderPreOp[i-1]+1 ; j <= entryNum-i ; j++){ numbers[j-1] = numbers[j]; // copy next element left for(k=1; k<=entryNum; k++){ //cout << numbers[k-1] << " "; } //cout << " \n"; } /* for(j=1; j<=entryNum-i; j++){ cout << numbers[j-1] << " "; }*/ //cout << " \n"; } for(i=1; i<=entryNum; i++){ //cout << chosenOrder[i-1] << " "; } //cout << "\n"; for(i=1; i<=entryNum; i++){ plchlderSeq[i-1] = seq[chosenOrder[i-1]-1]; } for(i=1; i<=entryNum; i++){ seq[i-1] = plchlderSeq[i-1]; } for(i=1; i<=entryNum-1; i++){ if(seq[i-1] > seq[i]){ seqIsSorted = false; } } for(i=1; i<=entryNum; i++){ //cout << seq[i-1] << " "; } if(seqIsSorted){ cout << "\nSequence is sorted \n"; for(i=1; i<=entryNum; i++){ cout << seq[i-1] << " "; } } else{ //cout << "\nSequence is not sorted \n"; } }while(!seqIsSorted); return 0; } int findModulus(int quotient, int divisor){ int result; do{ result = quotient; quotient = quotient-divisor; }while(quotient >= 0); return result; } Answer: Advice 1 int seq[entryNum];
{ "domain": "codereview.stackexchange", "id": 43490, "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++, beginner, algorithm, sorting", "url": null }
c++, beginner, algorithm, sorting Answer: Advice 1 int seq[entryNum]; That did not compile on Visual Studio 2022 to begin with. Use: #include <cstdlib> #include <vector> ... std::size_t seqLength; std::cin >> seqLength; std::vector<int> seq(seqLength); Advice 2 using namespace std; Please don't do it. Not just you import a lot of stuff to your program, but also abuse the compiler. Advice 3 cout << "Input the values: "; for (i = 1; i <= entryNum; i++) { cin >> seq[i - 1]; } Can be rewriten as: std::cout << "Input the values:\n"; for (std::size_t i = 0; i < seqLength; i++) { std::cin >> seq[i]; } Advice 4 I would not specifically randomize the input sequence, since you always can input whatever you want to seq. Advice 5 As noted in comments, you can use std::shuffle and std::is_sorted for your bogosort. Alternative implementation (C++20) #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <iterator> #include <random> #include <vector> template<class RandomIt, class Cmp = std::less<>> void bogosort(RandomIt first, RandomIt last, Cmp cmp = Cmp()) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); auto prng = std::default_random_engine(seed); while (!std::is_sorted(first, last, cmp)) { std::shuffle(first, last, prng); } } int main() { size_t seqLength; std::cout << "Number of values: "; std::cin >> seqLength; std::vector<int> seq(seqLength); std::cout << "Input the values:\n"; for (std::size_t i = 0; i < seqLength; i++) { std::cin >> seq[i]; } bogosort(seq.begin(), seq.end()); std::copy(seq.begin(), seq.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; }
{ "domain": "codereview.stackexchange", "id": 43490, "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++, beginner, algorithm, sorting", "url": null }
javascript, array, html, dynamic-programming Title: make html table in sync with javascript array Question: I have an array of users containing user name with their rules on my practice project I have generated a table in HTML from that array in JS, So I can change the status of any user rule by toggling on cell, or toggling all rules by clicking on name of user, or deny or grant rules for all users by clicking on column vertically! BUT I want to update the original array users rules, if the rules of any user change; In other words How can I make the array in JS synchronize with the table in HTML. const users = [ { name: "Admin", rules: { Create: true, Read: true, Update: true, Delete: true }, }, { name: "Developer", rules: { Create: true, Read: true, Update: false, Delete: true }, }, { name: "Customer", rules: { Create: false, Read: true, Update: false, Delete: false }, }, ]; let rules = ["Create", "Read", "Update", "Delete"]; let status = { "": "red", green: "red", red: "green", }; let icons = { "": "", green: "", red: "", }; const table = document.createElement("table"); const thead = table.createTHead(); const tr = thead.insertRow(); const th = tr.appendChild(document.createElement("th")); th.appendChild(document.createTextNode("Users")); rules.forEach((rule, i) => { const th = tr.appendChild(document.createElement("th")); th.appendChild(document.createTextNode(rule)); th.setAttribute("status", ""); th.onclick = (e) => { const cols = [ ...document.querySelectorAll(`tbody tr td:nth-child(${i + 2})`), ]; cols.forEach((col) => { col.textContent = icons[e.target.getAttribute("status") ?? ""]; }); e.target.setAttribute( "status", status[e.target.getAttribute("status") ?? ""] ); }; }); const tbody = table.createTBody(); users.forEach((user) => { const tr = tbody.insertRow(); const td = tr.appendChild(document.createElement("td")); td.appendChild(document.createTextNode(user.name));
{ "domain": "codereview.stackexchange", "id": 43491, "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, html, dynamic-programming", "url": null }
javascript, array, html, dynamic-programming td.onclick = (e) => { rulesUser = [...td.parentElement.children]; rulesUser.slice(1).forEach((rule) => { rule.textContent = icons[e.target.getAttribute("status") ?? ""]; }); e.target.setAttribute( "status", status[e.target.getAttribute("status") ?? ""] ); }; rules.forEach((rule) => { const td = tr.insertCell(); td.appendChild( document.createTextNode( Object.entries(user.rules) .filter((entry) => entry[1] == true) .map((entry) => entry[0]) .includes(rule) ? "" : "" ) ); td.setAttribute( "status", Object.entries(user.rules) .filter((entry) => entry[1] == true) .map((entry) => entry[0]) .includes(rule) ? "green" : "red" ); td.onclick = (e) => { e.target.textContent = icons[e.target.getAttribute("status") ?? ""]; e.target.setAttribute( "status", status[e.target.getAttribute("status") ?? ""] ); }; }); }); document.body.appendChild(table); * { font-family: sans-serif; } table { border-collapse: collapse; border: 1px solid; } td, th { padding: 5px 10px; text-align: center; border: 1px solid; cursor: pointer; } thead th { background-color: gray; } tbody th { background-color: lightgray; } thead th:first-child { background-color: lightblue; } Any feedback or suggestion to make the code better, I'd be really grateful if somebody could help me with this problem so I can continue building my practice project. Thanks ❤️
{ "domain": "codereview.stackexchange", "id": 43491, "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, html, dynamic-programming", "url": null }
javascript, array, html, dynamic-programming Answer: Personally I would break the code down into discrete functions that do specific peices of work. I would opt to use the users object graph as the 'source of truth' as to what state each element is in, and use that to update the DOM. This can then be leveraged for both the initial setup and the click handlers. I think generally speaking it not advised to use custom HTML attributes to convey state, or at least would should prefix them with the x- convention and possibly something to prevent attribute clashes with browser plugins that might be decorating DOM elements once the page is loaded. Another more accepted approach here is to use CSS classes and add/remove those classes to alter the visual state (show/hide elements for example). The below code is an example, and its a bit quick and dirty to illustrate the point. Ideally I suspect I'd want to be encapsulating the whole thing in a class, passing it a DOM element to act as the container for all generated code. Rather than using globals for users, rules, state etc you'd want this in the class, or at least passed into the functions so that its clear what state each function is operating on. const users = [ { name: "Admin", rules: { Create: true, Read: true, Update: true, Delete: true }, }, { name: "Developer", rules: { Create: true, Read: true, Update: false, Delete: true }, }, { name: "Customer", rules: { Create: false, Read: true, Update: false, Delete: false }, }, ]; let rules = ["Create", "Read", "Update", "Delete"]; const state = ["", ""] const ruleToggle = (index, enabled) => { users.forEach(user => user.rules[rules[index]] = enabled) } const userToggle = (index, enabled) => { rules.forEach(rule => { users[index].rules[rule] = enabled }) } const userRuleToggle = (userIdx, ruleIdx) => { users[userIdx].rules[rules[ruleIdx]] = !users[userIdx].rules[rules[ruleIdx]] }
{ "domain": "codereview.stackexchange", "id": 43491, "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, html, dynamic-programming", "url": null }
javascript, array, html, dynamic-programming const updateRules = (userIdx) => { for (let ruleIdx=0 ; ruleIdx < rules.length ; ruleIdx++) { const sel = `tbody tr:nth-child(${userIdx + 1}) td:nth-child(${ruleIdx + 2})` updateUserRule(userIdx, ruleIdx, document.querySelector(sel)) } } const updateUsers = (ruleIdx) => { for (let userIdx = 0; userIdx < users.length ; userIdx++) { const sel = `tbody tr:nth-child(${userIdx + 1}) td:nth-child(${ruleIdx + 2})` updateUserRule(userIdx, ruleIdx, document.querySelector(sel)) } } const updateUserRule = (userIdx, ruleIdx, el) => { el.textContent = state[users[userIdx].rules[rules[ruleIdx]] ? 1 : 0] } const toggleStatus = (el) => { const enabled = !parseInt(el.getAttribute("status")) el.setAttribute("status", enabled ? 1 : 0) return enabled } const insertColumnHeadings = (tr) => { const th = tr.appendChild(document.createElement("th")); th.textContent = "Users" rules.forEach((rule, i) => { const th = tr.appendChild(document.createElement("th")); th.textContent = rule toggleStatus(th); th.onclick = (ev) => { const enabled = toggleStatus(ev.target) ruleToggle(i, enabled) updateUsers(i) }; }); } const insertRows = (tbody) => { users.forEach((user, userIdx) => { const tr = tbody.insertRow(); const td = tr.appendChild(document.createElement("td")); td.textContent = user.name toggleStatus(td); td.onclick = (ev) => { const enabled = toggleStatus(ev.target) userToggle(userIdx, enabled) updateRules(userIdx) }; rules.forEach((rule, ruleIdx) => { const td = tr.insertCell(); updateUserRule(userIdx, ruleIdx, td) td.onclick = (el) => { userRuleToggle(userIdx, ruleIdx) updateUserRule(userIdx, ruleIdx, el.target) }; }); }); } const table = document.createElement("table"); const thead = table.createTHead(); const tr = thead.insertRow(); insertColumnHeadings(tr) const tbody = table.createTBody(); insertRows(tbody)
{ "domain": "codereview.stackexchange", "id": 43491, "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, html, dynamic-programming", "url": null }
javascript, array, html, dynamic-programming const tbody = table.createTBody(); insertRows(tbody) document.body.appendChild(table); * { font-family: sans-serif; } table { border-collapse: collapse; border: 1px solid; } td, th { padding: 5px 10px; text-align: center; border: 1px solid; cursor: pointer; } thead th { background-color: gray; } tbody th { background-color: lightgray; } thead th:first-child { background-color: lightblue; }
{ "domain": "codereview.stackexchange", "id": 43491, "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, html, dynamic-programming", "url": null }
python-3.x, pandas Title: Speeding up row insertion to Pandas DataFrames Question: I have the below code that seems to be taking a while to run over time. info_participants = info['participants'] for participant in info_participants: info_gamestatistics_table = flatdict.FlatDict(participant, delimiter='_') info_gamestatistics_table = dict(info_gamestatistics_table) info_gamestatistics_df = info_gamestatistics_df.append(info_gamestatistics_table, ignore_index=True) info participants is a list of json objects. I'm flattening a json object, turning the output to a dict, and adding it to my dataframe using the df.append() method, and I'm doing that for each participant (10). Is there a faster way to do this? Answer: Without knowing what info['participants'] looks like, I've made this assumption. As others have mentioned it would help the reviewers if you could provide a small sample of the data or a function to generate something that represents it. info = { "participants": [{f"foo_{i}": f"bar"} for i in range(200)] + [{f"spam_{i}": f"eggs"} for i in range(200)] } It appears you are using the FlatDict delimiter='_' to split keys in your object. With that I've ditched FlatDict for a python generator function import pandas as pd info = ... info_participants = info["participants"] def participants_to_dataframe(guest_list: list[dict[str, any]]) -> pd.DataFrame: def generate() -> tuple[str, ...]: for guest in guest_list: for key, value in guest.items(): yield *key.split("_"), value return pd.DataFrame(generate(), columns=["name", "id", "value"]).set_index( ["name", "id"] ) def start(): df = participants_to_dataframe(info_participants) print(df) if __name__ == "__main__": start()
{ "domain": "codereview.stackexchange", "id": 43492, "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-3.x, pandas", "url": null }
python-3.x, docker Title: Multi stage Dockerfile for eccode compilation Question: I wrote a Dockerfile to install ecCodes for use in a python environment using cfgrib and xarray. The tarball can be found on the ecCode releases page Dockerfile # syntax=docker/dockerfile:1 # ECCODE COMPILE FROM python:3.10.4 as compiler # /path/to/where/you/install/eccodes ENV ECCODES_DIR=/usr/src/eccodes # the zip file for eccodes COPY ./eccodes-2.24.2-Source.tar.gz ./eccodes-2.24.2-Source.tar.gz RUN apt-get update -y # compiler tools RUN apt-get install -y --no-install-recommends \ cmake \ gfortran \ build-essential # unzip RUN tar -xzf eccodes-2.24.2-Source.tar.gz # prepare the build folders RUN mkdir $ECCODES_DIR build && cd build # RUN cmake ../eccodes-2.24.2-Source -DCMAKE_INSTALL_PREFIX=$ECCODES_DIR -DENABLE_JPG=ON RUN make && ctest && make install # PYTHON BUILD FROM python:3.10.4 as builder ENV VIRTUAL_ENV=/opt/venv COPY ./requirements.txt ./requirements.txt # create the virtual env RUN python3 -m venv $VIRTUAL_ENV # upgrade pip RUN python3 -m pip install --upgrade pip # install the requirements RUN pip install -r requirements.txt # FINAL FROM python:3.10.4 COPY --from=compiler $ECCODES_DIR $ECCODES_DIR ENV ECCODES_DIR=$ECCODES_DIR COPY --from=builder $VIRTUAL_ENV $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" RUN python -m cfgrib selfcheck requirements.txt attrs==21.4.0 cffi==1.15.0 cfgrib==0.9.10.1 click==8.1.3 eccodes==1.4.2 findlibs==0.0.2 numpy==1.22.4 packaging==21.3 pandas==1.4.2 pycparser==2.21 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.1 six==1.16.0 xarray==2022.3.0 Answer: Instead of a COPY + RUN tar, you can get Docker to do the extraction for you by using ADD, since you have the file downloaded externally anyway:
{ "domain": "codereview.stackexchange", "id": 43493, "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-3.x, docker", "url": null }
python-3.x, docker If <src> is a local tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from remote URLs are not decompressed. When a directory is copied or unpacked, it has the same behavior as tar -x, the result is the union of: Whatever existed at the destination path and The contents of the source tree, with conflicts resolved in favor of "2." on a file-by-file basis. Note Whether a file is identified as a recognized compression format or not is done solely based on the contents of the file, not the name of the file. For example, if an empty file happens to end with .tar.gz this will not be recognized as a compressed file and will not generate any kind of decompression error message, rather the file will simply be copied to the destination. apt-get install -y will not suppress debconf questions (e.g., selecting the local timezone when install the timezone database package). However, since Docker doesn't provide an terminal on which debconf questions can be presented, they'll be automatically answered anyway, but this will lead to more noise in the build log. You should set the environment variable DEBIAN_FRONTEND=noninteractive to suppress debconf questions. The Docker documentation on ENV has an incorrect example of using DEBIAN_FRONTEND: If an environment variable is only needed during build, and not in the final image, consider setting a value for a single command instead: RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y ... In this command, DEBIAN_FRONTEND will only affect apt-get update, which won't be asking debconf questions anyway. It should be either: RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ... Or: RUN export DEBIAN_FRONTEND=noninteractive; apt-get update && apt-get install -y ... RUN commands are run in independent shells and a cd in one wouldn't affect the working directory in another:
{ "domain": "codereview.stackexchange", "id": 43493, "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-3.x, docker", "url": null }
python-3.x, docker Note that each instruction is run independently, and causes a new image to be created - so RUN cd /tmp will not have any effect on the next instructions. You should use WORKDIR instead, and since it can create the directory if it doesn't exist, skip the mkdir for that directory: RUN mkdir "$ECCODES_DIR" WORKDIR build RUN cmake ../eccodes-2.24.2-Source -DCMAKE_INSTALL_PREFIX="$ECCODES_DIR" -DENABLE_JPG=ON (Also, quote your variables.) Try to order layers in a way that matches their dependencies. In this snippet, only the last RUN depends on the COPY, but the preceding RUN statements will be re-executed each time requirements.txt changes, even if the cached results are perfectly usable: COPY ./requirements.txt ./requirements.txt # create the virtual env RUN python3 -m venv $VIRTUAL_ENV # upgrade pip RUN python3 -m pip install --upgrade pip # install the requirements RUN pip install -r requirements.txt I'd suggest: # create the virtual env RUN python3 -m venv "$VIRTUAL_ENV" # upgrade pip RUN python3 -m pip install --upgrade pip COPY ./requirements.txt ./requirements.txt # install the requirements RUN pip install -r requirements.txt (Or keep the COPY before upgrading pip. In either case, the virtualenv creation doesn't need to be re-run each time requirements.txt changes.)
{ "domain": "codereview.stackexchange", "id": 43493, "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-3.x, docker", "url": null }
python, datetime, console, timer Title: Clear output line in terminal after use for countdown (different length strings) Question: The method to overwrite the same line is well known and I use it for countdown, but what about when the next output string has a different size and will be generated by a single print? That's the reason for my question! I use a text countdown timer like (all on the same line): Next activation in 5 seconds Next activation in 4 seconds Next activation in 3 seconds Next activation in 2 seconds Next activation in 1 seconds In order not to waste unnecessary lines, I created a false way to produce the same result as the keyboard backspace button (false because it actually only writes over the top with blank spaces, giving the false impression that we return to the first position left writing in the terminal): import sys import time from datetime import datetime def main(): while True: print('-------- test --------') print(datetime.now().strftime('%Y/%d/%m %H:%M')) for remaining in range(5, 0, -1): sys.stdout.write('\r') txt_value = f'Next activation in {remaining:2d} seconds' sys.stdout.write(txt_value) sys.stdout.flush() time.sleep(1) sys.stdout.write('\r' + len(txt_value)*' ') sys.stdout.write('\r') if __name__ == '__main__': main() Output countdown: -------- test -------- Next activation in 5 seconds Output after full countdown: -------- test -------- 2022/18/06 21:21 It's a pretty archaic method (at least I imagine it is), so I brought this question for improvements and professionalization of the method.
{ "domain": "codereview.stackexchange", "id": 43494, "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, datetime, console, timer", "url": null }
python, datetime, console, timer Answer: ANSI escape sequences are not necessary, and the so-called archaic method of using a carriage return is preferred. Avoid mixing sys.stdout with print; prefer the latter. This offers a flush kwarg to be used instead of sys.stdout.flush(). For the purposes of demonstration it's best if you include a seconds-field in your timestamp. Think about the assumptions of print(). It has a default ending character of a linefeed. A more uniform approach to printing uses either a terminating linefeed or a terminating carriage return, not a prefix carriage return. During the sleeping period, the carriage return will have the cursor sitting at the beginning of the line, ready to overwrite with either another progress banner or real output. Suggested from time import sleep from datetime import datetime def main(): progress_len = 0 while True: print( f'{"-------- test --------":{progress_len}}\n' f'{datetime.now():%Y/%d/%m %H:%M:%S}' ) for remaining in range(5, 0, -1): txt_value = f'Next activation in {remaining:2d} seconds' progress_len = len(txt_value) print(txt_value, end='\r', flush=True) sleep(1) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43494, "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, datetime, console, timer", "url": null }
rust, iterator Title: Implementing Ord trait for an Iterator Wrapper Question: Recently, I needed to sort iterators by their first value and/or use them in BinaryHeap. There are things I don't like about this implementation: Using RefCell. Mutating an underlying object while calling eq/cmp/etc methods. Using unsafe in Deref. It seems to be doing exactly what I want but I feel there must be a better way of achieving the same result. use std::cell::RefCell; use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::iter::Peekable; use std::ops::{Deref, DerefMut}; struct IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { iter: RefCell<Peekable<I>>, } impl<I, T> Eq for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { } impl<I, T> PartialEq<Self> for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn eq(&self, other: &Self) -> bool { self.iter.borrow_mut().peek().eq(&other.iter.borrow_mut().peek()) } } impl<I, T> PartialOrd<Self> for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.iter.borrow_mut().peek().partial_cmp(&other.iter.borrow_mut().peek()) } } impl<I, T> Ord for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn cmp(&self, other: &Self) -> Ordering { self.iter.borrow_mut().peek().cmp(&other.iter.borrow_mut().peek()) } } impl<I, T> From<I> for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn from(iter: I) -> Self { Self { iter: RefCell::new(iter.peekable()) } } } impl<I, T> Deref for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { type Target = Peekable<I>; fn deref(&self) -> &Self::Target { let ptr = self.iter.as_ptr(); unsafe { &*ptr } } }
{ "domain": "codereview.stackexchange", "id": 43495, "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": "rust, iterator", "url": null }
rust, iterator impl<I, T> DerefMut for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn deref_mut(&mut self) -> &mut Self::Target { let ptr = self.iter.as_ptr(); unsafe { &mut *ptr } } } Usage example: #[cfg(test)] mod tests { use super::*; #[test] fn test() { let a = [1, 2, 3]; let b = [3, 2, 1]; let mut heap = BinaryHeap::new(); heap.push(IterHeapWrapper::from(a.iter())); heap.push(IterHeapWrapper::from(b.iter())); assert_eq!(heap.pop().unwrap().next().unwrap(), &3); } } Answer: The fundamental problem is a mismatch between Eq/PartialCmp/Cmp and Peekable. The comparison functions assume that comparing objects does not require modifying them. But the peekable() method is a mutable method, so you can't call it. But why isn't peekable an immutable function? After all, it doesn't logically modify the iterator, it just peeks. The reason is that it its lazy, it doesn't progress the iterator until you request to take a peek. If instead, it was eager, pulling the next item from the iterator right away, you could peek at it without modifying the iterator. So you could do something like this: struct IterHeapWrapper<I, T> where I: Iterator<Item = T> { iter: I, peeked: Option<T> } impl<I, T> From<I> for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { fn from(mut iter: I) -> Self { let peeked = iter.next(); Self { iter, peeked } } } impl<I, T> Iterator for IterHeapWrapper<I, T> where I: Iterator<Item = T>, T: Ord, { type Item = T; fn next(&mut self) -> Option<Self::Item> { let mut next = self.iter.next(); std::mem::swap(&mut next, &mut self.peeked); next } }
{ "domain": "codereview.stackexchange", "id": 43495, "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": "rust, iterator", "url": null }
rust, iterator This implements the logic of peekable, but in such a way that the next item is stored right there on the struct, so you can use it to do comparisons. Your unsafe code is not a good idea. I think implementing Iterator on IterHeapWrapper probably does what you want better. As it stands, by using unsafe code you've completely defeated the protection of RefCell. RefCell tracks at runtime the references created out of it to make sure it remains safe, but you skip that completely.
{ "domain": "codereview.stackexchange", "id": 43495, "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": "rust, iterator", "url": null }
java, integer, numbers-to-words Title: Spelling Java long values to human readable text in English Question: Now, I have extended my program taking some answers in the previous iteration into account: package com.github.coderodde.fun; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class LongSpeller { private static final class BigNumber { private final long size; private final String name; private BigNumber(long size, String name) { this.size = size; this.name = name; } public long getSize() { return size; } public String getName() { return name; } } private static final class Pair { private final String name; private final Long number; Pair(String name, Long number) { this.name = name; this.number = number; } } private static final BigNumber[] BIG_NUMBERS = { new BigNumber(1L, ""), new BigNumber(1_000L, "thousand"), new BigNumber(1_000_000L, "million"), new BigNumber(1_000_000_000L, "billion"), new BigNumber(1_000_000_000_000L, "trillion"), new BigNumber(1_000_000_000_000_000L, "quadrillion"), new BigNumber(1_000_000_000_000_000_000L, "quintillion"), }; private static final Map<Long, String> WORDS = new HashMap<>();
{ "domain": "codereview.stackexchange", "id": 43496, "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, integer, numbers-to-words", "url": null }
java, integer, numbers-to-words private static final Map<Long, String> WORDS = new HashMap<>(); static { WORDS.put(1L, "one"); WORDS.put(2L, "two"); WORDS.put(3L, "three"); WORDS.put(4L, "four"); WORDS.put(5L, "five"); WORDS.put(6L, "six"); WORDS.put(7L, "seven"); WORDS.put(8L, "eight"); WORDS.put(9L, "nine"); WORDS.put(10L, "ten"); WORDS.put(11L, "eleven"); WORDS.put(12L, "twelve"); WORDS.put(13L, "thirteen"); WORDS.put(14L, "fourteen"); WORDS.put(15L, "fifteen"); WORDS.put(16L, "sixteen"); WORDS.put(17L, "seventeen"); WORDS.put(18L, "eighteen"); WORDS.put(19L, "nineteen"); WORDS.put(20L, "twenty"); WORDS.put(30L, "thirty"); WORDS.put(40L, "fourty"); WORDS.put(50L, "fifty"); WORDS.put(60L, "sixty"); WORDS.put(70L, "seventy"); WORDS.put(80L, "eighty"); WORDS.put(90L, "ninety"); } /** * Spells an input long value as text. For example, for input 2048, the * return value will be "two thousand forty-eight". * * @param num the value to spell. * @return text representation of {@code num}. */ public static String spell(long num) { if (num == Long.MIN_VALUE) { return "(not supported)"; } else if (num == 0) { return "zero"; } StringBuilder sb = new StringBuilder(); if (num < 0) { sb.append("minus "); num = -num; } int orderOfMagnitude = 0; Deque<Pair> parts = new ArrayDeque<>(); do { parts.addLast( new Pair(BIG_NUMBERS[orderOfMagnitude++].getName(), num % 1_000L)); num /= 1_000L; } while (num > 0);
{ "domain": "codereview.stackexchange", "id": 43496, "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, integer, numbers-to-words", "url": null }
java, integer, numbers-to-words num /= 1_000L; } while (num > 0); while (parts.size() > 1) { Pair pair = parts.removeLast(); convertHundredsImpl( pair.number, sb).append(" ") .append(pair.name) .append(" "); } convertHundredsImpl(parts.removeLast().number, sb); return sb.toString().trim(); } // Converts a num in range [0, 999] to the human readable string: private static StringBuilder convertHundredsImpl(long num, StringBuilder sb) { long hundreds = num / 100; num -= 100 * hundreds; if (hundreds > 0) { sb.append(WORDS.get(hundreds)); sb.append(" hundred "); } if (num > 0) { String tensString = WORDS.get(num); if (tensString == null) { long units = num % 10; num -= units; sb.append(WORDS.get(num)); sb.append("-"); sb.append(WORDS.get(units)); } else { sb.append(tensString); } } return sb; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLong()) { long num = scanner.nextLong(); String s = spell(num); System.out.println(s); } } } Critique request So what do you think? Am I getting it right? Answer: Some thoughts Looking up names for numbers Your WORDS Map looks rather like a "code smell" - otherwise you'd have been able to find a much better name for it. In my suggestions for your previous post along these lines, I had at least two reasons to split the map into two arrays :-
{ "domain": "codereview.stackexchange", "id": 43496, "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, integer, numbers-to-words", "url": null }
java, integer, numbers-to-words It contains two similar, but not equivalent types of names, which are going to be handled differently, so they make more sense stored separately Using arrays for the look-up of names for numbers is natural, and more efficient than using a Map - leaving aside the overhead of creating the map, the boxing and unboxing of the numbers is a significant overhead. I'd sooner worry about the overhead of using a Map vs the efficiency of "do...while" vs "while". addLast/removeLast If you are doing stack operations, they can be more naturally expressed using a Deque implementation (such as java.util.ArrayDeque) - push() and pop(). Yes, I know they are equivalent operations, but push and pop better convey your intentions to readers of the code. However I'm far from convinced of the need for this processing which seems to be an artifact of the ordering of the BIG_NUMBERS table. In English we spell numbers from left to right, so it seems much more natural for your code to process them that way. Pair and BigNumber Apart from the order of the fields, and the difference between long and Long (did Pair need to contain Long?), these classes look very similar - couldn't you just have one? Of course, if you order the BIG_NUMBER table descending in size, you don't even need the Pair class. convertHundredsImpl We usually use the "Impl" suffix for the implementation of an abstract "thing" - why use it here? Overall This just looks bigger and more complex than it needs to be.
{ "domain": "codereview.stackexchange", "id": 43496, "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, integer, numbers-to-words", "url": null }
java, game, swing, tetris Title: Simple Java Tetris game Question: I have no IT background and taught myself Java and made a simple Tetris game. I compared my code on the internet with other tutorials. My first impression of those implementations is that they are very complex: Shape-classes, No-Shape-shape, rotation arrays etc. The location of a shape in the grid is also the shape's central/rotation point. A shape is an array of 4 Points/coordinates relative to the shapes central/rotation point. Is my code too simple? I would like some feedback. Here is my code: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel;
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris public class Tetris extends JFrame implements Runnable { final private static String I = "i"; final private static String O = "o"; final private static String J = "j"; final private static String L = "l"; final private static String T = "t"; final private static String S = "s"; final private static String Z = "z"; final private static HashMap SHAPE = new HashMap(); final private static HashMap COLOR = new HashMap(); final private int X = 10; final private int Y = 20; final private int SIZE = Toolkit.getDefaultToolkit().getScreenSize().height / 2 / Y; final private int MIN = 100; final private int MAX = 750; final private int DELAY = 5; final private JLabel PIECE = new JLabel() { @Override public void paint(Graphics g) { g.setColor((Color) COLOR.get(getText())); for (Point p : block) { g.fillRect((location.x + p.x) * SIZE, (location.y + p.y) * SIZE, SIZE, SIZE); } } }; final private JLabel NEXT = new JLabel((String) SHAPE.keySet().toArray()[new Random().nextInt(SHAPE.size())]) { @Override public void paint(Graphics g) { g.setColor((Color) COLOR.get(getText())); for (Point p : (Point[]) SHAPE.get(getText())) { g.fillRect(getWidth() / 2 + (int) ((p.x - 0.5) * SIZE), (p.y + 2) * SIZE, SIZE, SIZE); } } }; final private JLabel GAME_OVER = new JLabel("Game over", JLabel.CENTER); final private JLabel SCORE = new JLabel("0", JLabel.RIGHT); final private JButton START = new JButton("Start"); private ArrayList<Color[]> grid = new ArrayList(Arrays.asList(new Color[Y][X])); private Point location; private Point[] block;
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris public Tetris() { JLayeredPane board = new JLayeredPane(); JPanel statusPanel = new JPanel(new BorderLayout()); board.setOpaque(true); board.setBackground(Color.lightGray); board.add(new JPanel() { @Override public void paint(Graphics g) { for (int y = 0; y < Y; y++) { for (int x = 0; x < X; x++) { if (grid.get(y)[x] != null) { g.setColor(grid.get(y)[x]); g.fillRect(x * SIZE, y * SIZE, SIZE, SIZE); } } } } }); board.add(PIECE, new Integer(1)); board.add(GAME_OVER, new Integer(2)); board.setPreferredSize(new Dimension(X * SIZE, Y * SIZE)); for (Component c : board.getComponents()) { c.setSize(board.getPreferredSize()); }
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris statusPanel.add(SCORE, BorderLayout.NORTH); statusPanel.add(START, BorderLayout.CENTER); statusPanel.add(NEXT, BorderLayout.SOUTH); PIECE.setVisible(false); PIECE.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { blockXY(location.x - 1, location.y, block); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { blockXY(location.x + 1, location.y, block); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { blockXY(location.x, location.y + 1, block); } else if (e.getKeyCode() == KeyEvent.VK_SPACE && !PIECE.getText().equals(O)) { Point[] rotated = new Point[block.length]; int x = location.x; for (int i = 0; i < rotated.length; i++) { rotated[i] = new Point(block[i].y, -block[i].x); x = Math.max(-rotated[i].x, Math.min(x, X - 1 - rotated[i].x)); } blockXY(x, location.y, rotated); } } }); PIECE.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { PIECE.requestFocus(); } }); GAME_OVER.setVisible(false); GAME_OVER.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, GAME_OVER.getHeight() / 12)); SCORE.setFont(GAME_OVER.getFont()); START.setFont(GAME_OVER.getFont()); START.setBorder(null); START.setContentAreaFilled(false); START.setFocusPainted(false); START.addActionListener(e -> new Thread(this).start()); NEXT.setPreferredSize(new Dimension(PIECE.getHeight() / 3, PIECE.getHeight() / 3));
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris NEXT.setPreferredSize(new Dimension(PIECE.getHeight() / 3, PIECE.getHeight() / 3)); add(board, BorderLayout.WEST); add(statusPanel, BorderLayout.EAST); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setVisible(true); pack(); } private synchronized boolean blockXY(int x, int y, Point[] block) { for (Point p : block) { if (x + p.x == -1 || x + p.x == X || y + p.y >= Y || (y + p.y > -1 && grid.get(y + p.y)[x + p.x] != null)) { return false; } } location = new Point(x, y); this.block = block; repaint(); return true; } @Override public void run() { START.setVisible(false); grid = new ArrayList(Arrays.asList(new Color[Y][X])); SCORE.setText("0"); GAME_OVER.setVisible(false); String choice = I + O + J + L + T + S + Z; do { PIECE.setText(NEXT.getText()); NEXT.setText(choice.split("")[new Random().nextInt(choice.length())]); location = new Point(X / 2, -2); block = (Point[]) SHAPE.get(PIECE.getText()); PIECE.setVisible(true); do { try { Thread.sleep(Math.max(MIN, MAX - Integer.parseInt(SCORE.getText()) * DELAY)); } catch (Exception ex) { } PIECE.setVisible(blockXY(location.x, location.y + 1, block)); } while (PIECE.isVisible()); for (Point p : block) { try { grid.get(location.y + p.y)[location.x + p.x] = (Color) COLOR.get(PIECE.getText()); } catch (Exception ex) { GAME_OVER.setVisible(true); } }
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris if (!GAME_OVER.isVisible()) { for (int y = 0; y < Y; y++) { if (!Arrays.asList(grid.get(y)).contains(null)) { grid.set(y, new Color[X]); repaint(); try { Thread.sleep(800); } catch (Exception ex) { } grid.add(0, grid.remove(y)); SCORE.setText("" + (Integer.parseInt(SCORE.getText()) + 1)); } } choice = (I + O + J + L + T + S + Z).replace(NEXT.getText(), NEXT.getText().replace(PIECE.getText(), "")); } else { try { Thread.sleep(1200); } catch (Exception ex) { } START.setVisible(true); START.requestFocus(); } } while (!GAME_OVER.isVisible()); } public static void main(String[] args) { SHAPE.put(I, new Point[] {new Point(0, -2), new Point(0, -1), new Point(0, 0), new Point(0, 1)}); SHAPE.put(O, new Point[] {new Point(0, 0), new Point(-1, 0), new Point(0, 1), new Point(-1, 1)}); SHAPE.put(J, new Point[] {new Point(0, -1), new Point(0, 0), new Point(0, 1), new Point(-1, 1)}); SHAPE.put(L, new Point[] {new Point(0, -1), new Point(0, 0), new Point(0, 1), new Point(1, 1)}); SHAPE.put(T, new Point[] {new Point(-1, 0), new Point(0, 0), new Point(1, 0), new Point(0, 1)}); SHAPE.put(S, new Point[] {new Point(1, 0), new Point(0, 0), new Point(0, 1), new Point(-1, 1)}); SHAPE.put(Z, new Point[] {new Point(-1, 0), new Point(0, 0), new Point(0, 1), new Point(1, 1)}); COLOR.put(I, Color.cyan); COLOR.put(O, Color.yellow); COLOR.put(J, Color.blue); COLOR.put(L, Color.orange); COLOR.put(T, Color.magenta); COLOR.put(S, Color.green); COLOR.put(Z, Color.red);
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris COLOR.put(S, Color.green); COLOR.put(Z, Color.red); new Tetris().setLocationRelativeTo(null); } }
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris Answer: Is my code too simple? We need to unpack that a little, because we're probably operating on different definitions of "simple". Your application has only one file and one top-level class. Whereas that is in one sense simple, it's not a very good idea as it hinders maintainability and legibility, and actually implies more complexity when it comes to cognitive load - understanding how your code is laid out and being able to modify and test it meaningfully. You should attempt to subdivide and modularise. A battle-weary programmer's idea of simplicity is quite different, and involves smaller, more well-defined classes; better separation of concerns; etc. On a more granular level: Your single-letter constants are a code smell, and suggest that you're actually attempting to capture an enum of some kind. SHAPE and COLOR shouldn't be capitalised I think; need <> type parameters; and it's important that they be initialised inline instead of outside of the instance, something like private final Map<String, Point[]> shapes = Map.ofEntries( entry(I, new Point[] {new Point( 0, -2), new Point( 0, -1), new Point(0, 0), new Point( 0, 1)}), entry(O, new Point[] {new Point( 0, 0), new Point(-1, 0), new Point(0, 1), new Point(-1, 1)}), entry(J, new Point[] {new Point( 0, -1), new Point( 0, 0), new Point(0, 1), new Point(-1, 1)}), entry(L, new Point[] {new Point( 0, -1), new Point( 0, 0), new Point(0, 1), new Point( 1, 1)}), entry(T, new Point[] {new Point(-1, 0), new Point( 0, 0), new Point(1, 0), new Point( 0, 1)}), entry(S, new Point[] {new Point( 1, 0), new Point( 0, 0), new Point(0, 1), new Point(-1, 1)}), entry(Z, new Point[] {new Point(-1, 0), new Point( 0, 0), new Point(0, 1), new Point( 1, 1)}) );
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
java, game, swing, tetris private final Map<String, Color> colors = Map.ofEntries( entry(I, Color.cyan), entry(O, Color.yellow), entry(J, Color.blue), entry(L, Color.orange), entry(T, Color.magenta), entry(S, Color.green), entry(Z, Color.red) ); The fact that colors and shapes have the same cardinality suggests that there's a class there that you need to capture, having members for points and color. The expression grid.get(y)[x] needs to go into a variable for reuse. Don't new Integer(1); just write 1. This predicate: if (x + p.x == -1 || x + p.x == X || y + p.y >= Y || (y + p.y > -1 && grid.get(y + p.y)[x + p.x] != null)) { should be line-separated: if (x + p.x == -1 || x + p.x == X || y + p.y >= Y || (y + p.y > -1 && grid.get(y + p.y)[x + p.x] != null) ) { It's probably not a good idea for you to new Random() on the inside of run() in a loop. You should have a single Random instance, potentially as a member on the class but at the very least removed from that loop. catch (Exception ex) is poison to a program's debug-ability. It needs to go away, and if you're concerned about a specific exception from the try block, catch that instead.
{ "domain": "codereview.stackexchange", "id": 43497, "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, game, swing, tetris", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame Title: How can I make my Pygame Tic Tac Toe game better? Question: I have this code ready and it works just fine. But what are the ways by which I can improve this code? I have no CS background and this is my first coding project. I could not paste my entire code so I'm posting my github project link. Any recommendations on that would also be appreciated. import pygame pygame.init() window = pygame.display.set_mode((600,600)) pygame.display.set_caption("Tic Tac Toe") white = (255,255,255) Circle = pygame.image.load('Cross.png') Cross = pygame.image.load('Circle.png') clicks = [] load1 = False load2 = False load3 = False load4 = False load5 = False load6 = False load7 = False load8 = False load9 = False load10 = False load11 = False load12 = False load13 = False load14 = False load15 = False load16 = False load17 = False load18 = False def Background(): window.fill(white) pygame.draw.rect(window, (0,0,0),( 198,0,4,600)) pygame.draw.rect(window, (0,0,0),( 398,0,4,600)) pygame.draw.rect(window, (0,0,0),( 0,198,600,4)) pygame.draw.rect(window, (0,0,0),( 0,398,600,4)) pygame.display.flip() run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False mouse = pygame.mouse.get_pressed()[0] mouse_x,mouse_y = pygame.mouse.get_pos() if len(clicks)%2 != 0: if mouse: if mouse_x > 0 and mouse_x < 198 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load1 = True elif mouse_x > 0 and mouse_x < 198 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load2 = True elif mouse_x > 0 and mouse_x < 198 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load3 = True
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame elif mouse_x > 202 and mouse_x < 398 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load4 = True elif mouse_x > 202 and mouse_x < 398 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load5 = True elif mouse_x > 202 and mouse_x < 398 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load6 = True elif mouse_x > 402 and mouse_x < 600 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load7 = True elif mouse_x > 402 and mouse_x < 600 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load8 = True elif mouse_x > 402 and mouse_x < 600 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load9 = True elif len(clicks)%2 == 0: if mouse: if mouse_x > 0 and mouse_x < 198 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load10 = True elif mouse_x > 0 and mouse_x < 198 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load11 = True elif mouse_x > 0 and mouse_x < 198 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load12 = True elif mouse_x > 202 and mouse_x < 398 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load13 = True elif mouse_x > 202 and mouse_x < 398 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load14 = True elif mouse_x > 202 and mouse_x < 398 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load15 = True
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame elif mouse_x > 402 and mouse_x < 600 and mouse_y > 0 and mouse_y < 198: clicks.append(mouse) load16 = True elif mouse_x > 402 and mouse_x < 600 and mouse_y > 202 and mouse_y < 398: clicks.append(mouse) load17 = True elif mouse_x > 402 and mouse_x < 600 and mouse_y > 402 and mouse_y < 600: clicks.append(mouse) load18 = True if load1: window.blit(Circle, (0,0)) if load2: window.blit(Circle, (0,201)) if load3: window.blit(Circle, (0,401)) if load4: window.blit(Circle, (201,0)) if load5: window.blit(Circle, (201,201)) if load6: window.blit(Circle, (201,401)) if load7: window.blit(Circle, (401,0)) if load8: window.blit(Circle, (401,201)) if load9: window.blit(Circle, (401,401)) if load10: window.blit(Cross, (0,0)) if load11: window.blit(Cross, (0,201)) if load12: window.blit(Cross, (0,401)) if load13: window.blit(Cross, (201,0)) if load14: window.blit(Cross, (201,201)) if load15: window.blit(Cross, (201,401)) if load16: window.blit(Cross, (401,0)) if load17: window.blit(Cross, (401,201)) if load18: window.blit(Cross, (401,401)) if ((load1 and load2 and load3) or (load2 and load5 and load8) or (load3 and load6 and load9) or (load1 and load4 and load7) or (load4 and load5 and load6) or (load7 and load8 and load9) or (load1 and load5 and load9) or (load3 and load5 and load7)): print("Circle Wins")
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame elif ((load10 and load11 and load12) or (load13 and load14 and load15) or (load16 and load17 and load18) or (load10 and load13 and load16) or (load11 and load14 and load17) or(load12 and load15 and load18) or (load10 and load14 and load18) or (load13 and load14 and load16)): print("Cross Wins") pygame.display.update() Background() pygame.quit() Answer: These points are in order of how I went through your program. They are not ordered in matter of importance. Your code is suspicious from the start: Circle = pygame.image.load('Cross.png') Cross = pygame.image.load('Circle.png') Why? What prompted you to define a a circle as a cross and vice versa? Either way, the variable names start with a Capital while all other variables do not. Considering Python is a case-sensitive language, please keep all variable names lowercase to prevent confusion. Your code does not specify anywhere what the expected sizes of Cross.png and Circle.png are. Which means my first game looked like this: The pictures aren't correctly centred in their square, so the second game (with modified cross/circle files) looked like this: The cross in the middle square is misaligned, too far on the top-left of the corner. With the earlier game, it didn't do this. If you ship/share code without shipping/sharing the pictures, like you did when posting your question, make sure you either: leave a note somewhere either in the documentation or the code itself which states the required sizes. enforce the program won't start by checking the dimensions of the pictures. scale the images in your program so they'll always be made to fit. Your code only counts the clicks made. Not whether any of those clicks were correct. If I tap an already selected square again, I can make this game happen: Or this:
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame Or this: Because you're keeping track of each square twice, once for circle and once for cross, it sometimes happens that I can overwrite a square with a circle. Or that the logic of the program no longer corresponds with the visual representation, leading to a very confusing win: Long story short, your program is very easy to break. 5+ games in I got more rounds that didn't go according to expectations than games that did. This is how the program currently keeps track of the squares: load1 = False load2 = False load3 = False load4 = False load5 = False load6 = False load7 = False load8 = False load9 = False load10 = False load11 = False load12 = False load13 = False load14 = False load15 = False load16 = False load17 = False load18 = False load is an incredibly bad name for a variable. My first guess would be that it loads something externally, not that it's the state of an internal part. state or square would have been better. And while we're at it, might as well turn it into a list. While we could start with an empty list and append a False 18x times, we can also do it the Python way and use a list comprehension: states = [False for x in range(18)] Which can be called like states[3] (0-indexed, so 0..17 are valid). However, we don't want 18 values. There are only 9 squares and each square should only be fillable once. You're currently tracking each square twice, which is a good way to get bugs. Instead of 2 bool per square, we can give each square a State using Enum. The following example: from enum import Enum class State(Enum): FREE = 1 CIRCLE = 2 CROSS = 3 states = [State.FREE for x in range(9)] states[4] = State.CIRCLE states[6] = State.CROSS for i in states: print(i, type(i)) Produces the following output:
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame for i in states: print(i, type(i)) Produces the following output: State.FREE <enum 'State'> State.FREE <enum 'State'> State.FREE <enum 'State'> State.FREE <enum 'State'> State.CIRCLE <enum 'State'> State.FREE <enum 'State'> State.CROSS <enum 'State'> State.FREE <enum 'State'> State.FREE <enum 'State'> Now a square can no longer be a circle and a cross at the same time, not even by accident. Before overwriting, the square can be checked whether it's free. If it's not free, it can't be written to. Only after a successful write, should the game change players. This means we'll have to do away with the clicks list, stop appending the mouse location to anywhere and just handle the input. If it was right, act. If it was wrong, don't act. The easiest (not necessarily the best) way to keep track of a player, is using a player variable. We could use a bool, but why not make it an Enum instead? After all, we can toggle (invert the value) of an Enum just as easily as we can with a bool, if we pick the values right. class Player(Enum): CIRCLE = 1 CROSS = -1 Now, if we want to switch players, all we have to do is: player = Player(player.value * -1) Don't mind my poor naming, but functionally we're making progress. When checking for a player win, you print who won. However, you don't pause/exit the game and continue to accept input. This is unwanted. All we need to fix this using the already existing while run loop. You do have a pygame.quit() at the end of your program, but by the time the code reaches there the program will be terminated anyway. You don't need it. Just turn run to False. Then the validation of the win can be simplified: def is_3_in_row(a, b, c, sign): return states[a] == State.CIRCLE and states[b] == State.CIRCLE \ and states[c] == sign
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame Your board also doesn't recognize a tie (9 filled squares without winner). If we account for all that, we can wrap most of the program into a main guard. This will prevent the game from accidentally running if you later decide to import the file in a different program. All remaining global variables that will not be changed after being defined are now UPPER_CASE, see PEP 8. Background is now background. Your comma's (,) also got a bit of breathing room, making the code easier to read. The score so far: import pygame from enum import Enum class State(Enum): CIRCLE = 1 CROSS = 2 FREE = 3 class Player(Enum): CIRCLE = 1 CROSS = -1 def background(window): window.fill(WHITE) pygame.draw.rect(window, (0, 0, 0), (198, 0, 4, 600)) pygame.draw.rect(window, (0, 0, 0), (398, 0, 4, 600)) pygame.draw.rect(window, (0, 0, 0), (0, 198, 600, 4)) pygame.draw.rect(window, (0, 0, 0), (0, 398, 600, 4)) WHITE = (255, 255, 255) CIRCLE = pygame.image.load('Circle.png') CROSS = pygame.image.load('Cross.png') def main(): pygame.init() pygame.display.set_caption("Tic Tac Toe") window = pygame.display.set_mode((600, 600)) pygame.display.flip() states = [State.FREE for x in range(9)] player = Player.CIRCLE run = True def is_3_in_row(a, b, c, sign): return states[a] == State.CIRCLE and states[b] == State.CIRCLE \ and states[c] == sign while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame mouse = pygame.mouse.get_pressed()[0] mouse_x, mouse_y = pygame.mouse.get_pos() if mouse: if mouse_x > 0 and mouse_x < 198 and mouse_y > 0 and mouse_y < 198: if states[0] is State.FREE: if player == player.CIRCLE: states[0] = State.CIRCLE elif player == player.CROSS: states[0] = State.CROSS player = Player(player.value * -1) elif mouse_x > 0 and mouse_x < 198 and mouse_y > 202 and mouse_y < 398: if states[1] is State.FREE: if player == player.CIRCLE: states[1] = State.CIRCLE elif player == player.CROSS: states[1] = State.CROSS player = Player(player.value * -1) elif mouse_x > 0 and mouse_x < 198 and mouse_y > 402 and mouse_y < 600: if states[2] is State.FREE: if player == player.CIRCLE: states[2] = State.CIRCLE elif player == player.CROSS: states[2] = State.CROSS player = Player(player.value * -1) elif mouse_x > 202 and mouse_x < 398 and mouse_y > 0 and mouse_y < 198: if states[3] is State.FREE: if player == player.CIRCLE: states[3] = State.CIRCLE elif player == player.CROSS: states[3] = State.CROSS player = Player(player.value * -1) elif mouse_x > 202 and mouse_x < 398 and mouse_y > 202 and mouse_y < 398: if states[4] is State.FREE: if player == player.CIRCLE: states[4] = State.CIRCLE elif player == player.CROSS: states[4] = State.CROSS player = Player(player.value * -1)
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame player = Player(player.value * -1) elif mouse_x > 202 and mouse_x < 398 and mouse_y > 402 and mouse_y < 600: if states[5] is State.FREE: if player == player.CIRCLE: states[5] = State.CIRCLE elif player == player.CROSS: states[5] = State.CROSS player = Player(player.value * -1) elif mouse_x > 402 and mouse_x < 600 and mouse_y > 0 and mouse_y < 198: if states[6] is State.FREE: if player == player.CIRCLE: states[6] = State.CIRCLE elif player == player.CROSS: states[6] = State.CROSS player = Player(player.value * -1) elif mouse_x > 402 and mouse_x < 600 and mouse_y > 202 and mouse_y < 398: if states[7] is State.FREE: if player == player.CIRCLE: states[7] = State.CIRCLE elif player == player.CROSS: states[7] = State.CROSS player = Player(player.value * -1) elif mouse_x > 402 and mouse_x < 600 and mouse_y > 402 and mouse_y < 600: if states[8] is State.FREE: if player == player.CIRCLE: states[8] = State.CIRCLE elif player == player.CROSS: states[8] = State.CROSS player = Player(player.value * -1)
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame if states[0] == State.CIRCLE: window.blit(CIRCLE, (0, 0)) elif states[0] == State.CROSS: window.blit(CROSS, (0, 0)) if states[1] == State.CIRCLE: window.blit(CIRCLE, (0, 201)) elif states[1] == State.CROSS: window.blit(CROSS, (0, 201)) if states[2] == State.CIRCLE: window.blit(CIRCLE, (0, 401)) elif states[2] == State.CROSS: window.blit(CROSS, (0, 401)) if states[3] == State.CIRCLE: window.blit(CIRCLE, (201, 0)) elif states[3] == State.CROSS: window.blit(CROSS, (201, 0)) if states[4] == State.CIRCLE: window.blit(CIRCLE, (201, 201)) elif states[4] == State.CROSS: window.blit(CROSS, (201, 201)) if states[5] == State.CIRCLE: window.blit(CIRCLE, (201, 401)) elif states[5] == State.CROSS: window.blit(CROSS, (201, 401)) if states[6] == State.CIRCLE: window.blit(CIRCLE, (401, 0)) elif states[6] == State.CROSS: window.blit(CROSS, (401, 0)) if states[7] == State.CIRCLE: window.blit(CIRCLE, (401, 201)) elif states[7] == State.CROSS: window.blit(CROSS, (401, 201)) if states[8] == State.CIRCLE: window.blit(CROSS, (401, 401)) elif states[8] == State.CROSS: window.blit(CROSS, (401, 401)) if (is_3_in_row(0, 1, 2, State.CIRCLE) or is_3_in_row(1, 4, 7, State.CIRCLE) or is_3_in_row(2, 5, 8, State.CIRCLE) or is_3_in_row(0, 3, 6, State.CIRCLE) or is_3_in_row(3, 4, 5, State.CIRCLE) or is_3_in_row(6, 7, 8, State.CIRCLE) or is_3_in_row(0, 4, 8, State.CIRCLE) or is_3_in_row(2, 4, 6, State.CIRCLE)): print("Circle wins") run = False
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
python, beginner, python-3.x, tic-tac-toe, pygame elif (is_3_in_row(0, 1, 2, State.CROSS) or is_3_in_row(1, 4, 7, State.CROSS) or is_3_in_row(2, 5, 8, State.CROSS) or is_3_in_row(0, 3, 6, State.CROSS) or is_3_in_row(3, 4, 5, State.CROSS) or is_3_in_row(6, 7, 8, State.CROSS) or is_3_in_row(0, 4, 8, State.CROSS) or is_3_in_row(2, 4, 6, State.CROSS)): print("Cross wins") run = False elif all((state == State.CIRCLE or state == State.CROSS) for state in states): print("It's a tie") run = False pygame.display.update() background(window) if __name__ == "__main__": main() Is this as good as it can get? Absolutely not. We can simplify the part setting the new state of the square, by putting the logic behind a function. Including the player = Player(player.value * -1), but not without a long explanation about scope. So I will leave that for another time. If you work out what the relationships between the various coordinates of a square are, you can make a pre-defined datastructure that works out the coordinates for you instead of having to do all the adjustments in all 9 cells when something has to be adjusted (for example, if you ever increase your window-size to anything bigger than 600x600.
{ "domain": "codereview.stackexchange", "id": 43498, "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, beginner, python-3.x, tic-tac-toe, pygame", "url": null }
api, typescript, type-safety, client Title: API client that builds a response over multiple lines Question: I am performing a REST API call and I have copied their example code where they show how to perform such an api call. Their example is written in Javascript not Typescript though. To adapt the code I had to create a type type serviceConfig = {[key: string]: any} so that the variable config can be successively appended to. It is my understanding that any should be avoided where possible. How could I avoid using any in this case? Should I be avoiding coding patterns where I successively append to a variable? Should I instead create a type which describes config more accurately e.g. type serviceConfig = { baseURL?: string, method? string ... etc.} Or is this one of the times where any is acceptable? import axios from 'axios'; import crypto from 'crypto'; import FormData from 'form-data'; // These parameters should be used for all requests const SERVICE_APP_TOKEN = process.env.SERVICE_TOKEN!; // Example: sbx:uY0CgwELmgUAEyl4hNWxLngb.0WSeQeiYny4WEqmAALEAiK2qTC96fBad const SERVICE_SECRET_KEY = process.env.SERVICE_SECRET_KEY!; // Example: Hej2ch71kG2kTd1iIUDZFNsO5C1lh5Gq const SERVICE_BASE_URL = 'https://api.example.com'; type serviceConfig = { [key: string]: any } var config: serviceConfig = {} config.baseURL = SERVICE_BASE_URL; function createSignature(config: serviceConfig) { console.log('Creating a signature for the request...'); const ts = Math.floor(Date.now() / 1000); const signature = crypto.createHmac('sha256', SERVICE_SECRET_KEY); signature.update(ts + config.method.toUpperCase() + config.url); if (config.data instanceof FormData) { signature.update(config.data.getBuffer()); } else if (config.data) { signature.update(config.data); } config.headers['X-App-Access-Ts'] = ts; config.headers['X-App-Access-Sig'] = signature.digest('hex'); return config; }
{ "domain": "codereview.stackexchange", "id": 43499, "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": "api, typescript, type-safety, client", "url": null }
api, typescript, type-safety, client return config; } axios.interceptors.request.use(createSignature, function (error) { return Promise.reject(error) }) export function createAccessToken(externalUserId: string, levelName = 'basic-kyc-level', ttlInSecs = 600) { console.log("Creating an access token for initializng SDK..."); var method = 'post'; var url = `/resources/accessTokens?userId=${externalUserId}&ttlInSecs=${ttlInSecs}&levelName=${levelName}`; var headers = { 'Accept': 'application/json', 'X-App-Token': SERVICE_APP_TOKEN }; config.method = method; config.url = url; config.headers = headers; config.data = null; return config; } async function run() { const externalUserId = "random-JSToken-" + Math.random().toString(36).substr(2, 9); const levelName = 'basic-kyc-level'; console.log("External UserID: ", externalUserId); const response = await axios(createAccessToken(externalUserId, levelName, 1200)) .then(function (response) { console.log("Response:\n", response.data); return response; }) .catch(function (error) { console.log("Error:\n", error.response.data); }); console.log(response) } run();
{ "domain": "codereview.stackexchange", "id": 43499, "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": "api, typescript, type-safety, client", "url": null }
api, typescript, type-safety, client } run(); Answer: By using any you are losing type safety, which defeats the point of Typescript, at least in this spot. But sometimes it’s just easier. Just because the example is written in JavaScript doesn’t mean there aren’t types provided for Typescript for the config object. Check the docs and the sources for the correct imports. Or yes, you could define more specific types especially if you are using this in many other places and the API really doesn’t provide types (which seems unlikely in this case). Maybe overkill if this is all there is. Successive appending - if by that you mean separate statements to assign the properties there is nothing wrong with that, but that’s not what your type means. You could set config to an object literal: config = { method, url, headers, data: null } Or even just: return { method, url, headers, data: null }
{ "domain": "codereview.stackexchange", "id": 43499, "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": "api, typescript, type-safety, client", "url": null }
c++, recursion, combinatorics, math-expression-eval Title: Boolean evaluation Question: Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^ (XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesising the expression such that it evaluates to result. EXAMPLES: countEval("1^0|0|1", false) -> 2; countEval("0&0&0&1^1|0", true) -> 10 This is my implementation; any feedback/suggestions would be very much appreciated. #include <iostream> #include <string> #include <algorithm> inline bool charToBool (const char& c1) { if(c1 == '1') return true; else return false; } // the par function recursively calls itself such that it can // "create" every possible parenthesisation around every operation. // Next, it counts the number of boolean values that were calculated // returns count of true possibile booleans, // respectively count of false possibile booleans, // in all iterations of paranthesisation of // str expression from [first, last) std::pair<int, int> par(const std::string& str, const int first, const int last) { // substrLen is the length of the current parenthesis int substrLen = last-first; // base condition if(substrLen == 1){ if(charToBool(str[first])) return {1, 0}; else return {0, 1}; } std::pair<int, int> total = {0, 0}; // function par iterates through all possible parenthesis lengths // from index first, then recursively calls itself // for the rest of said expression str for(int len = 1; len <= substrLen-2; len+=2) { // pairs left and right represent the left parenthesis, // respectively right parenthesis of expressions, // compared to the token of operation std::pair<int, int> left = par(str, first, first+len); std::pair<int, int> right = par(str, first+len+1, last); switch(str[first+len]) { case '|':
{ "domain": "codereview.stackexchange", "id": 43500, "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++, recursion, combinatorics, math-expression-eval", "url": null }
c++, recursion, combinatorics, math-expression-eval switch(str[first+len]) { case '|': total.first += left.first*right.second + left.second*right.first + left.first*right.first; total.second += left.second*right.second; break; case '&': total.first += std::min(left.first, right.first); total.second += left.first*right.second + left.second*right.first + left.second*right.second; break; case '^': total.first += left.first*right.second + left.second*right.first; total.second += left.first*right.first + left.second*right.second; break; } } return total; } // the countEval function returns count // of target bool, after parenthesizing // through the par function int countEval(const std::string& str, const bool& target) { // checks if string is valid // (it must be of uneven size) if(str.size() % 2 == 0) return 0; std::pair<int, int> res = par(str, 0, str.size()); // first number of pair res is the true number count // second number of pair res is the false number count if(target) return res.first; else return res.second; } int main() { const std::string str = "0&0&0&1^1|0"; int res = countEval(str, true); std::cout << "res = " << res << '\n'; return 0; } // TIME COMPLEXITY: O(n^3); // SPACE COMPLEXITY : o(n^2); // where n is the length of std::string str Answer: Time complexity cannot be \$n^3\$. There are just too many ways to parenthesize the string, and the code inspects them all. I run an experiment counting a number of calls to par for the strings of different length. and the results (length of string vs number of calls) are 7 27 9 81 11 243 13 729 15 2187 17 6561
{ "domain": "codereview.stackexchange", "id": 43500, "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++, recursion, combinatorics, math-expression-eval", "url": null }
c++, recursion, combinatorics, math-expression-eval which curiously enough fits (exactly) the \$N = 3^{(n-1)/2}\$ relation. (Note that \$(n-1)/2\$ is a number of operators in a string). It will be an interesting exercise in combinatorics to prove that. total.first += std::min(left.first, right.first); looks like a bug to me. It should be total.first += left.first * right.first; All indices should be size_t rather than int. An implementation of charToBool is anti-idiomatic. It is a long way to say return c1 == '1';
{ "domain": "codereview.stackexchange", "id": 43500, "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++, recursion, combinatorics, math-expression-eval", "url": null }
python, python-3.x Title: Get some cryptocurrency rates from coingecko api Question: I'm currently learning some aspects of PEP8 and Python programming in general. Could you please code-review this little piece of code for me? I would be glad to hear any, even the smallest comments, thanks! from array import array from typing import NamedTuple from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() savedTokensArray = ['bitcoin', 'ethereum'] class CryptoCurrency(NamedTuple): currencyName: str currencyPrice: float def get_tokens_price(tokenIds: array) -> dict[str, float]: tokens = None for token in tokenIds: tokens = f'{tokens}, {token}' tokensList = cg.get_price(ids=tokens, vs_currencies='usd') data = [CryptoCurrency(currencyName=currency, currencyPrice=tokensList[currency]['usd']) for currency in tokensList] currencysDict = {} for token in data: currencysDict[token.currencyName] = token.currencyPrice return currencysDict resultDict = get_tokens_price(savedTokensArray) print(resultDict) Answer: First, PEP8 suggests using snake_case instead of camelCase for regular variable names, so you should rename those. def get_tokens_price(tokenIds: array) -> dict[str, float]: array is the wrong type annotation. This is not an array.array1 - this is a list of strings. list[str] . tokens = None for token in tokenIds: tokens = f'{tokens}, {token}' tokensList = cg.get_price(ids=tokens, vs_currencies='usd') No need for a for loop here - just use str.join. tokens_list = cg.get_price(ids=",".join(token_ids), vs_currencies='usd') You also construct a list of NamedTuples, just to use it to construct the dictionary that you return. Just construct the dictionary directly, and get rid of CryptoCurrency. You can also use dict.items() to iterate over (key, value) pairs directly. currencies = {currency: prices['usd'] for currency, prices in tokens_list.items()} Full code: from typing import NamedTuple from pycoingecko import CoinGeckoAPI
{ "domain": "codereview.stackexchange", "id": 43501, "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", "url": null }
python, python-3.x Full code: from typing import NamedTuple from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() saved_tokens = ['bitcoin', 'ethereum'] def get_token_prices(token_ids: list[str]) -> dict[str, float]: tokens_list = cg.get_price(ids=",".join(token_ids), vs_currencies='usd') currencies = {name: prices['usd'] for name, prices in tokens_list.items()} return currencies prices = get_token_prices(saved_tokens) print(prices) 1 arrays are a specialized type that are used for storing large sequences of numerical data.
{ "domain": "codereview.stackexchange", "id": 43501, "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", "url": null }
game, haskell, hangman Title: A simple hangman game in Haskell Question: I just finished a course of functional programming in uni and continued to study Haskell because I found it very interesting! I made a simple hangman game and would like to hear any of your thoughts and ideas that may arise looking at the code! What, for example, could make it more dogmatic in a functional programming sense? import Control.Monad import Data.List (elemIndices, sort) pictures = 9 main :: IO () main = do word <- getWord "" clearScreen hang word hang :: String -> IO () hang word = hang' word [] [] pictures hang' :: String -> [Char] -> [Char] -> Int -> IO () hang' word _ _ lives | lives == 0 = clearScreen >> putStrLn (renderHangman 0) >> putStrLn "You lost!" >> putStrLn ("The correct word was " ++ word ++ "\n") hang' word rights _ lives | win rights word = clearScreen >> putStrLn (renderHangman lives) >> putStrLn "You won!" >> putStrLn ("The correct word was " ++ word ++ "\n") hang' word rights wrongs lives = do clearScreen putStrLn $ renderHangman lives putStrLn $ renderWord rights word putStrLn $ renderLives lives putStrLn $ renderWrongs wrongs guess <- getGuess if guess `elem` (rights ++ wrongs) then hang' word rights wrongs lives else if correctGuess guess word then hang' word (guess : rights) wrongs lives else hang' word rights (guess : wrongs) (lives - 1) win :: [Char] -> String -> Bool win guesses = all (`elem` guesses) clearScreen :: IO () clearScreen = replicateM_ 100 (putStrLn "") correctGuess :: Char -> String -> Bool correctGuess guess word = guess `elem` word getGuess :: IO Char getGuess = do putStrLn "Guess a letter!" getChar getWord s = do clearScreen putStrLn "Give a secret word!" putStr ['*' | _ <- s] c <- getChar case c of '\n' -> return s char -> getWord (s ++ [char])
{ "domain": "codereview.stackexchange", "id": 43502, "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": "game, haskell, hangman", "url": null }
game, haskell, hangman renderWord :: [Char] -> String -> String renderWord guesses = foldr hide "" where hide = \x xs -> if x `elem` guesses then x : xs else '_' : xs renderWrongs :: [Char] -> String renderWrongs [] = "" renderWrongs wrongs = "Wrong guesses: " ++ sort wrongs renderHangman :: Int -> String renderHangman = unlines . hangmanpics renderLives :: Int -> String renderLives lives = show lives ++ " guesses left!" hangmanpics :: Int -> [String] hangmanpics 9 = [" ", " ", " ", " ", " ", " ", "========="] hangmanpics 8 = [" ", " |", " |", " |", " |", " |", "========="] hangmanpics 7 = [" +---+", " |", " |", " |", " |", " |", "========="] hangmanpics 6 = [" +---+", " | |", " |", " |", " |", " |", "========="] hangmanpics 5 = [" +---+", " | |", " O |", " |", " |", " |", " ========="] hangmanpics 4 = [" +---+", " | |", " O |", " | |", " |", " |", " ========="] hangmanpics 3 = [" +---+", " | |", " O |", " /| |", " |", " |", " ========="] hangmanpics 2 = [" +---+", " | |", " O |", " /|\\ |", " |", " |", " ========="] hangmanpics 1 = [" +---+", " | |", " O |", " /|\\ |", " / |", " |", " ========="] hangmanpics 0 = [" +---+", " | |", " O |", " /|\\ |", " / \\ |", " |", " ========="] hangmanpics _ = [" +---+", " | |", " O |", " /|\\ |", " / \\ |", " |", " ========="] ``` Answer: looks really good! Here are some suggestions, in rough order of significance The game essentially can be described by the three values word, rights, wrongs, and lives which you pass around between functions. For readability, I would suggest wrapping these up into a datatype: data GameState = GameState { word :: String , rights :: [Char] , wrongs :: [Char] , lives :: Int }
{ "domain": "codereview.stackexchange", "id": 43502, "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": "game, haskell, hangman", "url": null }
game, haskell, hangman The end of hang' feels convoluted. By "end" I mean the code after getGuess. The semantic structure is this: "update" the "game state", and then restart hang'. But it's not easy to see that with the current code structure, since each branch is its own "independent" call to hang'. Storing state in its own GameState type, we can cleanly split the code into the parts (1) update the state; (2) call hang'. To cut to the chase, it looks like this: guess <- getGuess let state' = if guess `elem` (rights state ++ wrongs state) then state else if correctGuess guess state then state { rights = guess : rights state } else state { wrongs = guess : wrongs state, lives = lives state - 1 } hang' state' [Char] is not quite an appropriate datatype for rights and wrongs. Using [Char] here suggests to me that you care about the order of the Chars in the list and how many times they show up, but in fact you do not. I would recommend Data.Set instead. (This will give you better performance, too!) getWord can be implemented more simply as clearScreen >> putStrLn "Give a secret word!" >> getLine win -- sleek implementation of this function! Unrelated, I would rename it. win sounds like an action, but really the function is a predicate. Perhaps isWin? As a general rule of thumb, I would try to avoid unqualified imports like import Control.Monad. If you have more than one unqualified import, it can become difficult to know where a function or operator is being imported from. getWord is missing its type signature, as is pictures. This is not a huge deal, but it's generally recommended to include type signatures on (at least) all top-level values.
{ "domain": "codereview.stackexchange", "id": 43502, "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": "game, haskell, hangman", "url": null }
game, haskell, hangman In some places you chain IO actions with >> and in others you use do notation. These are actually the same thing; thingOne >> thingTwo and do { thingOne; thingTwo; } are the same code. (It's unclear to me if you know this already) Anyway, for readability I would suggest using do for longer chains and >> or >>= for shorter expressions. Concretely, rewrite the clearScreen >> putStrLn ... parts of hang' using do, and then rewrite getGuess as putStrLn "Guess a letter!" >> getChar. Hope this helps :-) See the code with all changes made (except for using Set) here
{ "domain": "codereview.stackexchange", "id": 43502, "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": "game, haskell, hangman", "url": null }
performance, php, laravel Title: Laravel 9 - Metadata creation using middleware? Question: I wrote a middleware for laravel that grabs the current metadata for the specific URL you visit. How it works: we use the $request and compare the current URL: $request->getRequestUri() with the URL in the database table: So a User visits e.g. /features/landing my code would display the metadata (keywords, description) for the /features/landing in the database. Middleware: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class CreateMetadata { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $metadata = DB::table('seos') ->where('url', '=', $request->getRequestUri()) ->first(); view()->share('metadata', $metadata); return $next($request); } } how I call it in my web.php router (wrapped over all pages!): Route::middleware([CreateMetadata::class])->group(function () { then I have a component meta.blade.php I call on all pages: @if(isset($metadata)) {{-- primary meta tags --}} <title>{{$metadata->title}}</title> <meta name="title" content="{{$metadata->title}}"> <meta name="description" content="{{$metadata->description}}"> @endif Question: Is this a good practice? Are there better ways to implement this feature? Because if we look at the waterfall of the code execution this currently takes by FAR the biggest time on the website: Answer: Redis If you really need to use specific data and you don't have other ways to do it you can use Redis. Misc improvements (Not sure if this works with Laravel 9) You also should not save direct URL but instead route name with: \Request::route()->getName()
{ "domain": "codereview.stackexchange", "id": 43503, "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": "performance, php, laravel", "url": null }
performance, php, laravel \Request::route()->getName() This will allow you to change URL of your pages easily and not having to go in your database every time you change a URL. If you don't need every field from your app, use select title, description instead of select *: this can increase transfer speed (especially if your database server is not local). Sources (on Stack Overflow): Laravel: How to Get Current Route Name? Which is faster, SELECT * or SELECT `field` ?
{ "domain": "codereview.stackexchange", "id": 43503, "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": "performance, php, laravel", "url": null }
c, socket, winapi Title: Proper way to send and receive buffer in Winsock Question: I have a piece of code to send and receive buffers. Is this the right way to do it? And am I guaranteed that the full buffer will be sent and received? receiving function: #include <stdio.h> #include <winsock2.h> #include <ws2tcpip.h> #include <direct.h> #include <string.h> #include <stdint.h> static inline uint32_t ntohl_ch(char const* a) { uint32_t x; memcpy(&x, a, sizeof(x)); return ntohl(x); } char* recvStrBuffer(SOCKET s) { int totalReceived = 0; int received = 0; // recv buffer size char b[sizeof(uint32_t)]; int r = recv(s, b, sizeof(uint32_t), 0); if (r == SOCKET_ERROR) { printf("error recv\n"); return NULL; } uint32_t bufferSize = ntohl_ch(&b[0]); //printf("bufferSize: %d\n", bufferSize); char* buff = (char*)malloc(sizeof(char) * bufferSize); while (totalReceived < bufferSize) { received = recv(s, buff + totalReceived, bufferSize - totalReceived, 0); if (received == SOCKET_ERROR) { printf("error receiving buffer %d\n", WSAGetLastError()); return NULL; } totalReceived += received; //printf("received: %d\n", received); //printf("totalReceived: %d\n", totalReceived); } //printf("%s", buff); return buff; } sending function: #include <stdio.h> #include <winsock2.h> #include <ws2tcpip.h> #include <direct.h> #include <string.h> #include <stdint.h> int sendStrBuffer(SOCKET s, char* buffer) { // send buffer size int bufferSize = strlen(buffer); //printf("bufferSize: %d\n", bufferSize); uint32_t num = htonl(bufferSize); char* converted_num = (char*)&num; int res = send(s, converted_num, sizeof(uint32_t), 0); if (res == SOCKET_ERROR) { printf("error send\n"); return SOCKET_ERROR; }
{ "domain": "codereview.stackexchange", "id": 43504, "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, socket, winapi", "url": null }
c, socket, winapi int totalSent = 0; int sent = 0; while (totalSent < bufferSize) { sent = send(s, buffer + totalSent, bufferSize - totalSent, 0); if (sent == SOCKET_ERROR) { printf("error sending buffer\n"); return SOCKET_ERROR; } totalSent += sent; //printf("sent: %d\n", sent); //printf("totalSent: %d\n", totalSent); } } And then in main (receiving part): char* buffer; buffer = recvStrBuffer(socket); if (buffer == NULL) { printf("error %d\n", WSAGetLastError()); } printf("%s", buffer); free(buffer); Main (sending part): int r = sendStrBuffer(socket, totalBuffer); if (r == SOCKET_ERROR) { printf("error %d\n", WSAGetLastError()); } Answer: General Observations The code is mostly readable and except in one case maintainable. The exception may be a copy-and-paste error. Generally code isn't considered ready for review when it contains commented out debug statements such as //printf("bufferSize: %d\n", bufferSize); //printf("received: %d\n", received); //printf("totalReceived: %d\n", totalReceived); Warning Messages It would be better if you compiled using the -wall switch to catch all possible errors in the code. I compiled this with Visual Studio 2019 and got 2 warning messages, both messages indicate possible bugs: warning C4018: '<': signed/unsigned mismatch warning C4715: 'sendStrBuffer': not all control paths return a value The second warning is a problem that you definitely want to fix. You are not explicitly returning a value from sendStrBuffer when the function is successful. What gets returned is undefined and that definitely isn't a good thing, it may return SOCKET_ERROR or some other value that could cause problems in the calling program. The function should probably return zero if it is successful. The first warning is on this line: while (totalReceived < bufferSize)
{ "domain": "codereview.stackexchange", "id": 43504, "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, socket, winapi", "url": null }
c, socket, winapi in recvStrBuffer(). The variable totalReceived is declared as a signed integer, the variable bufferSize is declared as an unsigned integer. It would be better if both variables were defined using the same type. It would be even better if both variables were defined as size_t since they represent a size. The type size_t is what is returned by the sizeof() operator. The size_t type is the largest unsigned integer value your system supports. File and Program Organization To make it easier to share values between the sending function and the receiving function it might be better to put both functions into a common library C source file and share the resulting object file between the sending program and the receiving program. There should be a dedicated header file that provides the function prototypes for both functions that the sending program and the receiving program include. This file organization would make it easier to maintain the code because all the code for sending and receiving through the socket is in the same file. Test for Possible Memory Allocation Errors In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).
{ "domain": "codereview.stackexchange", "id": 43504, "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, socket, winapi", "url": null }
c, socket, winapi To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL. Example of Current Code: char* buff = (char*)malloc(sizeof(char) * bufferSize);
{ "domain": "codereview.stackexchange", "id": 43504, "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, socket, winapi", "url": null }
c, socket, winapi Example of Current Code with Test: char* buff = (char*)malloc(sizeof(*buff) * bufferSize); if (!buff) { fprintf(stderr, "Malloc of buffer failed in recvStrBuffer\n"); return NULL; } Convention When Using Memory Allocation in C When using malloc(), calloc() or realloc() in C a common convention is to sizeof(*PTR) rather sizeof(PTR_TYPE); this makes the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. See the example above. Print Error Messages to stderr There are 3 streams provided by stdio.h one, stdin is an input stream, two, stdout and stderr are output streams. Generally it is better to print error messages to stderr rather than stdout. When you redirect output to a file the two streams can be separated, and you can generate two files, one containing errors and the other containing program output. This helps when you are debugging or developing code. One Statement Per Line I don't know if this is a copy and paste error or if this the actual code in the program, but there should always be only one statement per line to make maintenance of the code easier. static inline uint32_t ntohl_ch(char const* a) { uint32_t x; memcpy(&x, a, sizeof(x)); return ntohl(x); } This function should return size_t rather than uint32_t. Use of the inline Keyword The inline keyword is only a recommendation to the compiler; it may not do anything. Rather than use the inline keyword it is better to compile with the best optimization you can, generally -O3. The optimizing compilers will use inline code when that code fits into the cache memory whether you use the inline keyword or not.
{ "domain": "codereview.stackexchange", "id": 43504, "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, socket, winapi", "url": null }
java, programming-challenge Title: Split word based on terms from an array Question: I was faced with a coding challenge and I'm looking for a more elegant way to achieve the goal. The challenge Take the word baseball from the first item in the string array and split it into two comma separated words using only the terms provided in the second item of the string array. If it's impossible to split the word into two separate comma separated words, return the string "not possible". Example Given the array new String[] {"baseball","a,all,b,ball,bas,base,cat,code,d,e,quit,z"}; The program should output base,ball If your program is unable to split baseball using the words from the second item in the string array return "not possible" I provided the following solution, does anybody have something a little bit more elegant? public static String ArrayChallenge(String[] strArr) { //my code starts here String pattern = strArr[0]; String[] dictionaryWords = strArr[1].split(","); Set<String> dictionaryWordSet = new HashSet<>(Arrays.asList(dictionaryWords)); String[] tempArr = new String[2]; for (int i = 0; i < pattern.length(); i++) { String firstWord = pattern.substring(0, i); if(dictionaryWordSet.contains(firstWord)) { if(tempArr[0] == null) { tempArr[0] = firstWord; } else if(tempArr[0].length() < firstWord.length()) { tempArr[0] = firstWord; } } String lastWord = pattern.substring(i); if(dictionaryWordSet.contains(lastWord)) { tempArr[1] = lastWord; break; } } if(!pattern.equals(tempArr[0] + tempArr[1])) { return "not possible"; } strArr[0] = tempArr[0] + "," + tempArr[1]; //My code ends here return strArr[0]; } public static void main(String[] args) { String[] arr = new String[] {"baseball", "a,all,b,ball,bas,base,cat,code,d,e,quit,z"}; System.out.println(ArrayChallenge(arr)); }
{ "domain": "codereview.stackexchange", "id": 43505, "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, programming-challenge", "url": null }
java, programming-challenge System.out.println(ArrayChallenge(arr)); } Answer: The goal when writing code should almost always be to optimize for readability. Only worry about performance when you have a known performance bottleneck. Readable code can always be rewritten to be performant later. The reverse is much harder. In Idiomatic java, methods begin with a lowercase letter. I understand this is not your method name, but I’m immediately dubious about whoever has created this challenge. In idiomatic java, there is whitespace between if and (, to visually distinguish control flow keywords from method names. pattern is a misleading name, as this is not a pattern. It’s the word to be split. Streaming might make it cleaner to pull out the words into a set. dictionaryWordSet can be shortened to dictionaryWords. It is not generally necessary to embed the type of a variable in its name. tempArr is not a helpful name. Try to avoid abbreviations, as they make the code harder to read, and try to find a descriptive name. Your algorithm appears to be trying to maximize the length of the first word. This is not in the problem description. The more elegant way to handle this is to reverse the loop so you’re starting from the back, not the front. This will allow you to get rid of tempArr altogether, which is good because it’s confusing. Return early if you find a valid partition. If you make these changes, your code might look something like: public static String arrayChallenge(String[] strArr) { String wordToSplit = strArr[0]; Set<String> dictionaryWords = Arrays.stream(strArr[1].split(",")).collect(toSet()); for (int i = wordToSplit.length() - 1; i > 0; i--) { String firstWord = wordToSplit.substring(0, i); String lastWord = wordToSplit.substring(i); if (dictionaryWords.contains(firstWord) && dictionaryWords.contains(lastWord)) { return firstWord + "," + lastWord; } } return "not possible"; }
{ "domain": "codereview.stackexchange", "id": 43505, "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, programming-challenge", "url": null }
python, beginner, python-3.x, checksum Title: Credit Card Validation Check (Using Luhn's Algorithm) Question: list = int(input("Enter the first 15 digits of your credit card number without spaces and dashes: ")) checkDigit = int(input("Enter the last digit of the credit card number: ")) numbers = [] for elements in str(list): numbers.append(int(elements)) def main(): n = None total_odd = 0 total_even = 0 count = 0 for element in numbers[::2]: total_odd += element if element > 4: count += 1 for element in numbers[1::2]: total_even += element total = total_even + (total_odd * 2) + count if total % 10 != 0: for i in range(1,10): if (total + i) % 10 == 0: n = i else: n = 0 validation(n) def validation(n): if n == checkDigit: print("Your credit card is valid!") else: print("Your credit card in not valid!") main() Answer: Your program and functions are structured ineffectively. You have some code at the top level (collecting user input and converting it to numbers), then most of the card-checking logic in main(), and a tiny bit of printing logic in validation(). Much better would be a structure like the sketch below. In main() we handle the user interactions (getting input and printing) and we use a function like validate_credit_card_number() to handle the detailed logic and return true or false. This structure is better for a variety of reasons, one being that it makes it much easier to subject the validation function (which is where the greatest potential for errors lies) to a battery of automated tests. Note also that we end up with no logic at the top level (the sooner you embrace this habit, the better). def main(): ccnum = input(...) if validate_credit_card_number(ccnum): print('valid') else: print('invalid') def validate_credit_card_number(ccnum): # Details shown below. ... if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43506, "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, beginner, python-3.x, checksum", "url": null }
python, beginner, python-3.x, checksum if __name__ == '__main__': main() Converting the card number to the needed lists of digits. There are easier ways to handle such tasks, mostly using indexing and slicing techniques that you already appear to know about: # Convert a big int to a list of its digits. digits = [int(d) for d in str(ccnum)] # Grab the last digit. check_digit = digits[-1] # Grab two groups of every-other digits, taken from the first 15 digits. odds = digits[0:16:2] evens = digits[1:16:2] Counting the number of odds greater than 4. This can also be done more simply via Python's sum() function and the fact that boolean outcomes can be treated arithmetically. n_big_odds = sum(o > 4 for o in odds) Simplifying the computation of the expected check digit. Your approach seems overly complex. Via experimentation with different inputs, I inferred the following pattern. [Someone more fluent in the rules of modulo arithmetic than I might be able to simplify it further.] checksum = sum(evens) + (sum(odds) * 2) + n_big_odds expected = (10 - (checksum % 10)) % 10 The final check. And then the function should just return a boolean value. return expected == check_digit
{ "domain": "codereview.stackexchange", "id": 43506, "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, beginner, python-3.x, checksum", "url": null }
c, reinventing-the-wheel, formatting, io Title: Re-designing c-style Input Output Question: Re - designing c-style input output [ btw I use printf() and scanf() in the core ] Reasons for redesigning it :- Needs 2 functions for input output [ namely printf() and scanf() ] Can't customize the format specifiers Can't print float/double point precisely / dynamically [ i.e printing 3.5 makes 3.500000 from printf("%f",3.5);, we can use %.1f instead of %f but that's explicit and not dynamic and only works in that context ] To get input with written text, We need to printf() then scanf() Code is increased and looks a bit long [ espacially when we have to input lot of things from user ] Improvements after redesigning it :- [ NOTE: I use printf() and scanf() in the core but it is code friendly at the end ] Needs only 1 function for both input and output [ format specifier are different default: $ for output, % for input ] Can customize the format specifiers Can print float/double precisely / dynamically or if you want explicitly We have only one function, so we can directly print text and get input Code is reduced Amazingly if you only want print, you can using print() which is included only for output and not for input file: io.h #ifndef IO_H_INCL #define IO_H_INCL #ifndef IO_OUTPUT_TOK #define IO_OUTPUT_TOK '$' #endif #ifndef IO_INPUT_TOK #define IO_INPUT_TOK '%' #endif #ifndef IO_DEF_STR_SPACE #define IO_DEF_STR_SPACE 0 #endif #include<stdarg.h> void vio(const char*, char, va_list); void print(const char*, ...); void io(const char*, ...); #endif file: io.c #include "io.h" #include <stdio.h> #include <string.h> #include <stdarg.h> /* ---- Format Specifier ---- [ default ] change the '$' if you have customized it!
{ "domain": "codereview.stackexchange", "id": 43507, "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, reinventing-the-wheel, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io /* ---- Format Specifier ---- [ default ] change the '$' if you have customized it! == == For Output == == - $i : integer - $c : charachter - $f : float - $d : double - $.nf : prints n number of points after main value [ float ] ( n needs to be 0-9 ) - $.nd : prints n number of points after main value [ double ] ( n needs to be 0-9 ) - $u : unsigned integer - $p : pointers - $x : hexadecimal conversion from int - $li : long - $lu : long unsigned - $ll : long long - $LL : long long unsigned - $s : string change the '%' if you have customized it! == == For input == == - %i : integer - %c : charachter - %f : float - %d : double - %u : unsigned integer - %li : long int - %lu : long unsigned [int] - %ll : long long [int] - %lL : long long unsigned [int] - %s : string */
{ "domain": "codereview.stackexchange", "id": 43507, "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, reinventing-the-wheel, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io // main input output void vio(const char* fmt, char mode, va_list va){ size_t i; for (i = 0; i < strlen(fmt); i++) { char cch = fmt[i]; // if mode == 0 [means input and output both] if (!mode) { // if input token is the current charachter if (cch == IO_INPUT_TOK){ char cch2 = fmt[i+1]; i+=1; // process based on input format specifier if (cch2 == 'i' || cch2 == 'I'){ int* iptr = va_arg(va,int*); scanf("%d",iptr); }else if (cch2 == 'c' || cch2 == 'C'){ char* cptr = va_arg(va,char*); scanf("%c",cptr); }else if (cch2 == 'f' || cch2 == 'F'){ float* fptr = va_arg(va,float*); scanf("%f",fptr); }else if (cch2 == 'd' || cch2 == 'D'){ double* dptr = va_arg(va,double*); scanf("%lf",dptr); }else if (cch2 == 'u'){ unsigned int* uptr = va_arg(va,unsigned int*); scanf("%u",uptr); }else if (cch2 == 'l' || cch2 == 'L'){ char cch3 = fmt[i]; i+=1; if (cch3 == 'i' || cch3 == 'I') { long int* li = va_arg(va,long int*); scanf("%li",li); }else if (cch3 == 'l'){ long long int* l = va_arg(va,long long int*); scanf("%lli",l); }else if (cch3 == 'L'){ long long unsigned int* l = va_arg(va,long long unsigned int*); scanf("%llu",l); }else if (cch3 == 'u'){ long unsigned int* lu = va_arg(va,long unsigned int*); scanf("%lu",lu); }else{ i-=1; printf("%c%c%c",IO_INPUT_TOK,cch2,cch3); } }else if (cch2 == 's'){
{ "domain": "codereview.stackexchange", "id": 43507, "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, reinventing-the-wheel, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io } }else if (cch2 == 's'){ // if string check if string is affected by space // if not [as default] make up the whole input to string char* s = va_arg(va,char*); if (IO_DEF_STR_SPACE){ scanf("%s",s); }else{ scanf("%[^\n]s",s); } // if it's like %% or INPUT_TOK INPUT_TOK just print INPUT_TOK }else if (cch2 == IO_INPUT_TOK){ printf("%c",IO_INPUT_TOK); i-=1; } } } // check for output token if (cch == IO_OUTPUT_TOK){ char cch2 = fmt[i+1]; i+=1; // everything is pretty simple // check what format specifier, printf it if (cch2 == 'i' || cch2 == 'I'){ printf("%d",va_arg(va,int)); }else if (cch2 == 'c' || cch2 == 'C'){ printf("%c",va_arg(va,int)); }else if (cch2 == 'f' || cch2 == 'F'){ // float print dynamic points! // make a string to store result of snprintf, i for loop variable, //flt for actual float value, s2 for output string char s[50]=""; char s2[50]=""; size_t i; float flt = va_arg(va,double);
{ "domain": "codereview.stackexchange", "id": 43507, "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, reinventing-the-wheel, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io snprintf(s,50,"%f",flt); // states that the current isZero is true [ default ] int isZero = 1; for(i=strlen(s); i>0; i--) { // if previously it was zero and now its not, make it false!~ // stripping zero mechanism [ stripps the continuous zero till hitting // a non-zero value ] if (isZero&&s[i-1] != '0'){ isZero = 0; } // if the zeroes are already stripped out or it is the last element, // store it in output s2 if (!isZero || s[i-2] == '.'){ s2[i-1] = s[i-1]; } } // print the output str printf("%s",s2); }else if (cch2 == 'd' || cch2 == 'D'){ // double print dynamic points! // make a string to store result of snprintf, i for loop variable, //flt for actual float value, s2 for output string char s[50]=""; char s2[50]=""; size_t i; double dbl = va_arg(va,double); snprintf(s,50,"%lf",dbl); // states that the current isZero is true [ default ] int isZero = 1; for(i=strlen(s); i>0; i--) { // if previously it was zero and now its not, make it false!~ // stripping zero mechanism [ stripps the continuous zero till hitting // a non-zero value ] if (isZero&&s[i-1] != '0'){ isZero = 0; }
{ "domain": "codereview.stackexchange", "id": 43507, "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, reinventing-the-wheel, formatting, io", "url": null }