text stringlengths 1 2.12k | source dict |
|---|---|
javascript, form
Answer: Testability
Writing good code essentially boils down to, how well can your code be tested?
When mixing concepts such as DOM manipulation with domain logic, it greatly increases the difficulty to write proper tests for your code.
Your generatePassword method should be an independant and straight forward function with no concept of DOM manipuation.
const includeSymbols = symbols.checked;
For example, this is the first peice of code that we see in your generate password function. We directly access a symbols which represents the DOM Input element. That in itself should be a red flag.
Instead what should be done is generate password should accept a variety of different params.
const generatePassword = ({ includeSymbols }) => {
// stuff
}
generatePassword({
includeSymbols: symbols.checked
});
In the above, generate password is now much more testable since it's starting to have less of an understanding of what the DOM is and it sticks to simple primitive values.
Needless iterations
do {
pwd = '';
for(let i = 0; i < length; i++){
pwd += charPool[Math.floor(Math.random()*charPoolLength)];
}
}while(
(includeLower && !hasLowercase(pwd)) ||
(includeUpper && !hasUppercase(pwd)) ||
(includeNumbers && !hasNumber(pwd)) ||
(includeSymbols && !hasSymbol(pwd))
) | {
"domain": "codereview.stackexchange",
"id": 43689,
"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, form",
"url": null
} |
javascript, form
This do/whilte loop is expensive because essentially it does not allow for a fixed number of itereations. It's a double loop that never ends until all the random checks have been completed.
It would be much more beneficial to reduce the randomness of this loop and luckily there is an easy way to do it.
Predetermine the length of each character type.
For example, if you know that your password will consist of symbols and numbers predetermine how many symbols and how many numbers you want.
Then create a fixed loop to randomely take a symbol X times from the symbols list.
Thenc reate a fixed loop to randomely take a number X times from the numbers list.
At this stage, it's not too important to randomely mix the characters together, that can be done right after.
Once you've preselected all your characters, now we can mix them up (aka Shuffle).
const shuffle = (list)=>{
return list.map((value)=>({
value,
sort: Math.random()
})).sort((a, b)=>a.sort - b.sort).map(({ value })=>value);
}
const randomlyShuffledPasswordList = shuffle([
...selectedSymbols,
...selectedUppercaseLetters,
...selectedLowercaseLetters,
...selectedNumbers,
]);
Excluding ambiguous characters probably doesn't work
if(!excludeHard){
charPool.push(... ''.split('ioIo01|'));
}
This section doesn't make much sense to me and most likely doesn't work. I'm assuming your goal was to remove these characters from the pool of possible characters to be selected?
If so then | can be removed since it doesn't exist in the default pool anyway and the second o should be uppercase?
In any case, the characters that are to be excluded should be done at the moment you select your list with letters, or numbers or symbols.
The full rewrite (without the ambiguous part) of the genreatePassword function can be found here. It's written in typescript and deno, but I've generated a bundled javascript version. | {
"domain": "codereview.stackexchange",
"id": 43689,
"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, form",
"url": null
} |
javascript, form
const SYMBOLS = ";!#$%&*+-=?^_";
const LETTERS = "abcdefghijklmnopqrstuvwxyz";
const NUMBERS = "1234567890";
const getRandomNumber = (max) => Math.floor(Math.random() * max);
const getRandomCharactersFromList = (list, numberOfCharacters) => {
return new Array(numberOfCharacters).fill(undefined).map(() => list[getRandomNumber(list.length)]);
};
const shuffle = (list) => {
return list.map((value) => ({
value,
sort: Math.random()
})).sort((a, b) => a.sort - b.sort).map(({
value
}) => value);
};
const generatePassword = (options = {}) => {
const {
numberOfSymbols = 10, numberOfUppercaseLetters = 10, numberOfLowercaseLetters = 10, numberOfNumbers = 10,
} = options;
const selectedSymbols = getRandomCharactersFromList(SYMBOLS, numberOfSymbols);
const selectedUppercaseLetters = getRandomCharactersFromList(LETTERS.toUpperCase(), numberOfUppercaseLetters);
const selectedLowercaseLetters = getRandomCharactersFromList(LETTERS, numberOfLowercaseLetters);
const selectedNumbers = getRandomCharactersFromList(NUMBERS, numberOfNumbers);
const randomlyShuffledPasswordList = shuffle([
...selectedSymbols,
...selectedUppercaseLetters,
...selectedLowercaseLetters,
...selectedNumbers,
]);
return randomlyShuffledPasswordList.join("");
};
button.addEventListener('click', () => {
const password = generatePassword({
numberOfSymbols: Number(symbols.value),
numberOfUppercaseLetters: Number(upper.value),
numberOfLowercaseLetters: Number(lower.value),
numberOfNumbers: Number(numbers.value)
});
pwd.value = password;
})
form {
display: block;
margin-left: auto;
margin-right: auto;
width: 75%
}
pair {
display: block
}
<form>
<h2>Secure Password Generator</h2>
<pair>
<label for="symbols">Number of symbols</label>
<input type="number" id="symbols" value='5'>
</pair>
<pair>
<label for="numbers">Number of numbers</label>
<input type="number" id="numbers" value='5'>
</pair> | {
"domain": "codereview.stackexchange",
"id": 43689,
"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, form",
"url": null
} |
javascript, form
<pair>
<label for="lower">Number of lowercase letters</label>
<input type="number" id="lower" value='5'>
</pair>
<pair>
<label for="upper">Number of uppercase letters</label>
<input type="number" id="upper" value='5'>
</pair>
<br>
<button type="button" id="button">Generate</button>
<br><br>
<pair>
<label for="pwd">Generated password</label>
<input type="text" id="pwd">
</pair>
<br><br> Inspired by <a href="https://web.archive.org/web/20220711113233/https://passwordsgenerator.net/">passwordsgenerator.net</a>
<!-- This will never generate server side, always try to use cookies, and always autoselect the pwd-->
</form> | {
"domain": "codereview.stackexchange",
"id": 43689,
"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, form",
"url": null
} |
c++, objective-c, grand-central-dispatch
Title: A periodic implementation for C++ using Grand Central Dispatch
Question: I have a C++ project which needs a few periodic timers. I have created a timer class for this project using Grand Central Dispatch.
I tried using boost::asio, but for some company policy reasons, I cannot link with said library.
Here's the header file with the interface:
//
// PeriodicTimer.hpp
//
#pragma once
#include <thread>
#include <mutex>
#include <memory>
#ifdef __OBJC__
#import <dispatch/dispatch.h>
#else
using dispatch_queue_t = void *;
using dispatch_source_t = void *;
#endif
namespace Test
{
#pragma mark -
#pragma mark TimerWorkloop
/**
@class TimerWorkloop
@brief a workloop to host all the timer events
*/
class TimerWorkloop
{
public:
using Context = dispatch_queue_t;
private:
Context mContext;
public:
/**
@function ctor
*/
TimerWorkloop();
/**
@function dtor
*/
~TimerWorkloop();
/**
@function getContext
@abstract the loop used by the thread for the io context
*/
Context getContext()
{ return mContext; }
};
#pragma mark -
#pragma mark PeriodicTimer
/**
@class PeriodicTimer
@brief a timer that gives a periodic asynchronous callback
@note please note that the callback issued by this class is on the TimerWorkloop thread, and if there is significant
work to be done in the callback, then the client should offload the work onto a separate thread
*/
class PeriodicTimer
{
public:
using CallbackFunc = std::function<void(PeriodicTimer *)>; | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
private:
using Timer = dispatch_source_t;
bool mIsActive;
uint32_t mPeriodMs;
CallbackFunc mCb;
std::shared_ptr<TimerWorkloop> mWl;
Timer mTimer;
std::mutex mLock;
public:
static constexpr uint32_t kMinPeriodMs = 5;
/**
@function ctor
*/
PeriodicTimer(std::shared_ptr<TimerWorkloop> inWl);
/**
@function dtor
*/
~PeriodicTimer();
/**
@function start
@param inPeriod the period for the timer
@param inCb the callback function that will be called
*/
void start(uint32_t inperiodMs, CallbackFunc inCb);
/**
@function stop
*/
void stop();
/**
@function getperiodMs
@return current period in milliseconds
*/
uint32_t getPeriodMs() const { return mPeriodMs; }
/**
@function isRunning
@return bool indicating whether the timer is running
*/
bool isRunning() const { return mIsActive; }
private:
/**
@function _timerHandler
@param inErrorCode the error code used to indicate whether the timer has expired or cancelled
*/
void _timerHandler();
PeriodicTimer(PeriodicTimer const &) = delete;
PeriodicTimer(PeriodicTimer &&) = delete;
};
}
And the implementation:
//
// PeriodicTimer.mm
//
#include "PeriodicTimer.hpp"
#include <stdexcept>
using namespace Test; | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
#include "PeriodicTimer.hpp"
#include <stdexcept>
using namespace Test;
#pragma mark -
#pragma mark TimerWorkloop
TimerWorkloop::TimerWorkloop()
{
mContext = dispatch_queue_create("com.test.timerworkloop",
DISPATCH_QUEUE_SERIAL);
}
TimerWorkloop::~TimerWorkloop()
{
}
#pragma mark -
#pragma mark PeriodicTimer
PeriodicTimer::PeriodicTimer(std::shared_ptr<TimerWorkloop> inWl) :
mWl(inWl), mIsActive(false), mPeriodMs(0), mCb(nullptr)
{
}
PeriodicTimer::~PeriodicTimer()
{
if (mIsActive)
{
stop();
}
}
void
PeriodicTimer::start(uint32_t inPeriodMs, CallbackFunc inCb)
{
if (!mIsActive)
{
if (inPeriodMs < kMinPeriodMs)
{
throw std::runtime_error("Too short a period for the timer");
}
if (inCb == nullptr)
{
throw std::runtime_error("Empty timer callback");
}
mPeriodMs = inPeriodMs;
mCb = inCb;
mIsActive = true;
mTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, mWl->getContext());
ThrowIfFalse(mTimer != nil, "Could not allocate a timer dispatch source");
dispatch_source_set_timer(mTimer, DISPATCH_TIME_NOW, inPeriodMs * NSEC_PER_MSEC,
NSEC_PER_MSEC);
dispatch_source_set_event_handler(mTimer, ^{ this->_timerHandler(); });
dispatch_resume(mTimer);
}
}
void
PeriodicTimer::stop()
{
if (mIsActive)
{
dispatch_source_cancel(mTimer);
mIsActive = false;
}
}
void
PeriodicTimer::_timerHandler()
{
if (mCb != nullptr)
{
mCb(this);
}
} | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
void
PeriodicTimer::_timerHandler()
{
if (mCb != nullptr)
{
mCb(this);
}
}
I have not used GCD before, and I am relatively new to Objective C as well. Please review my code.
EDIT:
I did some performance measurements, and I am seeing some weird behavior:
The first time the timer fires, it fires too quickly, within <1ms of enabling, even if the period is quite high. In addition to this, even at some other times, the timer fires a bit sooner than expected (up to 5 ms sooner).
Why might this be?
Answer: TimerWorkLoop is useless
The class TimerWorkLoop does almost nothing. It initializes mContext and then you can get that variable. A lot of lines of codes have been written for this, but why not simply pass a Context to PeriodicTimer? So instead of:
auto workLoop = std::make_shared<TimerWorkLoop>();
PeriodicTimer timer(workLoop);
You could then write:
auto context = dispatch_queue_create("com.test.timerworkloop", DISPATCH_QUEUE_SERIAL);
PeriodicTimer timer(context); | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
If you don't have ARC enabled, I could see some value for this class if it also properly cleaned up after itself, by calling dispatch_release() in the destructor.
If you want to hide the work loop details so you can easily swap it out for some other implementation, then I would expect all functions that currently rely on knowing the type of context to be moved into TimerWorkLoop. That means most of PeriodicTimer::start() should become one or more member functions of TimerWorkLoop.
mLock is not used
You are not using mLock anywhere in your code, so you can remove it. I also see that you #include <thread> and <mutex>, those are not necessary either.
Consider starting a timer in its constructor
When you create a PeriodicTimer object it's not doing anything yet, you have to call start() first. It is quite likely that you'd want to start a timer as soon as you have created it, so I would add an overload for the constructor that takes a period and callback function and have it start the timer immediately. Note that you can have multiple constructors for a given class in C++, so you can also keep the original constructor to allow creating a timer that does not immediately start.
Use std::chrono::duration to store periods
I can see in your code that the period is supposed to be in milliseconds, but the Doxygen documentation for start() doesn't even mention that. But you can avoid any potential confusion by passing and storing the period as an appropriate std::chrono::duration, like so:
class PeriodicTimer
{
public:
using Duration = std::chrono::nanoseconds;
...
private:
Duration mPeriod;
...
public:
static constexpr Duration kMinPeriod = std::chrono::milliseconds(5);
...
void start(Duration inPeriod, CallbackFunc inCb);
Duration getPeriod() const { return mPeriod; }
...
}; | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
void PeriodicTimer::start(Duration inPeriod, CallbackFunc inCb)
{
if (inPeriod < kMinPeriod)
{
throw std::runtime_error("Too short a period for the timer");
}
...
mPeriod = inPeriod;
...
dispatch_source_set_timer(..., mPeriod.count(), ...);
...
};
The std::chrono::duration types can implicitly convert to another, so the code creating a timer can pass in milliseconds, seconds or whatever they want without having to care about what resolution PeriodicTimer uses, like so:
PeriodicTimer timer(...);
timer.start(std::chrono::minutes(1), [](PeriodicTimer *t){...});
Issues with the HeaderDoc documentation
It's great that you are using HeaderDoc to document your code. However, there are some issues I am seeing:
@class and @function are rarely needed anymore; HeaderDoc will know comments belong to a given class or (member) function from the surrounding source code. It's easy to make a typo in @class and @function, and then the documentation would not match the source code anymore.
I recommend you use @brief instead of @abstract, the latter is not supported by Doxygen (and it might be nice to have Doxygen also be able to parse your documentation).
@param names not matching the actual parameter names, like @param inPeriod for start(uitn32_t inperiodMs, ...).
@param for non-existing parameters, like @param inErrorCode.
It might also be a good idea to run headerdoc2html with the --paranoid option on your source code, and then fix all the problems it finds.
Unnecessary code
In the destructor of PeriodicTimer() you can call stop() unconditionally, as the latter will already check mIsActive.
In _timerHandler() you can also call mCb(this) unconditionally, as you already forbid starting a timer without a callback function.
Your destructors are not doing anything, so you can remove them completely, unless you want to provide a stable API and want to have the option open to add a destructor later.
First callback and timer granularity | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
c++, objective-c, grand-central-dispatch
The first time the timer fires, it fires too quickly, within <1ms of enabling, even if the period is quite high.
This is because the second argument to dispatch_source_set_timer() is the time when the timer should first fire. Since you set it to DISPATCH_TIME_NOW, it fires immediately. Either explicitly set the start time to now plus the period using dispatch_time(), or you could write some code to somehow ignore the first time the timer fires.
In addition to this, even at some other times, the timer fires a bit sooner than expected (up to 5 ms sooner).
Timers are not perfect and can fire a bit sooner or later depending on the granularity of the timer interrupt used by GCD. You just have to accept this, or use a different kind of timer. See Apple's documentation about high precision timers for more information. | {
"domain": "codereview.stackexchange",
"id": 43690,
"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++, objective-c, grand-central-dispatch",
"url": null
} |
java, console, javafx, color
Title: Funny TextUIWindow.java and a simple colorful text editor
Question:
(See this repository for full code.)
Now I have rolled a simple class extending JavaFX Canvas for showing terminal like, colorful console:
TextUIWindow.java:
package com.github.coderodde.ui;
import javafx.scene.canvas.Canvas;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.sun.javafx.tk.FontMetrics;
import com.sun.javafx.tk.Toolkit;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javafx.event.EventHandler;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.FontWeight;
/**
* This class implements a simple colorful terminal window.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jul 24, 2022)
* @since 1.6 (Jul 24, 2022)
*/
public class TextUIWindow extends Canvas {
private static final int MINIMUM_WIDTH = 1;
private static final int MINIMUM_HEIGHT = 1;
private static final int MINIMUM_FONT_SIZE = 1;
private static final Color DEFAULT_TEXT_BACKGROUND_COLOR = Color.BLACK;
private static final Color DEFAULT_TEXT_FOREGROUND_COLOR = Color.WHITE;
private static final Color DEFAULT_BLINK_BACKGROUND_COLOR = Color.WHITE;
private static final Color DEFAULT_BLINK_FOREGROUND_COLOR = Color.BLACK;
private static final char DEFAULT_CHAR = ' ';
private static final String FONT_NAME = "Monospaced";
private static final int DEFAULT_CHAR_DELIMITER_LENGTH = 4;
private final int width;
private final int height;
private final int fontSize;
private final Font font;
private final int fontCharWidth;
private final int fontCharHeight;
private final int charDelimiterLength;
private int windowTitleBorderThickness;
private final Set<TextUIWindowMouseListener> mouseMotionListeners =
new HashSet<>(); | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private final Set<TextUIWindowKeyboardListener> keyboardListeners =
new HashSet<>();
private final Color[][] backgroundColorGrid;
private final Color[][] foregroundColorGrid;
private final boolean[][] cursorGrid;
private final char[][] charGrid;
private Color textBackgroundColor = DEFAULT_TEXT_BACKGROUND_COLOR;
private Color textForegroundColor = DEFAULT_TEXT_FOREGROUND_COLOR;
private Color blinkCursorBackgroundColor = DEFAULT_BLINK_BACKGROUND_COLOR;
private Color blinkCursorForegroundColor = DEFAULT_BLINK_FOREGROUND_COLOR;
public TextUIWindow(int width, int height, int fontSize) {
this(width, height, fontSize, DEFAULT_CHAR_DELIMITER_LENGTH);
}
public TextUIWindow(int width,
int height,
int fontSize,
int charDelimiterLength) {
this.width = checkWidth(width);
this.height = checkHeight(height);
this.fontSize = checkFontSize(fontSize);
this.charDelimiterLength =
checkCharDelimiterLength(charDelimiterLength);
this.font = getFont();
this.fontCharWidth = getFontWidth();
this.fontCharHeight = getFontHeight();
backgroundColorGrid = new Color[height][width];
foregroundColorGrid = new Color[height][width];
charGrid = new char[height][width];
cursorGrid = new boolean[height][width];
setDefaultForegroundColors();
setDefaultBackgroundColors();
setChars();
this.setWidth(width * (fontCharWidth + charDelimiterLength));
this.setHeight(height * fontCharHeight);
this.setFocusTraversable(true);
this.addEventFilter(MouseEvent.ANY, (e) -> this.requestFocus());
setMouseListeners();
setMouseMotionListeners();
setKeyboardListeners();
}
public Color getTextForegroundColor() {
return textForegroundColor;
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
public Color getTextForegroundColor() {
return textForegroundColor;
}
public Color getTextBackgroundColor() {
return textBackgroundColor;
}
public Color getBlinkCursorForegroundColor() {
return blinkCursorForegroundColor;
}
public Color getBlinkCursorBackgroundColor() {
return blinkCursorBackgroundColor;
}
public void setForegroundColor(Color color) {
textForegroundColor =
Objects.requireNonNull(color, "The input color is null.");
}
public void setBackgroundColor(Color color) {
textBackgroundColor =
Objects.requireNonNull(color, "The input color is null.");
}
public void turnOffBlink(int charX, int charY) {
if (checkXandY(charX, charY)) {
cursorGrid[charY][charX] = false;
}
}
public void setBlinkCursorBackgroundColor(Color backgroundColor) {
this.blinkCursorBackgroundColor =
Objects.requireNonNull(
backgroundColor,
"backgroundColor is null.");
}
public void setBlinkCursorForegroundColor(Color foregroundColor) {
this.blinkCursorForegroundColor =
Objects.requireNonNull(
foregroundColor,
"foregroundColor is null.");
}
public void setTextBackgroundColor(Color backgroundColor) {
this.textBackgroundColor =
Objects.requireNonNull(backgroundColor,
"The input color is null.");
}
public void setTextForegroundColor(Color foregroundColor) {
this.textForegroundColor =
Objects.requireNonNull(foregroundColor,
"The input color is null.");
}
public int getGridWidth() {
return width;
}
public int getGridHeight() {
return height;
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
public int getGridHeight() {
return height;
}
public void toggleBlinkCursor(int charX, int charY) {
if (checkXandY(charX, charY)) {
cursorGrid[charY][charX] = !cursorGrid[charY][charX];
}
}
public boolean readCursorStatus(int charX, int charY) {
if (!checkX(charX)) {
throw charXToException(charX);
}
if (!checkY(charY)) {
throw charYToException(charY);
}
return cursorGrid[charY][charX];
}
public void printString(int charX, int charY, String text) {
if (!checkY(charY)) {
return;
}
for (int i = 0; i < text.length(); ++i) {
setChar(charX + i, charY, text.charAt(i));
if (!checkX(charX + i)) {
// Once here, the input text string proceeds beyond the right
// border. Nothing to print, can exit.
return;
}
}
}
public void addTextUIWindowMouseListener(
TextUIWindowMouseListener listener) {
mouseMotionListeners.add(listener);
}
public void removeTextUIWindowMouseListener(
TextUIWindowMouseListener listener) {
mouseMotionListeners.remove(listener);
}
public void addTextUIWindowKeyboardListener(
TextUIWindowKeyboardListener listener) {
keyboardListeners.add(listener);
}
public void removeTextUIWindowKeyboardListener(
TextUIWindowKeyboardListener listener) {
keyboardListeners.remove(listener);
}
private void setMouseListeners() {
setMouseClickedListener();
setMouseEnteredListener();
setMousePressedListener();
setMouseReleasedListener();
setMouseExitedListener();
}
private void setMouseMotionListeners() {
setMouseMovedListener();
setMouseDraggedListener();
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private void setKeyboardListeners() {
setKeyboardPressedListener();
setKeyboardReleaseListener();
setKeyboardTypedListener();
}
private void setKeyboardPressedListener() {
this.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
for (TextUIWindowKeyboardListener listener
: keyboardListeners) {
listener.onKeyPressed(event);
}
}
});
}
private void setKeyboardReleaseListener() {
this.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
for (TextUIWindowKeyboardListener listener
: keyboardListeners) {
listener.onKeyReleased(event);
}
}
});
}
private void setKeyboardTypedListener() {
this.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
public void handle(KeyEvent event) {
for (TextUIWindowKeyboardListener listener : keyboardListeners) {
listener.onKeyTyped(event);
}
}
});
}
private void setMouseMovedListener() {
this.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseMove(event, charX, charY);
}
}
});
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private void setMouseDraggedListener() {
this.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseClick(event, charX, charY);
}
}
});
}
private void setMouseClickedListener() {
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseClick(event, charX, charY);
}
}
});
}
private void setMouseEnteredListener() {
this.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseEntered(event, charX, charY);
}
}
});
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private void setMouseExitedListener() {
this.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseExited(event, charX, charY);
}
}
});
}
private void setMousePressedListener() {
this.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMousePressed(event, charX, charY);
}
}
});
}
private void setMouseReleasedListener() {
this.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
for (TextUIWindowMouseListener listener
: mouseMotionListeners) {
listener.onMouseReleased(event, charX, charY);
}
}
});
}
private int convertPixelXtoCharX(int pixelX) {
return pixelX / (fontCharWidth + charDelimiterLength);
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private int convertPixelYtoCharY(int pixelY) {
return (pixelY - windowTitleBorderThickness) / fontCharHeight;
}
public void setTitleBorderThickness(int thickness) {
this.windowTitleBorderThickness = thickness;
}
public void repaint() {
GraphicsContext gc = getGraphicsContext2D();
for (int y = 0; y < height; y++) {
repaintRow(gc, y);
}
}
private void repaintRow(GraphicsContext gc, int y) {
for (int x = 0; x < width; x++) {
repaintCell(gc, x, y);
}
}
private void repaintCell(GraphicsContext gc, int x, int y) {
repaintCellBackground(gc, x, y);
repaintCellForeground(gc, x, y);
}
private void repaintCellBackground(GraphicsContext gc,
int charX,
int charY) {
if (cursorGrid[charY][charX]) {
// Once here, we need to use the cursor's color:
gc.setFill(blinkCursorBackgroundColor);
} else {
gc.setFill(backgroundColorGrid[charY][charX]);
}
gc.fillRect(charX * (fontCharWidth + charDelimiterLength),
charY * fontCharHeight,
fontCharWidth + charDelimiterLength,
fontCharHeight);
}
private void repaintCellForeground(GraphicsContext gc,
int charX,
int charY) {
gc.setFont(font);
if (cursorGrid[charY][charX]) {
gc.setFill(blinkCursorForegroundColor);
} else {
gc.setFill(foregroundColorGrid[charY][charX]);
}
int fixY = fontCharHeight - (int) getFontMetrics().getMaxAscent(); | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
int fixY = fontCharHeight - (int) getFontMetrics().getMaxAscent();
gc.fillText("" + charGrid[charY][charX],
charDelimiterLength / 2 +
(fontCharWidth + charDelimiterLength) * charX,
fontCharHeight * (charY + 1) - fixY);
}
public Color getForegroundColor(int charX, int charY) {
if (!checkX(charX)) {
throw charXToException(charX);
}
if (!checkY(charY)) {
throw charYToException(charY);
}
return foregroundColorGrid[charY][charX];
}
public Color getBackgroundColor(int charX, int charY) {
if (!checkX(charX)) {
throw charXToException(charX);
}
if (!checkY(charY)) {
throw charYToException(charY);
}
return backgroundColorGrid[charY][charX];
}
public void setForegroundColor(int charX, int charY, Color color) {
if (checkXandY(charX, charY)) {
foregroundColorGrid[charY][charX] =
Objects.requireNonNull(color, "The color is null.");
}
}
public void setBackgroundColor(int x, int y, Color color) {
if (checkXandY(x, y)) {
backgroundColorGrid[y][x] =
Objects.requireNonNull(color, "The color is null.");
}
}
public char getChar(int charX, int charY) {
if (!checkX(charX)) {
throw charXToException(charX);
}
if (!checkY(charY)) {
throw charYToException(charY);
}
return charGrid[charY][charX];
}
public void setChar(int x, int y, char ch) {
if (checkXandY(x, y)) {
charGrid[y][x] = ch;
foregroundColorGrid[y][x] = textForegroundColor;
backgroundColorGrid[y][x] = textBackgroundColor;
}
}
public int getPreferredWidth() {
return width * (fontCharWidth + charDelimiterLength);
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
public int getPreferredHeight() {
return height * fontCharHeight;
}
private FontMetrics getFontMetrics() {
return Toolkit.getToolkit().getFontLoader().getFontMetrics(font);
}
private static int checkWidth(int widthCandidate) {
if (widthCandidate < MINIMUM_WIDTH) {
throw new IllegalArgumentException(
"Width candidate is invalid ("
+ widthCandidate
+ "). Must be at least "
+ MINIMUM_WIDTH
+ ".");
}
return widthCandidate;
}
private static int checkHeight(int heightCandidate) {
if (heightCandidate < MINIMUM_WIDTH) {
throw new IllegalArgumentException(
"Height candidate is invalid ("
+ heightCandidate
+ "). Must be at least "
+ MINIMUM_HEIGHT
+ ".");
}
return heightCandidate;
}
private static int checkFontSize(int fontSizeCandidate) {
if (fontSizeCandidate < MINIMUM_FONT_SIZE) {
throw new IllegalArgumentException(
"Font size candidate is invalid ("
+ fontSizeCandidate
+ "). Must be at least "
+ MINIMUM_FONT_SIZE
+ ".");
}
return fontSizeCandidate;
}
private int checkCharDelimiterLength(int charDelimiterLength) {
if (charDelimiterLength < 0) {
throw new IllegalArgumentException(
"Char delimiter length negative: ("
+ charDelimiterLength
+ "). Must be at least 0.");
}
return charDelimiterLength;
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
return charDelimiterLength;
}
private IndexOutOfBoundsException charXToException(int charX) {
if (charX < 0) {
return new IndexOutOfBoundsException(
"Character X coordinate is negative: " + charX);
}
if (charX >= width) {
return new IndexOutOfBoundsException(
"Character X coordinate is too large: "
+ charX
+ ". Must be at most "
+ (width - 1)
+ ".");
}
throw new IllegalStateException("Should not get here.");
}
private IndexOutOfBoundsException charYToException(int charY) {
if (charY < 0) {
throw new IndexOutOfBoundsException(
"Character Y coordinate is negative: " + charY);
}
if (charY >= height) {
throw new IndexOutOfBoundsException(
"Character Y coordinate is too large: "
+ charY
+ ". Must be at most "
+ (height - 1)
+ ".");
}
throw new IllegalStateException("Should not get here.");
}
private boolean checkX(int x) {
return x >= 0 && x < width;
}
private boolean checkY(int y) {
return y >= 0 && y < height;
}
private boolean checkXandY(int x, int y) {
return checkX(x) && checkY(y);
}
private void setDefaultForegroundColors() {
for (Color[] colors : foregroundColorGrid) {
for (int i = 0; i < width; i++) {
colors[i] = DEFAULT_TEXT_FOREGROUND_COLOR;
}
}
}
private void setDefaultBackgroundColors() {
for (Color[] colors : backgroundColorGrid) {
for (int i = 0; i < width; i++) {
colors[i] = DEFAULT_TEXT_BACKGROUND_COLOR;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private void setChars() {
for (char[] charRow : charGrid) {
for (int i = 0; i < width; i++) {
charRow[i] = DEFAULT_CHAR;
}
}
}
private Font getFont() {
return Font.font(FONT_NAME, FontWeight.BOLD, fontSize);
}
private int getFontWidth() {
return (int) getFontMetrics().getCharWidth('C') + charDelimiterLength;
}
private int getFontHeight() {
return (int) getFontMetrics().getLineHeight();
}
}
TextEditorApp.java:
package com.github.coderodde.ui;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.ColorPicker;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* This class implements a simple demo text editor.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jul 14, 2022)
* @since 1.6 (Jul 14, 2022)
*/
public class TextEditorApp extends Application {
private static final int CHAR_GRID_WIDTH = 40;
private static final int CHAR_GRID_HEIGHT = 24;
private static final int FONT_SIZE = 17;
private static final int CHAR_HORIZONTAL_DELIMITER_LENGTH = 1;
private static final int SLEEP_MILLISECONDS = 400;
private static final String HELLO_WORLD_STRING = "Hello, world! ";
private final TextUIWindow window;
private final HelloWorldThread helloWorldThread;
private final CursorBlinkThread cursorBlinkThread;
private volatile int cursorX = 0;
private volatile int cursorY = 2; | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private volatile int cursorX = 0;
private volatile int cursorY = 2;
public TextEditorApp() {
this.window = new TextUIWindow(CHAR_GRID_WIDTH,
CHAR_GRID_HEIGHT,
FONT_SIZE,
CHAR_HORIZONTAL_DELIMITER_LENGTH);
this.helloWorldThread = new HelloWorldThread();
this.cursorBlinkThread = new CursorBlinkThread();
}
@Override
public void stop() {
helloWorldThread.requestExit();
cursorBlinkThread.requestExit();
try {
helloWorldThread.join();
} catch (InterruptedException ex) {
}
try {
cursorBlinkThread.join();
} catch (InterruptedException ex) {
}
}
@Override
public void start(Stage primaryStage) {
Platform.runLater(() -> {
try {
ColorPicker textForegroundColorPicker =
new ColorPicker(window.getTextForegroundColor());
ColorPicker textBackgroundColorPicker =
new ColorPicker(window.getTextBackgroundColor());
ColorPicker cursorBlinkForegroundColorPicker =
new ColorPicker(window.getBlinkCursorForegroundColor());
ColorPicker cursorBlinkBackgroundColorPicker =
new ColorPicker(window.getBlinkCursorBackgroundColor());
textForegroundColorPicker.setOnAction(new EventHandler() {
@Override
public void handle(Event t) {
Color color = textForegroundColorPicker.getValue();
window.setTextForegroundColor(color);
window.setForegroundColor(cursorX, cursorY, color);
}
}); | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
textBackgroundColorPicker.setOnAction(new EventHandler() {
@Override
public void handle(Event t) {
Color color = textBackgroundColorPicker.getValue();
window.setTextBackgroundColor(color);
window.setBackgroundColor(cursorX, cursorY, color);
}
});
cursorBlinkForegroundColorPicker.setOnAction(new EventHandler() {
@Override
public void handle(Event t) {
window.setBlinkCursorForegroundColor(
cursorBlinkForegroundColorPicker.getValue());
}
});
cursorBlinkBackgroundColorPicker.setOnAction(new EventHandler() {
@Override
public void handle(Event t) {
window.setBlinkCursorBackgroundColor(
cursorBlinkBackgroundColorPicker.getValue());
}
});
HBox hboxColorPickers = new HBox(textForegroundColorPicker,
textBackgroundColorPicker,
cursorBlinkForegroundColorPicker,
cursorBlinkBackgroundColorPicker);
VBox vbox = new VBox(hboxColorPickers, window);
Scene scene = new Scene(vbox,
window.getPreferredWidth(),
window.getPreferredHeight() + 35, // How to get rid of this 35?
false,
SceneAntialiasing.BALANCED);
window.setTitleBorderThickness((int) scene.getY()); | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
window.setTitleBorderThickness((int) scene.getY());
primaryStage.setScene(scene);
window.addTextUIWindowMouseListener(new TextEditorMouseListener());
window.addTextUIWindowKeyboardListener(
new TextEditorKeyboardListener());
helloWorldThread.start();
cursorBlinkThread.start();
primaryStage.setResizable(false);
primaryStage.show();
window.requestFocus();
window.repaint();
} catch (Exception ex) {
ex.printStackTrace();
helloWorldThread.requestExit();
cursorBlinkThread.requestExit();
try {
helloWorldThread.join();
} catch (InterruptedException ex2) {
}
try {
cursorBlinkThread.join();
} catch (InterruptedException ex2) {
}
}
});
}
public static void main(String[] args) {
launch(args);
}
private void moveCursorUp() {
if (cursorY == 2) {
return;
}
window.turnOffBlink(cursorX, cursorY);
cursorY--;
Platform.runLater(() -> { window.repaint(); });
}
private void moveCursorLeft() {
if (cursorX == 0) {
if (cursorY > 2) {
window.turnOffBlink(cursorX, cursorY);
cursorY--;
cursorX = window.getGridWidth() - 1;
Platform.runLater(() -> { window.repaint(); });
}
} else {
window.turnOffBlink(cursorX, cursorY);
cursorX--;
Platform.runLater(() -> { window.repaint(); });
}
} | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
private void moveCursorRight() {
if (cursorX == window.getGridWidth() - 1) {
if (cursorY < window.getGridHeight() - 1) {
window.turnOffBlink(cursorX, cursorY);
cursorY++;
cursorX = 0;
Platform.runLater(() -> { window.repaint(); });
}
} else {
window.turnOffBlink(cursorX, cursorY);
cursorX++;
Platform.runLater(() -> { window.repaint(); });
}
}
private void moveCursorDown() {
if (cursorY == window.getGridHeight() - 1) {
return;
}
window.turnOffBlink(cursorX, cursorY);
cursorY++;
Platform.runLater(() -> { window.repaint(); });
}
private final class CursorBlinkThread extends Thread {
private static final long CURSOR_BLINK_SLEEP = 600L;
private volatile boolean doRun = true;
@Override
public void run() {
while (doRun) {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(CURSOR_BLINK_SLEEP / 10);
if (!doRun) {
return;
}
}
} catch (InterruptedException ex) {
}
window.toggleBlinkCursor(cursorX, cursorY);
Platform.runLater(() -> { window.repaint(); });
}
}
void requestExit() {
doRun = false;
}
}
private final class HelloWorldThread extends Thread {
private final char[] textChars = new char[HELLO_WORLD_STRING.length()];
private volatile boolean doRun = true;
void requestExit() {
doRun = false;
}
@Override
public void run() {
int xOffset =
(window.getGridWidth() - HELLO_WORLD_STRING.length()) / 2; | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
List<Character> characterList =
new ArrayList<>(HELLO_WORLD_STRING.length());
for (char ch : HELLO_WORLD_STRING.toCharArray()) {
characterList.add(ch);
}
while (doRun) {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(SLEEP_MILLISECONDS / 10);
if (!doRun) {
return;
}
}
} catch (InterruptedException ex) {
return;
}
String text = toString(characterList, textChars);
window.printString(xOffset, 0, text);
Character ch = characterList.remove(0);
characterList.add(ch);
Platform.runLater(() -> { window.repaint(); });
}
}
private static String toString(List<Character> charList,
char[] chars) {
for (int i = 0; i < chars.length; i++) {
chars[i] = charList.get(i);
}
return new String(chars);
}
}
private final class TextEditorKeyboardListener
implements TextUIWindowKeyboardListener {
@Override
public void onKeyTyped(KeyEvent event) {
window.turnOffBlink(cursorX, cursorY);
window.setChar(cursorX, cursorY, event.getCharacter().charAt(0));
moveCursorRight();
Platform.runLater(() -> { window.repaint(); });
event.consume();
}
@Override
public void onKeyPressed(KeyEvent event) {
switch (event.getCode()) {
case UP:
moveCursorUp();
break;
case LEFT:
moveCursorLeft();
break; | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
case LEFT:
moveCursorLeft();
break;
case RIGHT:
moveCursorRight();
break;
case DOWN:
moveCursorDown();
break;
}
event.consume();
}
}
private final class TextEditorMouseListener
implements TextUIWindowMouseListener {
public void onMouseClick(MouseEvent event, int charX, int charY) {
window.turnOffBlink(cursorX, cursorY);
cursorX = charX;
cursorY = charY;
}
}
}
Critique request
Can you spot any graphics/listener artifacts? Also, in the app class, on line 130, I have hardcoded the height for the HBox of the color pickers; would like to hear a word or two how to make this in a non-hard coded fashion.
(Some) Running instructions
I use JavaFX SDK 18.0.1 and the VM options:
--module-path "C:\Software\javafx-sdk-18.0.1\lib" --add-modules javafx.base,javafx.controls,javafx.fxml,javafx.graphics --add-exports javafx.graphics/com.sun.javafx.tk=ALL-UNNAMED
(Change C:\Software\javafx-sdk-18.0.1\lib to point to your JavaFX SDK lib folder.) Also, I run everything from NetBeans 14. If you want to make a runnable .jar-file, you will need to configure the project pom.xml. | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
Answer: Re-usability of Widget
First, your name is a bit misguiding, since TextUIWindow is not a real Window/Stage (see javafx.stage.Stage) but a mere Canvas.
Second thing is that your image (your Screenshots) provide the feeling, that the TextUIWindow is rather a Widget. And as such one it has a strong coupling to the TextEditorApp.CursorBlinkThread and therefore to the TextEditorApp. Without them, the Widget can`t work properly.
Maybe you could refactor the widget to be more standalone and less dependent?
What if i want to include your TextUIWindow into my App? Do i have to care about the rendering myself? I am not sure if i would do, in this case.
Bugs
bug: incorrect calculation of height (as requested in your post)
(i havent tried out, still updating my IDE with Javafx ^^)
getPreferredHeight(){
return height * fontCharHeight;
}
looks good so far, but when we inspect on how fontCharHeight is calculated we see:
this.fontCharHeight = getFontHeight();
digging even deeper revelas the source of problems:
private int getFontHeight() {
return (int) getFontMetrics().getLineHeight(); //LOSS OF PRECISION!!!!
}
here happenes the problem, the line height is rounded... und the round error is multiplied for each row...
minor bug TextUIWindow:
line 289, setOnMouseDraggedListener()
for (TextUIWindowMouseListener listener: mouseMotionListeners) {
listener.onMouseClick(event, charX, charY); //Should be 'onMouseDragged'
}
minor bug: pom.xml
<exec.mainClass>com.github.coderodde.ui.CUIWindow</exec.mainClass> //would be TextEditorApp
minor smells
duplicated code: all mouse Events Handlings have the code
int pixelX = (int) event.getX();
int pixelY = (int) event.getY();
int charX = convertPixelXtoCharX(pixelX);
int charY = convertPixelYtoCharY(pixelY);
maybe a simple method could reduce this bloater:
listener.onMouseClick(event, getCharX(event), getCharY(event)); | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
java, console, javafx, color
(if you do not like this because it is calculated for each listener then create a proper data object - but how much listener are you expecting ^^)
missing test:
your repository does not contain any tests... | {
"domain": "codereview.stackexchange",
"id": 43691,
"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, console, javafx, color",
"url": null
} |
python, python-3.x, file
Title: Python Function that Replicates a Directory's File-Tree for Specific File Types while Changing the Parent Directory
Question: Problem Context: I needed to make a script that would search through all the files in a GitHub Repo and find all the README files within it, then replicate the File-Tree of the Repo to a specified destination directory.
Solution: I made a function that takes in two directories (source, destination). The directory inputs are Path objects. The source_dir input is validated in the main() function to exist.
import os # For walking through a filetree.
import shutil # For copying files from src to dest
import sys # For CLI argument handling
from pathlib import Path # For proper handling of file paths regardless of OS back/forward slash convention | {
"domain": "codereview.stackexchange",
"id": 43692,
"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, file",
"url": null
} |
python, python-3.x, file
def find_readmes(source_dir, dest_dir):
readme_filepath_list_original = [] # We need to store a list of all the README filepaths we found to preserve their filetree while changing their *common* parent directory later
readme_filepath_list_new = [] # Then we need to store the new file paths that will serve as the respective destinations where we copy the old files to
for root, dirs, files in os.walk(source_dir): # Note: On Python 3.5+ os.walk() is implemented using os.scandir() resulting in a massive performance boost (5~20x) compared to python 3.4-
for file in files:
if file.endswith("README.md"):
readme_filepath = os.path.join(root, file)
readme_filepath_list_original.append(readme_filepath) # Now that we found a README.md file, add it the list mentioned above
for path in readme_filepath_list_original: # We need to build a new version of the list above with the common path changed to our destination directory
if path.startswith(str(source_dir)):
readme_filepath_list_new.append(path.replace(str(source_dir), str(dest_dir), 1))
for src_path, dest_path in zip(readme_filepath_list_original, readme_filepath_list_new): # Because we appended to our new list in exactly the same order as the old one, we can iterate simultaneously over both and copy files
os.makedirs(os.path.dirname(dest_path), exist_ok=True) # shutil.copy() expects folders that any files will be copied to, to already exist or it throws an error
print("| Original Path: {}\n| New Path: {}\n".format(src_path, dest_path))
shutil.copy(src_path, dest_path)
print("CREATED OUTPUT FOLDER '{}' which contains any detected README.md files, preserved in their original file structure.".format(dest_dir))
Question: I do not know if this is the most effective way to replicate the file tree with a changed parent directory and I was hoping to see if there was a better way to do this. | {
"domain": "codereview.stackexchange",
"id": 43692,
"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, file",
"url": null
} |
python, python-3.x, file
Answer: This is more complicated than it needs to be, and doesn't make good use of pathlib. You should be using rglob instead of doing a nested loop.
This:
if path.startswith(str(source_dir)):
is a problem, because
it should never evaluate to false, since you've acquired path from source_dir
if it did evaluate to false, then the sequences over which you zip are now misaligned and you'll be copying to the wrong place.
find_readmes does not do what's on the tin: it both finds and copies. Rename it, and/or separate it.
Suggested
from pathlib import Path
from shutil import copy
from typing import Iterator, Iterable
def find_readmes(source_dir: Path, dest_dir: Path) -> Iterator[tuple[Path, Path]]:
for source in source_dir.rglob('*README.md'):
dest = dest_dir / source.relative_to(source_dir)
yield source, dest
def copy_readmes(paths: Iterable[tuple[Path, Path]]) -> None:
for source, dest in paths:
print(f'| Original Path: {source}\n'
f'| New Path: {dest}')
dest.parent.mkdir(parents=True, exist_ok=True)
copy(source, dest)
copy_readmes(find_readmes(Path('../some-source'), Path('./dest-readmes'))) | {
"domain": "codereview.stackexchange",
"id": 43692,
"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, file",
"url": null
} |
c++, beginner, validation, floating-point
Title: Input validation of a signed double (in C++)
Question: I am a beginner, who is just learning the language (C++) from C++ Primer. I have been trying to build a side pico-project by writing functions for validation of user input for an signed double. The code is provided below. My questions:
Are there any logical errors in the code (I have tested several times with invalid inputs and the code works, but I might have missed many probabilities - hence, asking for expert advice).
Are there any ways to optimize the code, anywhere?
What other better ways to handle user inputs' errors?
Are there any built-in library functions that deals with invalid inputs from the end-users (asking this to know - if I am trying to re-invent the wheel - even if it was for academic purpose)?
EDIT: INTENTION OF THE CODE
6546y.6 invalid
2,45,556 valid
-2'34.89 valid
--23,89 invalid
3,,4.6 invalid
78-23.78 invalid
-,, invalid
-345.4,56 invalid
CODE GOES HERE:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
void printErrorMsg(int err_code)
{
switch(err_code)
{
case -3:
std::cout << "- is allowed only at the beginning. Try again. ";
break;
case -2:
std::cout << "Too many separators! Try again. ";
break;
case -1:
std::cout << "Invalid input! Try Again. ";
break;
case 0:
std::cout << "Empty input! Try again. ";
break;
case 1:
std::cout << "No alphabets or punctuations allowed. Try again. ";
break;
case 2:
std::cout << "No separators allowed after decimal(.)! Try again. ";
break;
default:
break;
}
}
void analyzeSeparator(const std::string *const input)
{
//Further Analysis starts from here
std::string _flattened_ {}; //just bear with the name, damn it!
const char replacer {'~'}; //can be bloody anything | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
for(size_t i=0; i<input->size(); ++i)
{
if(((*input)[i] == ' ') || ((*input)[i] == '\'') || ((*input)[i] == ','))
_flattened_.push_back(replacer);
else
_flattened_.push_back((*input)[i]);
}
for(size_t i=0; i<_flattened_.size()-1; ++i)
{
if(_flattened_[i] == replacer)
{
if(_flattened_[i] == _flattened_[i+1])
throw -2;
}
}
if(_flattened_.find('.') != std::string::npos)
{
if(_flattened_.find(replacer, _flattened_.find('.')) != std::string::npos)
throw 2;
}
}
void reconstructInputString(std::string *const input)
{
std::string reconstructedInput {};
for(size_t i=0; i<input->size(); ++i)
{
if(((*input)[i] != ' ') && ((*input)[i] != '\'') && ((*input)[i] != ','))
reconstructedInput.push_back((*input)[i]);
}
*input = reconstructedInput;
}
void verifyInput(const std::string *const input)
{
/* the outcome will depend on the nature of input *\
|* throws exception if the input is invalid or empty *|
\* returns true if the entry is valid input */
bool presenceOfHyphen {(*input)[0]=='-'}; //a specific identifier to check the presence of '-' (minus) sign at the beginning of the input (implying negative numbers)
unsigned short periodCounter {0}; //an identifier to count the number of period in the input. if > 1 that implies invalid input
unsigned short hyphenCounter {0}; //an identifier to count the number of hyphen in the input. if > 1 that implies invalid input
if(input->empty())
throw 0;
if(input->find_last_not_of("-.0123456789 \',")!=std::string::npos)
throw 1;
analyzeSeparator(input);
for(auto ch : *input)
{
if(ch=='.') //counting numbers of period
++periodCounter;
if(ch=='-') //counting numbers of hyphen
++hyphenCounter;
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
//std::cout << std::endl << "pC: "<<periodCounter <<"\t"<< "hC: "<<hyphenCounter <<"\t"<< "pOH: "<<presenceOfHyphen <<std::endl; //diagnostic statement
if(periodCounter > 1)
throw -1;
if(hyphenCounter > 1)
throw -1;
if(hyphenCounter == 1 && !presenceOfHyphen)
throw -3;
}
double runInputLoop()
{
for(;;)
{
std::string input {};
getline(std::cin, input);
try
{
verifyInput(&input);
reconstructInputString(&input);
std::stringstream ss(input);
double value;
if(ss >> value)
return value;
else
throw -1; //conversion went wrong - probably invalid input.
}
catch (int err_code)
{
printErrorMsg(err_code);
}
}
}
double getVDecimal(const double minN, const double maxN)
{
std::cout << "Please enter a number between " << minN << " and " << maxN << " (decimal allowed).\n";
std::cout << "You can use either a space or a comma or \' as separator: ";
for(;;)
{
double value {runInputLoop()};
if(value >= minN && value <=maxN)
return value;
else
std::cout << "Input out of range. Try again: ";
}
}
int main()
{
double val {getVDecimal(-3458835.52, 9879797.98)};
std::cout << "\nYou have entered: ";
std::cout << std::setprecision(10) << val;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
return 0;
}
Answer: Not a bad first attempt for a beginner, though you probably bit off more than you should have for a first attempt. As @JerryCoffin suggested, it would probably have been enough just to validate the input and return true/false. (However, even that is far, far more difficult than you’d think. Honestly, anything involving non-integer numbers is a fucking quagmire. I would not advise beginners to try any parsing or validation of any sort involving non-integer numbers.)
Before I get into reviewing your code, I’ll suggest how I would have approached the problem, because a lot of being a good C++ programmer has little to do with the C++ itself. Rather, it is learning to think like a software development engineer that really makes you a good C++ coder (and, as a bonus, those skills are easily transferable to other languages as well).
Okay, so the goal is to read a possibly negative decimal real number, and verify that it’s within a given range. Right away I imagine what a function that does that would have to look like. I would need to take the stream it’s trying to read the number from and the range, and it would need to return the number. So:
auto getVDecimal(std::istream& input_stream, value_range range) -> double;
where value_range is a type that holds a double range, so it probably looks something like this (to start):
struct value_range
{
double min;
double max;
}; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
I’ll get back to that type in a moment. (You’re probably wondering why I made a new type rather than just passing two doubles like you did. You’ll see in a moment.)
Now I ask… but what if there’s an error? How do I handle/report errors?
You’ve chosen to throw an exception, which is fine, and which means that the function signature above is good (because exceptions are thrown on a side channel, so you don’t need to change the function signature to support them).
(If instead the decision was not to use exceptions to signal errors, then I either would have used the stream’s error handling, or returned a std::expected<double, std:error_code>, or both… probably both.)
Now I look at the function signature again… I have to take the stream by non-const reference (that’s just required because of how streams work)… but the value range I only want to look at, for a read-only parameter the default is to use a const reference, so:
auto getVDecimal(std::istream& input_stream, value_range const& range) -> double; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
This looks good to me, so I’ll use that as the function signature.
Now let’s take another look at value_range. The reason I created a specific type for this is because… that’s how you do C++. See, C++ is a strongly-typed language… it’s probably the most strongly-typed language you’ll ever use. To really get the max power out of C++, you need to use the type system. I always tell the people I teach: in C++, when you get the types right, everything else Just Works™. When you get the types right, everything else falls magically into place. I’ll demonstrate.
So value_range holds a pair of doubles… but not just any pair of doubles. It must be a pair where both doubles are valid numbers (no nans), and, it must be a pair where one double is less than or equal to the other. The latter is a very important point. Your function just takes two doubles… what’s to stop someone from calling it like this: getVDecimal(1.0, -1.0)? (Or this: getVDecimal(std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN())?)
That means value_range needs to verify that the doubles it’s being given fit the bill:
class value_range
{
double _min = 0.0;
double _max = 0.0;
public:
constexpr value_range() noexcept = default;
constexpr value_range(double min_val, double max_val)
: _min{min_val}
, _max{max_val}
{
if (std::isnan(_min) or std::isnan(_max))
throw std::invalid_argument{"value_range bounds must be numbers"};
if (_min > _max)
throw std::invalid_argument{"value_range minimum bound is greater the maximum bound"};
}
constexpr auto min() const noexcept { return _min; }
constexpr auto max() const noexcept { return _max; }
// Handy helper function.
constexpr auto contains(double value) const noexcept
{
if (std::isnan(value))
return false;
return value >= _min and value <= _max;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
return value >= _min and value <= _max;
}
};
With this type, the function is now ironclad safe… you literally cannot call it incorrectly. If you try to do getVDecimal(in_stream, {1.0, -1.0}) or getVDecimal(in_stream, {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()}), you won’t get strange bugs… you’ll get an exception. (And it can be detected at compile time!)
And there’s more! With the contains() helper function, checking that a value is within the range no longer requires writing if (value >= minN && value >= maxN) out manually. And did you see what happened there? Oops, I made a typo and introduced a bug. But if (range.contains(value))… you can’t really introduce a typo bug with that. (Plus it reads a lot more nicely.)
That is what writing good C++ looks like: get the types right, and everything else Just Works™.
So, I have a function signature (and a helper type). What do I do next? …
…
…
I write the tests.
Yes, the function doesn’t exist yet. I’m writing the tests before I write the function. Because that’s how you do it.
And the tests are not hard. First you need to pick a testing framework. Let’s go with Catch2. So a simple test case would look like:
TEST_CASE("Simple test case")
{
auto input = std::istringstream{"-123.4"};
REQUIRE(getVDecimal(input, {-150.0, 150.0}) == -123.4);
}
And of course, you need to test expected error cases as well:
TEST_CASE("Value is too low")
{
auto input = std::istringstream{"-123.4"};
REQUIRE_THROWS_AS(getVDecimal(input, {-100.0, 150.0}), std::invalid_argument);
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
REQUIRE_THROWS_AS(getVDecimal(input, {-100.0, 150.0}), std::invalid_argument);
}
That’s the basic gist of it. Write as many tests as you please until you’re satisfied that you’ve covered all the edge cases.
(Incidentally, you should also write a whole set of tests just for value_range by itself, to make sure it works. You should test that initializing it with a valid range works, and the .min() and .max() member functions return the right values. You should test that .contains() works. And you should test that it throws when you try to create an invalid range.)
Once that’s done, I would have a whole wash of tests that won’t compile… because I haven’t written the function yet. So… I write this:
auto getVDecimal(std::istream& input_stream, value_range const& range) -> double
{
return 0.0;
}
Yup. That’s it.
With that, the tests will compile… but almost all of them will fail. That’s good. Now we can actually start coding the function.
This is where I’ll stop my example, because from here on out it’s just iterative improvements on the function. I add a bit of functionality, then I compile and run the tests again. Then I add a bit more, and run the tests again. Add more, run tests. Over and over, until all the tests pass.
And once all the tests pass, I’m done: I will know, with absolute confidence, that the function works.
(At that point I can start tweaking and optimizing the function, safe in the knowledge that if I accidentally break anything, the tests will tell me.)
That is how I would approach this problem:
Consider the interface: What should the function signature look like to allow all the flexibility I want, yet still be safe to protect against accidental misuse?
Write the tests.
Write the code, checking the tests often, until all pass. | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
Now I’ll review your code.
Code review
void printErrorMsg(int err_code)
{
switch(err_code)
{
case -3:
std::cout << "- is allowed only at the beginning. Try again. ";
break;
case -2:
std::cout << "Too many separators! Try again. ";
break;
case -1:
std::cout << "Invalid input! Try Again. ";
break;
case 0:
std::cout << "Empty input! Try again. ";
break;
case 1:
std::cout << "No alphabets or punctuations allowed. Try again. ";
break;
case 2:
std::cout << "No separators allowed after decimal(.)! Try again. ";
break;
default:
break;
}
}
The major problem with this function is the fact that you’re using a naked int as an error code.
Remember, C++ is a strongly-typed language; it’s all about the types. That means you should create a custom type for every “thing” that is a distinct “thing” in your program. An error code is a very distinct thing. And an error code is definitely not an int. You can add ints; does it make sense to add error codes? Of course not, right?
For something like error codes, the best default thing to use is an enum. This is in fact the basis for std::error_code (though going the whole hog for std::error_code—making an error category and all—is a bit much for a beginner program, so we won’t go into all that).
So, what you should do is something more like this:
enum class decimal_input_errc
{
success = 0, // adding this as the first error enumerator is a good idea
hyphen_not_at_beginning,
too_many_separators,
invalid_input,
empty_input,
invalid_character,
separators_after_decimal_point
};
void printErrorMsg(decimal_input_errc err_code)
{
switch(err_code)
{
case decimal_input_errc::hyphen_not_at_beginning:
std::cout << "- is allowed only at the beginning. Try again. ";
break;
// ... and so on... | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
Even better would be to have a function specifically to convert the error code to a string, and keep that separate:
enum class decimal_input_errc
{
success = 0, // adding this as the first error enumerator is a good idea
hyphen_not_at_beginning,
too_many_separators,
invalid_input,
empty_input,
invalid_character,
separators_after_decimal_point
};
auto message(decimal_input_errc err_code) -> std::string
{
switch (err_code)
{
case decimal_input_errc::hyphen_not_at_beginning:
return "- is allowed only at the beginning.";
case decimal_input_errc::too_many_separators:
return "Too many separators!";
// ... and so on ...
default:
throw std::logic_error{"should never get here!"};
}
}
void printErrorMsg(decimal_input_errc err_code)
{
std::cout << message(err_code) << " Try again. ";
}
That way, if ever need to add/remove/change any of the error codes, you only need to do it in the error code enum itself, and the message() function. (It’s not perfect to have to keep changes in two places in sync, but it’s the best you can do without getting really advanced.)
void analyzeSeparator(const std::string *const input)
Taking arguments by pointer is… not a great idea. Not unless you intend for the argument to be optional. (Which you don’t; you never check for nullptr.)
The right thing to do is to use a reference:
void analyzeSeparator(std::string const& input)
However….
There’s an even better way to take string arguments, and that’s to use std::string_view:
void analyzeSeparator(std::string_view input) | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
No need for pointers, references, or even any consts (because std::string_view is logically const already). Plus, it’s often far more efficient.
Now, one thing your code really needs is comments. Comments are massively important to help people understand what your code is doing. And you’ll probably find that you won’t even remember yourself what your code was doing if you come back to it after a few months.
Don’t add stupid comments like the classic ++i; // increments i. But do try to explain the logic of your code. Anything that isn’t immediately obvious, any clever tricks or reasoning, any assumptions you’ve made… those kinds of things are good candidates for comments.
In this case, it looks like what this function does is:
Detect repeated separators.
Detect separators after the decimal point.
Explaining that with a comment would have been a good thing.
Now, this function is made up of 2 for loops and an if block (that hides 3 more loops). Naked for loops are bad practice. You should always use an algorithm wherever possibly; preferably a standard algorithm, but failing that, you can always write one yourself.
So, let’s start with the first loop. What is it doing? Well, it’s replacing all the separators with ~. “Replacing”. So, check out the list of algorithms, and…
replace()
replace_if()
replace_copy()
replace_copy_if()
(There are old-school and ranges versions of each of these. You should use the ranges versions whenever possible.)
replace() doesn’t really work because it just replaces one character with another. I mean, you could do this:
auto _flattened_ = std::string{input};
std::ranges::replace(_flattened_, ' ', replacer);
std::ranges::replace(_flattened_, '\'', replacer);
std::ranges::replace(_flattened_, ',', replacer);
… but that’s just silly.
What you really need is a is_separator() function:
constexpr auto is_separator(char c) noexcept
{
return c == ' ' or c == '\'' or c == ',';
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
You should have this in any case, because that way you don’t need to repeat the list of separators in multiple places.
With that, you could just do:
auto _flattened_ = std::string{input};
std::ranges::replace_if(_flattened_, is_separator, replacer);
The next for loop looks for cases where there are two adjacent ~. Well, let’s look at the algorithm list and… well, there’s adjacent_find().
The basic version of adjacent_find() just looks for any adjacent duplicates. That’s not great, because it would find the two zeros in 1200.34.
However, there is a version of adjacent_find() that takes a custom predicate. You could just use a lambda to drop in what you actually have:
if (std::ranges::adjacent_find(_flattened_, [](char c1, char c2) { return c1 == '~' and c2 == c1; }))
throw decimal_input_errc::too_many_separators;
But here’s a million-dollar observation… we don’t actually need t replace the separators. We can just use is_separator() directly on the input:
if (std::ranges::adjacent_find(input, [](char c1, char c2) { return is_separator(c1) and is_separator(c2); }))
throw decimal_input_errc::too_many_separators;
You can pull the lambda out to make it easier to read:
auto double_separators = [](char c1, char c2)
{
return is_separator(c1) and is_separator(c2);
};
if (std::ranges::adjacent_find(input, double_separators))
throw decimal_input_errc::too_many_separators;
Finally, the if block at the end searches for a decimal point, and if it finds one, searches for it again (duplicate work!), and then search for any separators after it.
What you could do to avoid the extra work is exploit the fact that if the starting location for a search is past-the-end… well, nothing will be found. So:
if (input.find(replacer, input.find('.')) != std::string_view::npos)
throw decimal_input_errc::separators_after_decimal_point; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
However… I would suggest rethinking the strategy here.
The problem is that you do all that work searching for doubled separators on the whole string… even though you only need to do it on the part before the decimal point. If you think about it, you’re treating the before-the-point part of the string and the after-the-point part of the string totally differently. So perhaps you should separate them first… and then do your checks. Something like this:
auto analyzeSeparator(std::string_view input)
{
// Start by assuming there is no decimal point.
//
// So everything is "before" the point, and nothing is after.
auto before_point = input;
auto after_point = std::string_view{};
// Now check to see if there is a decimal point.
if (auto point_position = input.find('.'); point_position != std::string_view::npos)
{
// It has one! So now split the string appropriately.
before_point = input.substr(0, point_position);
after_point = input.substr(point_position + 1); // the "+1" is to skip the point itself
}
// Now check for doubled separators before the point.
auto double_separators = [](char c1, char c2)
{
return is_separator(c1) and is_separator(c2);
};
if (std::ranges::adjacent_find(before_point, double_separators))
throw decimal_input_errc::too_many_separators;
// Then check for *any* separators after the point.
if (std::ranges::any_of(after_point, is_separator))
throw decimal_input_errc::separators_after_decimal_point;
}
Another way to write the first bit is:
// Look for a decimal point first.
auto const decimal_point_position = input.find('.');
// The before-the-point part is easy.
auto const before_point = input.substr(0, decimal_point_position); | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
// The after-the-point part is a little trickier.
auto const after_point = (decimal_point_position != std::string_view::npos)
? input.substr(decimal_point_position + 1)
: std::string_view{};
The neat thing about writing it that way is everything can be const.
void reconstructInputString(std::string *const input)
{
std::string reconstructedInput {};
for(size_t i=0; i<input->size(); ++i)
{
if(((*input)[i] != ' ') && ((*input)[i] != '\'') && ((*input)[i] != ','))
reconstructedInput.push_back((*input)[i]);
}
*input = reconstructedInput;
}
Here’s another naked for loop. So what are you trying to do here? Well, you’re trying to remove all the separators, right? Let’s look in the algorithm list again and…:
remove()
remove_if()
remove_copy()
remove_copy_if()
You could use remove_copy_if() to remove all the separators while copying to reconstructedInput, and then copy that back to input. However, it would make more sense to remove the separators from input directly.
Now, for very technical reasons, remove() doesn’t actually remove things from a container. Instead it shuffles the container around so that all the “non-removed” stuff is first, with a bunch of garbage at the end that you then have to erase. Thus, the erase-remove idiom, which looks like this:
auto const [first_removed, last_removed] = std::ranges::remove_if(input, is_separator);
input.erase(first_removed, last_removed);
But as of C++20, there’s a shortcut:
std::erase_if(input, is_separator);
Which means your function is just:
auto reconstructInputString(std::string& input)
{
std::erase_if(input, is_separator);
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
(Which implies the name reconstructInputString isn’t that great, because you’re not really “reconstructing” anything. You’re just stripping the separators.)
void verifyInput(const std::string *const input)
{
/* the outcome will depend on the nature of input *\
|* throws exception if the input is invalid or empty *|
\* returns true if the entry is valid input */
bool presenceOfHyphen {(*input)[0]=='-'}; //a specific identifier to check the presence of '-' (minus) sign at the beginning of the input (implying negative numbers)
unsigned short periodCounter {0}; //an identifier to count the number of period in the input. if > 1 that implies invalid input
unsigned short hyphenCounter {0}; //an identifier to count the number of hyphen in the input. if > 1 that implies invalid input
if(input->empty())
throw 0;
Alright, there are a couple of things wrong here right at the start.
The first problem is that it is bad practice to put all the function variables right at the top of the function. That is archaic C practice; it was never a good idea in C++.
The second problem… which happens because of the first problem… is that the function has a bug. You check for the presence of a hyphen… before checking whether the string is empty. If the string is empty, you have triggered undefined behaviour… which is very bad.
The solution to both problems is simple. Don’t declare variables until you need them. You don’t need presenceOfHyphen until the end of the function.
I also don’t see the point of using unsigned short for the counters. What’s wrong with unsigned int? Or better yet… int. Don’t use unsigned unless you’re doing bit twiddling or modular arithmetic.
The naked for loop is actually two count() operations:
auto const periodCounter = std::ranges::count(input, '.');
auto const hyphenCounter = std::ranges::count(input, '-');
if(periodCounter > 1)
throw decimal_input_errc::invalid_input; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
if(periodCounter > 1)
throw decimal_input_errc::invalid_input;
if(hyphenCounter > 1)
throw decimal_input_errc::invalid_input;
Or even just:
if (std::ranges::count(input, '.') > 1)
throw decimal_input_errc::invalid_input;
if (std::ranges::count(input, '-') > 1)
throw decimal_input_errc::invalid_input;
Technically, the way you do it—a single loop for both counts—is more efficient, though there are ways to get the same efficiency with standard algorithms.
double runInputLoop()
{
for(;;)
{
std::string input {};
getline(std::cin, input);
try
{
verifyInput(&input);
reconstructInputString(&input);
std::stringstream ss(input);
double value;
if(ss >> value)
return value;
else
throw -1; //conversion went wrong - probably invalid input.
}
catch (int err_code)
{
printErrorMsg(err_code);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
There is a very tricky problem with what you’re doing here, and it stems from the fact that you’re using IOstreams to parse the number. (Incidentally, all you need here is an input stream, so you should be using std::istringstream, not std::stringstream.)
The problem is that you have gone to a lot of trouble to ensure that the number is of the form -?[0-9]*\.?[0-9]* (whether that is really what you intend or not). I presume you intend that the string “1.25” parses as a double with the value of 1¼. You may be surprised to find that it might actually parse as the number 125.
Why? The problem is locales. Streams use locales, and by default, they use the global locale. If no one mucks with the global locale, it will be the standard C or POSIX locale by default. But if someone does much with it… well, in some locales, the period is not a decimal point, it’s just a separator.
What you should be using is std::from_chars(). However, that is a low-level function, and it’s not easy to use. So I would say just stick with the stream parsing for now.
The other issue here has to do with the fact that you’ve mixed up all your error-handling code within your parsing code… which kinda defeats the whole point of exceptions. For all their problems, exceptions have the beautiful feature of being separate from actual logic.
What you should do is rethink the structure of what you’re doing. It’s basically this:
auto main() -> int
{
auto const minN = -3458835.52;
auto const maxN = 9879797.98;
std::cout << "Please enter a number between " << minN << " and " << maxN << " (decimal allowed).\n";
std::cout << "You can use either a space or a comma or \' as separator: ";
// ***
auto val = double{}; | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
// ***
auto val = double{};
auto got_val = false;
while (not got_val)
{
try
{
val = getVDecimal(minN, maxN);
got_val = true;
}
catch (std::exception const& x)
{
std::cout << x.what() << " Try again: ";
}
}
// ***
std::cout << "\nYou have entered: ";
std::cout << std::setprecision(10) << val;
}
Note that when you write it this way, all of the error handling is removed from getVDecimal(). That function now has one and only one job: parsing that value.
You could take the part between the asterisks and put that in a function (or even the stuff between the asterisks and the two couts before)—that would be a good idea, even. But still, the point is that getVDecimal() itself stays pure. One function; one job. Don’t mix the logic all over the place; that’s how you get spaghetti code.
getVDecimal() should do nothing but read the input, try to parse it, and throw on failure. That’s it. No looping. No error handling. That stuff is higher-level logic that should be handled separately.
There’s one more thing I’d suggest you consider, and that is rethinking the way you validate the input. You jump through a lot of hoops going through the input over and over. I would suggest instead making a single pass, using the mental model of a state machine to keep track of where you are in your parsing.
For example (vastly simplified pseudocode just to illustrate):
auto getVDecimal(std::istream& in, value_range const& limits)
{
auto buffer = std::string{};
// The stream sentry sets things up for reading, and does some basic
// checks.
if (auto sentry = std::istream::sentry{in}; sentry)
{
// Let's start by checking for a negative sign.
auto negative = char(in.peek()) == '-';
// If there was a negative sign, eat it.
if (negative)
{
buffer.push_back('-');
in.ignore():
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
// Now we should read a sequence of digits and separators.
//
// We'll stop at either eof or a '.'.
//
// We'll check for doubled separators as we read.
auto last_char_was_separator = false;
while (in.good() and char(in.peek()) != '.')
{
auto c = char(in.peek());
if (not is_digit(c) and not is_separator(c))
// invalid character
if (is_separator(c) and last_char_was_separator)
// doubled separator
// If we got here, it is either a digit or a separator, *and*
// it is not a double separator.
// Keep digits, ignore separators.
if (is_digit(c))
buffer.push_back(c);
last_char_was_separator = is_separator();
// Discard the character.
in.ignore();
}
// Getting here means either:
// 1. we found a '.'; orw
// 2. EOF.
if (in.good())
{
// So we found a '.'.
buffer.push_back('.');
// Now we should read a sequence of digits.
while (in.good())
{
auto c = char(in.peek());
if (not is_digit(c))
// error
buffer.push_back(c);
in.ignore();
}
}
// If we got here, then we successfully parsed:
// 1. an optional '-'
// 2. a sequence of digits with separators (the separators were discarded)
// 3. an optional '.' followed by a sequence of digits (no separators)
// and all of that is in the buffer.
//
// So now it's just a matter of:
auto iss = std::istringstream{buffer};
auto val = double{};
if (iss >> val)
{
if (not limits.contains(val))
throw out of range;
return val;
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
return val;
}
// ... and if we got here, then we failed to parse the buffer string
// as a double. So:
throw invalid input;
}
else
{
// If you catch this error, you should not retry, because the stream
// is bad.
throw std::runtime_error{"invalid input stream"};
}
}
Naturally, this is a very long function, and should be broken up:
auto parse_sign(std::istream& in, std::string& buffer)
{
if (char(in.peek()) == '-')
{
buffer.push_back('-');
in.ignore();
}
}
auto parse_whole_part(std::istream& in, std::string& buffer)
{
auto last_char_was_separator = false;
while (in.good() and char(in.peek()) != '.')
{
auto c = char(in.peek());
if (not is_digit(c) and not is_separator(c))
// invalid character
if (is_separator(c) and last_char_was_separator)
// doubled separator
// If we got here, it is either a digit or a separator, *and*
// it is not a double separator.
// Keep digits, ignore separators.
if (is_digit(c))
buffer.push_back(c);
last_char_was_separator = is_separator();
// Discard the character.
in.ignore();
}
}
auto parse_fractional_part(std::istream& in, std::string& buffer)
{
if (char(in.peek()) == '.')
{
// So we found a '.'.
buffer.push_back('.');
// Now we should read a sequence of digits.
while (in.good())
{
auto c = char(in.peek());
if (not is_digit(c))
// error
buffer.push_back(c);
in.ignore();
}
}
}
auto actually_parse(std::string const& buffer)
{
auto iss = std::istringstream{buffer};
auto val = double{};
if (not (iss >> val))
{
throw invalid input;
}
return val;
} | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
c++, beginner, validation, floating-point
return val;
}
auto getVDecimal(std::istream& in, value_range const& limits)
{
if (auto sentry = std::istream::sentry{in}; sentry)
{
auto buffer = std::string{};
parse_sign(in, buffer);
parse_whole_part(in, buffer);
parse_fractional_part(in, buffer);
auto const val = actually_parse(buffer);
if (not limits.contains(val))
throw out of range;
return val;
}
else
{
throw std::runtime_error{"invalid input stream"};
}
}
I think that final function is much easier to read, and because you only go through the input once, it will be much more efficient. As mentioned, there is no looping or error handling in there; it’s all handled at a higher level.
Doing it this way is much more complex, and requires learning about input streams (which, warning, they suck). But the benefits are enormous. | {
"domain": "codereview.stackexchange",
"id": 43693,
"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, validation, floating-point",
"url": null
} |
php, laravel, laravel-blade
Title: Laravel 8 blogging application
Question: I am working on a blogging application in Laravel 8.
In the FrontendController controller I have:
namespace App\Http\Controllers;
use App\Models\Settings;
use App\Models\ArticleCategory;
class FrontendController extends Controller
{
protected $site_settings;
protected $theme_directory;
protected $site_name;
protected $tagline;
protected $owner_name;
protected $article_categories;
public function __construct()
{
$this->site_settings = Settings::first();
$this->theme_directory = $this->site_settings['theme_directory'] ?? null;
$this->site_name = $this->site_settings['site_name'] ?? null;
$this->tagline = $this->site_settings['tagline'] ?? null;
$this->owner_name = $this->site_settings['owner_name'] ?? null;
// Article categories
$this->article_categories = ArticleCategory::all();
}
}
The ArticlesController controller extends the one above:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ArticleCategory;
use App\Models\Article;
class ArticlesController extends FrontendController {
// Articles per page
protected $per_page = 12;
public function index(Request $request) {
// Search query
$qry = $request->input('search');
$articles = Article::where('title', 'like', '%' . $qry . '%')
->orWhere('short_description', 'like', '%' . $qry . '%')
->orWhere('content', 'like', '%' . $qry . '%')
->orderBy('id', 'desc')
->paginate($this->per_page); | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
php, laravel, laravel-blade
// Search results count
if ($request->input('search')){
$article_count = Article::where('title', 'like', '%' . $qry . '%')
->orWhere('short_description', 'like', '%' . $qry . '%')
->orWhere('content', 'like', '%' . $qry . '%')
->count();
}
return view('themes/' . $this->theme_directory . '/templates/index',
[
'theme_directory' => $this->theme_directory,
'search_query' => $qry,
'site_name' => $this->site_name,
'tagline' => $this->tagline,
'owner_name' => $this->owner_name,
'categories' => $this->article_categories,
'articles' => $articles,
'article_count' => $article_count ?? null
]
);
}
public function category($category_id) {
$category = ArticleCategory::where('id', $category_id)->first();
$articles = Article::where('category_id', $category_id)->paginate($this->per_page);
return view('themes/' . $this->theme_directory . '/templates/index',
[
'theme_directory' => $this->theme_directory,
'site_name' => $this->site_name,
'tagline' => $this->tagline,
'owner_name' => $this->owner_name,
'categories' => $this->article_categories,
'category' => $category,
'articles' => $articles
]
);
} | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
php, laravel, laravel-blade
public function show($slug) {
// Single article
$article = Article::where('slug', $slug)->first();
return view('themes/' . $this->theme_directory . '/templates/single',
[
'theme_directory' => $this->theme_directory,
'site_name' => $this->site_name,
'tagline' => $this->tagline,
'owner_name' => $this->owner_name,
'categories' => $this->article_categories,
'article' => $article
]
);
}
}
The posts list view (index.blade.php):
@extends('themes/' .$theme_directory . '/layout')
@section('content')
<!-- Page Header -->
<header class="masthead" style="background-image: url({{ asset('themes/' . $theme_directory . '/img/home-bg.jpg') }}">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>{{ $site_name }}</h1>
<span class="subheading">
@if(isset($category))
{{ $category->name }}
@else
{{ $tagline }}
@endif
</span>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
@if (isset($search_query))
<p class="mt-0 text-muted">We found {{ $article_count }} posts containing <span class="quote-inline">{{ $search_query }}</span>:</p>
@endif | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
php, laravel, laravel-blade
@if (count($articles))
@foreach ($articles as $article)
<div class="post-preview">
<a href="{{ url('/show/' . $article->slug) }}">
<h2 class="post-title">
{{ $article->title }}
</h2>
<h3 class="post-subtitle">
{{ $article->short_description }}
</h3>
</a>
<p class="post-meta">Posted by
<a href="#">{{ $article->user->first_name }} {{ $article->user->last_name }}</a>
on {{ date('j F, Y', strtotime($article->created_at)) }}
</p>
</div>
<hr>
@endforeach
@endif
<!-- Pager -->
@if($articles->hasPages())
<div class="clearfix">
<ul class="pagination">
<li class="next">
<a class="btn btn-primary {{ $articles->withQueryString()->onFirstPage() ? 'disabled' : '' }}" href="{{ $articles->previousPageUrl() }}">← Newer Posts</a>
</li>
<li class="prev">
<a class="btn btn-primary {{ $articles->withQueryString()->onLastPage() ? 'disabled' : '' }}" href="{{ $articles->nextPageUrl() }}">Older Posts →</a>
</li>
</ul>
</div>
@endif
</div>
</div>
</div>
<hr>
@endsection
Questions
What would be an optimal way to reduce code repetition in the two controllers?
Are there any code optimisation opportunities? | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
php, laravel, laravel-blade
Answer:
What would be an optimal way to reduce code repetition in the two controllers?
If those four values from the first settings record and $article_categories are applicable to all views then they could be shared with all views using the View facade's share() method in the boot() method of the App\Providers\AppServiceProvider. Then there may not be a need to have those lines in the constructor of the FrontEndController, and the member variables can be eliminated also.
Otherwise if those values from the settings record only apply to certain views, one could define a helper method(s) to obtain the data to be sent to the view. In the two methods index() and show() the first four entries are repeated so those could be returned by a new helper method, and the other data entry - e.g. articles or article can be added via array_merge() or the array union operator - i.e. +.
In the FrontEndController constructor a loop could be used to iterate over the properties that need to be set from the settings record.
In the ArticlesController::show() method these three lines could be pulled out:
Article::where('title', 'like', '%' . $qry . '%')
->orWhere('short_description', 'like', '%' . $qry . '%')
->orWhere('content', 'like', '%' . $qry . '%')
and assigned to a local variable like $articlesQuery, which could be then used to generate $articles and $article_count.
Are there any code optimisation opportunities?
If site_settings is only used inside the constructor then perhaps it does not need to be a member variable - it could simply be a local variable.
In the ArticlesController::category() method the line with the query to get the category:
$category = ArticleCategory::where('id', $category_id)->first();
Could be simplified using the firstWhere() method:
$category = ArticleCategory::firstWhere('id', $category_id);
The same applies to first line of the show() method - i.e. to find article by slug. | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
php, laravel, laravel-blade
The same applies to first line of the show() method - i.e. to find article by slug.
Does ArticlesController::$per_page ever get assigned a different value than 12? If not then it could be declared as a constant.
Variable parsing - also known as String interpolation - could be used to simplify instances of '%' . $qry . '%' to ”%$qry%”. | {
"domain": "codereview.stackexchange",
"id": 43694,
"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": "php, laravel, laravel-blade",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
Title: Porting C-style socket to CPP class
Question: I am porting the C-style socket to design a simple wrapper around the telnet client in CPP. The telnet protocol is accomplished by using libtelnet in C. The C-style code for this wrapper is reviewed here and here as well.
I want to follow standard practices in my CPP code, such as using smart pointers in CPP instead of raw pointers, etc. Therefore, please see my implementation below:
1. simple_telnet_client.cpp
#include <simple_telnet_client/simple_telnet_client.hpp>
namespace simple_telnet_client {
class NotImplemented : public std::logic_error {
public:
NotImplemented() : std::logic_error("Function not yet implemented"){};
};
TelnetClient::TelnetClient(const std::string &serverIP,
const std::string &serverPort,
const size_t timeOut,
const size_t bufferSize)
: mBufferSize(bufferSize) {
// define our buffer
mBuffer = static_cast<char *>(malloc(sizeof(char) * mBufferSize));
try {
// let's make socket
mSockFd = makeConnection(serverIP, serverPort);
} catch (const std::runtime_error &error) {
// throw it to the user
throw std::runtime_error(error);
}
// socket related configuarations
configureReadWriteFd();
configureTimeout(timeOut);
// telnet options
const telnet_telopt_t telnetOpts[] = {
{ TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO},
{ TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT},
{TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO},
{ TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO},
{ -1, 0, 0}};
// initialize telnet box
mTelnet = telnet_init(telnetOpts, trampoline, 0, this);
}
int TelnetClient::makeConnection(const std::string &serverIP,
const std::string &serverPort) {
int retVal;
int sockFd;
struct addrinfo *addrInfo;
struct addrinfo addrHints; | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
// look up server host
memset(&addrHints, 0, sizeof(addrHints));
addrHints.ai_family = AF_INET;
addrHints.ai_socktype = SOCK_STREAM;
if ((retVal = getaddrinfo(serverIP.c_str(), serverPort.c_str(), &addrHints, &addrInfo)) != 0) {
throw std::runtime_error("getaddrinfo() failed for " + serverIP + " with error: " + gai_strerror(retVal));
}
// create server socket
if ((sockFd = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol)) == -1) {
throw std::runtime_error("socket() failed: " + std::string(strerror(errno)));
}
// connect
if (connect(sockFd, addrInfo->ai_addr, addrInfo->ai_addrlen) == -1) {
auto error = std::string(strerror(errno));
close(sockFd);
throw std::runtime_error("connect() failed: " + error);
}
// free address lookup info
freeaddrinfo(addrInfo);
return sockFd;
}
void TelnetClient::trampoline(telnet_t *telnet,
telnet_event_t *event,
void *user_data) {
(void)telnet; // to get rid of unused parameter warning
TelnetClient *me = static_cast<TelnetClient *>(user_data);
me->telnetEvent(event);
} | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
void TelnetClient::telnetEvent(telnet_event_t *event) {
switch (event->type) {
// data received
case TELNET_EV_DATA:
mReceivedMsg = std::string(event->data.buffer, event->data.size);
#if DEBUG_MODE
std::cout << "response: [" << mReceivedMsg << "]" << std::endl;
#endif
break;
// data must be sent
case TELNET_EV_SEND:
sendAll(event->data.buffer, event->data.size);
break;
// execute to enable local feature (or receipt)
case TELNET_EV_DO:
throw NotImplemented();
// demand to disable local feature (or receipt)
case TELNET_EV_DONT:
throw NotImplemented();
// respond to TTYPE commands
case TELNET_EV_TTYPE:
throw NotImplemented();
// respond to particular subnegotiations
case TELNET_EV_SUBNEGOTIATION:
throw NotImplemented();
// error
case TELNET_EV_ERROR:
throw std::runtime_error("telnet error: " + std::string(event->error.msg));
default:
// ignore
break;
}
}
int TelnetClient::sendAll(const char *buffer, size_t size) {
int retVal = -1; // default value
// send data
while (size > 0) {
retVal = send(mSockFd, buffer, size, 0);
if (retVal == 0 || errno == EINTR) {
// try again
continue;
} else if (retVal == -1) {
throw std::runtime_error("send() failed: " + std::string(strerror(errno)));
}
// update pointer and size to see if we've got more to send
buffer += retVal;
size -= retVal;
}
return retVal;
}
void TelnetClient::configureReadWriteFd() {
// clear the set ahead of time
FD_ZERO(&mReadFd);
FD_ZERO(&mWriteFd);
// add our descriptors to the set
FD_SET(mSockFd, &mReadFd);
FD_SET(mSockFd, &mWriteFd);
}
void TelnetClient::configureTimeout(const size_t seconds) {
mTimeout.tv_sec = seconds;
mTimeout.tv_usec = 0;
}
void TelnetClient::execute(const std::string &command) {
int retVal = select(mSockFd + 1, NULL, &mWriteFd, NULL, &mTimeout); | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
if (retVal == -1) {
// error occurred in select()
throw std::runtime_error("select() failed: " + std::string(strerror(errno)));
} else if (retVal == 0) {
throw std::runtime_error("timeout occurred");
} else {
// send the execute
if (FD_ISSET(mSockFd, &mWriteFd)) {
#if DEBUG_MODE
// print only for debugging
std::cout << "request: [" << command << "]" << std::endl;
#endif
telnet_send(mTelnet, command.c_str(), command.length());
}
}
}
std::string TelnetClient::response() {
// erase previously received msg by setting it to an empty string
mReceivedMsg.clear();
int retVal = select(mSockFd + 1, &mReadFd, NULL, NULL, &mTimeout);
if (retVal == -1) {
// error occurred in select()
throw std::runtime_error("select() failed: " + std::string(strerror(errno)));
} else if (retVal == 0) {
throw std::runtime_error("timeout occurred");
} else {
// response the response
if (FD_ISSET(mSockFd, &mReadFd)) {
if ((retVal = recv(mSockFd, mBuffer, mBufferSize, 0)) > 0) {
telnet_recv(mTelnet, mBuffer, retVal);
} else if (retVal == 0) {
throw std::runtime_error("connection has been closed.");
} else {
throw std::runtime_error("recv() failed: " + std::string(strerror(errno)));
}
}
}
return mReceivedMsg;
}
TelnetClient::~TelnetClient() {
if (mBuffer) {
free(mBuffer);
mBuffer = NULL;
}
// clean up
telnet_free(mTelnet);
close(mSockFd);
}
} // namespace simple_telnet_client
2. simple_telnet_client.hpp
#ifndef SIMPLE_TELNET_CLIENT__TELNET_CLIENT_HPP_
#define SIMPLE_TELNET_CLIENT__TELNET_CLIENT_HPP_
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <libtelnet.h>
#include <iostream>
#include <stdexcept>
// flag to print requests and responses in the console for debugging purposes
#define DEBUG_MODE true | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
namespace simple_telnet_client {
class TelnetClient {
public:
TelnetClient(const std::string &serverIP,
const std::string &serverPort,
const size_t timeOut = 1,
const size_t bufferSize = 2048);
// execute a command on the server
void execute(const std::string &command);
// receive the response from the server
std::string response();
~TelnetClient();
private:
int mSockFd;
const size_t mBufferSize;
std::string mReceivedMsg;
fd_set mReadFd;
fd_set mWriteFd;
struct timeval mTimeout;
// todo: use std::unique_ptr?
telnet_t *mTelnet;
// todo: how about this?
char *mBuffer;
static void trampoline(telnet_t *telnet,
telnet_event_t *event,
void *user_data);
int makeConnection(const std::string &serverIP,
const std::string &serverPort);
void telnetEvent(telnet_event_t *event);
int sendAll(const char *mBuffer,
size_t size);
void configureTimeout(const size_t seconds);
void configureReadWriteFd();
};
} // namespace simple_telnet_client
#endif // SIMPLE_TELNET_CLIENT__TELNET_CLIENT_HPP_
PS: I am using C++14 and GCC 9.4 in Ubuntu 20.04 LTS.
Answer: Avoid using malloc() in C++
There are much better ways to allocate memory in C++ that are simpler and safer. First, in C++ you should use new if you really want to do your own memory allocation:
mBuffer = new char[mBufferSize];
But now you have to remember to delete it. Even better is to just use std::vector to manage a bunch of bytes for you:
class TelnetClient {
...
std::vector<char> mBuffer;
...
};
TelnetClient::TelnetClient(const std::string &serverIP,
const std::string &serverPort,
const size_t timeOut,
const size_t bufferSize)
: mBuffer(bufferSize) {
...
} | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
Now you no longer need to free mBuffer yourself.
To receive data into the buffer, you can write:
retVal = recv(mSockFd, mBuffer.data(), mBuffer.size(), 0);
This also avoids a memory leak in the constructor of TelnetClient, as when you throw because makeConnection() failed, the vector will be automatically cleaned up, but manually allocated memory will not.
Avoid other C-isms in C++
Since you are using socket functions, your code is going to look a bit like C anyway, but try to avoid coding like C and use more idiomatic C++ code where possible. Instead of memcpy() and memset(), consider using std::copy_n() and std::fill_n(). But if you just want to zero-initialize a struct, you can write this:
struct addrinfo addrHints = {};
Pay attention to the return type of functions
In response() you declare int retVal. This is the right type to store the return value of select(). But later on you reuse retVal to store the return value of recv(). However, recv() returns a ssize_t, not an int. Due to implicit conversion rules this is legal, but the value returned might not fit in an int, which can lead to problems. Always store return values in the correct type.
Consider not reusing variables in this case, and using auto to deduce the correct type:
auto retVal = select(...);
...
auto received = recv(...);
Overuse of exceptions
Exceptions should be used for exceptional errors. However, network errors are rather common, and particularly the remote end closing the connection is quite normal. So arguably, instead of throwing exceptions, you should return error codes in these cases. Consider using std::error_code for this.
Since C++17, you could also consider using std::optional<> to return things, and in C++23 we will get std::expected<>.
You also wrote some code that doesn't make sense at all, for example:
try {
mSockFd = makeConnection(serverIP, serverPort);
} catch (const std::runtime_error &error) {
throw std::runtime_error(error);
} | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
Here you catch an exception only to rethrow it immediately. Just don't catch it here, the whole point of exceptions is that they will propagate up the call stack until something can actually handle the error.
As Jack Aidley mentioned, it also helps if you create your own exception types that inherit from the standard exception types. This allows callers to programmatically detect exactly what kind of error happened, without them having to parse the .what() text.
Not all errors are fatal
select(), recv() and send() might return -1 also when there is a recoverable error. In particular, if errno == EINTR, you should just try again.
Write log and error messages to std::cerr
Always write log, warning and error messages to std::cerr. Consider that the regular output of a program goes to std::cout, and if you are redirecting the standard output to a file, then if warnings and errors are written to std::cout as well, both get mixed up in the file, which is undesirable.
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 often unnecessary and might impact performance.
Avoiding unused parameter warnings
In C++ you can omit the name of a function parameter, this will suppress unused parameter warnings:
void TelnetClient::trampoline(telnet_t *,
telnet_event_t *event,
void *user_data) {
TelnetClient *me = static_cast<TelnetClient *>(user_data);
me->telnetEvent(event);
} | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, object-oriented, c++14, networking, wrapper
response() might not return the full response
response() only ever calls recv() once, so it is perfectly possible to only receive a partial response, but the name of this function suggests that it always receives a complete response.
Either this function should be written to call recv() in a loop until the whole response has been received (and deal with all the issues you might have with this, which we already discussed here), or it should just be renamed to recv() so it implies it has the same semantics as the POSIX recv() function. | {
"domain": "codereview.stackexchange",
"id": 43695,
"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++, object-oriented, c++14, networking, wrapper",
"url": null
} |
c++, c++20
Title: A parse function for text line with fields separated by a comma with the known number and their type
Question: I am trying to parse a line with a fixed amount of fields and known types.
using Text = FieldType<std::string>;
using Int = FieldType<int>;
using Name = Text;
using TextSpecificField = Text;
using IntSpecificField = Int;
struct LineData
{
Name name;
TextSpecificField textField;
IntSpecificField intField;
// LineData contains 12 fields in total, types are known
};
struct InvalidLine { std::string line, err; };
using Line = std::variant<LineData, InvalidLine>;
With that, I can write a parsing function for each specific field type:
template<Field T>
constexpr auto parse(std::string_view field) -> detail::ReturnOptErr<T>
{
if constexpr (std::is_same_v<Text, T>)
{
return {decltype(T::value){field}};
}
else if constexpr (std::is_same_v<Int, T>)
{
auto [value, err] = toNum<decltype(T::value)>(field); // Why typename T::value doesn't work?
return {T{value}, std::move(err)};
}
else
{
[]<bool flag = false> { static_assert(flag, "no match"); }();
}
}
Here my problem starts with the below parse function. I am having trouble wrapping my head around trying to simplify this piece of code. As it can be seen, there is a repeating pattern that I would like to abstract:
auto parse(std::string_view line) -> Line
{
// Parsing a string and returning string is done intentionally to show repeating pattern
auto [nameStr, rest] = split(line, ',');
auto name = parse<Name>(nameStr);
if (name.errorText)
{
return InvalidLine{std::string{line}, std::move(name.errorText.value())};
}
auto [textStr, rest2] = split(rest, ',');
auto textField = parse<TextSpecificField>(textStr);
if (textField.errorText)
{
return InvalidLine{std::string{line}, std::move(textField.errorText.value())};
} | {
"domain": "codereview.stackexchange",
"id": 43696,
"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++, c++20",
"url": null
} |
c++, c++20
auto [intStr, rest3] = split(rest2, ',');
auto intField = parse<IntSpecificField>(intStr);
if (intField.errorText)
{
return InvalidLine{std::string{line}, std::move(intField.errorText.value())};
}
return LineData{std::move(name.value), std::move(textField.value), intField.value};
}
Is there an elegant way to approach this? I thought about using exceptions, but I don't like that solution. I also tried to approach this problem using template recursion, but I could not come up with an idea of returning Line from such a parser.
Full example
BR
#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <optional>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <variant>
// - Utility ---------------------------------------------------------------------------------------
namespace detail
{
template <typename FieldType>
struct ReturnOptErr
{
FieldType value;
std::optional<std::string> errorText;
};
} // namespace detail
template<typename T>
constexpr auto toNum(std::string_view valueStr) -> detail::ReturnOptErr<T>
{
// Implementation of number parsing using <charconv>
return detail::ReturnOptErr<T>{123};
}
constexpr auto split(std::string_view input, char delim) noexcept -> std::pair<std::string_view, std::string_view>
{
auto const delimPos = input.find(delim);
if (delimPos == std::string_view::npos)
{
return {input, ""};
}
auto const token = input.substr(0, delimPos);
auto const rest = input.substr(delimPos + 1);
return {token, rest};
}
// - Data ------------------------------------------------------------------------------------------
template<typename T>
struct FieldType
{
T value;
};
template<typename T>
concept Field = std::is_same_v<FieldType<decltype(T::value)>, T>;
auto operator<<(std::ostream& os, Field auto const& field) -> std::ostream&
{
return os << field.value;
} | {
"domain": "codereview.stackexchange",
"id": 43696,
"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++, c++20",
"url": null
} |
c++, c++20
using Text = FieldType<std::string>;
using Int = FieldType<int>;
using Name = Text;
using TextSpecificField = Text;
using IntSpecificField = Int;
// more field types
// ------------------------------------------------------------------------------------------------
struct LineData
{
Name name;
TextSpecificField textField;
IntSpecificField intField;
// LineData containts 12 fields in total, types are known
};
struct InvalidLine { std::string line, err; };
using Line = std::variant<LineData, InvalidLine>;
// - Parser ----------------------------------------------------------------------------------------
template<Field T>
constexpr auto parse(std::string_view field) -> detail::ReturnOptErr<T>
{
if constexpr (std::is_same_v<Text, T>)
{
return {decltype(T::value){field}};
}
else if constexpr (std::is_same_v<Int, T>)
{
auto [value, err] = toNum<decltype(T::value)>(field); // Why typename T::value doesn't work?
return {T{value}, std::move(err)};
}
else
{
[]<bool flag = false> { static_assert(flag, "no match"); }();
}
}
auto parse(std::string_view line) -> Line
{
// Parsing a string and returning string is done intentionally to show repeating pattern
auto [nameStr, rest] = split(line, ',');
auto name = parse<Name>(nameStr);
if (name.errorText)
{
return InvalidLine{std::string{line}, std::move(name.errorText.value())};
}
auto [textStr, rest2] = split(rest, ',');
auto textField = parse<TextSpecificField>(textStr);
if (textField.errorText)
{
return InvalidLine{std::string{line}, std::move(textField.errorText.value())};
}
auto [intStr, rest3] = split(rest2, ',');
auto intField = parse<IntSpecificField>(intStr);
if (intField.errorText)
{
return InvalidLine{std::string{line}, std::move(intField.errorText.value())};
} | {
"domain": "codereview.stackexchange",
"id": 43696,
"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++, c++20",
"url": null
} |
c++, c++20
return LineData{std::move(name.value), std::move(textField.value), intField.value};
}
int main()
{
std::string lineStr = "name, text, 123456";
auto lineVar = parse(lineStr);
auto& line = std::get<LineData>(lineVar);
std::cout << line.name << ", " << line.textField << ", " << line.intField << "\n";
}
Answer: Create a helper function
To reduce the code repetition, a classic solution is to write a helper function. You can do that here as well. First let's look at how we want parse() to look:
auto parse(std::string_view line) -> Line
{
LineData data;
parse_field(line, &data.name);
parse_field(line, &data.textField);
parse_field(line, &data.intField);
return data;
}
The function parse_field() gets a reference to the member of data, and by making it a template it can deduce the type for us. It could look like:
void parse_field(std::string_view& line, auto& member)
{
auto [field, line] = split(line, ',');
member = parse<decltype(member)>(field);
}
Note the reference to line in the latter function. I have also omitted all the error checking here, that should be added back of course. Note that you can do that in a way that still preserves the simple structure of parse() above. For example, you could pass a reference to a InvalidLine to parse_field(), and have parse_field() return a bool on error, so you can chain the calls to parse_field() with ||.
You still need to repeat parse_field(line, &data.member) for each member, you can reduce even that by creating a variadic parse_fields() function, so that in parse() you only have to write:
auto parse(std::string_view line) -> Line
{
LineData data;
parse_fields(line, &data.name, &data.textField, &data.intField);
return data;
} | {
"domain": "codereview.stackexchange",
"id": 43696,
"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++, c++20",
"url": null
} |
c++, c++20
A fully generic solution
It would be nice to create a fully generic parse() function that would work with any struct, not just Line. It is unfortunate that C++ doesn't have introspection yet; because ideally you would write a function like:
template<typename LineType>
requires std::is_class<LineType>
auto parse(std::string_view line) {
LineType result;
for (member: LineType) {
auto [field, line] = split(line, ',');
result.member = parse<decltype(result.member)>(field);
}
return result;
}
However, you can approach this hypothetical solution by using a std::tuple instead of a struct to hold all the fields of a line. A solution could then look like so:
template <typename T>
constexpr bool is_tuple = false;
template<typename ... Ts>
constexpr bool is_tuple<std::tuple<Ts...>> = true;
template<TupleType>
requires is_tuple<TupleType>
auto parse(std::string_view line) {
TupleType result;
auto parse_one = [&](auto& arg) {
auto [field, line] = split(line, ',');
arg = parse<decltype(arg)>(field);
};
std::apply([&](auto&... args) {
(parse_one(args), ...);
}, result);
return result;
}
Then you could do this:
using LineData = std::tuple<Name, textField, intField>;
...
LineData data = parse<decltype(data)>(line);
You can avoid having to pass the type as a template parameter by not using a return value but passing the result using a reference function parameter. Of course the drawback is that getting access to the fields in a tuple is not very nice. | {
"domain": "codereview.stackexchange",
"id": 43696,
"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++, c++20",
"url": null
} |
python, pandas, matplotlib
Title: Plot time windows based on interested value
Question: I use the following code to identify some interested values into a dataframe and them plot a time window before and after that value appeared. It works very well, but I would like to know if there is a less coding way/more pythonic way to accomplish this. Thanks in advance!
Before I go, I try to use only Seaborn on the plotting secction, but creating the subplots and filling then was easier, considering I don't want to share axis.
# Libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
# Generate Data
rng = np.random.default_rng(12345)
df = pd.DataFrame(
index=pd.date_range(start="1/1/2019", periods=1035, freq='D'),
data={'value':rng.integers(-100, 30000, 1035)}
).reset_index()
# Creating a boolean for interesting values
df['select'] = df['value'] < 0
# Finding days with interested value and creating the periods
lt_dates = df.loc[df['select'], 'index'].to_list()
lt_days_after = [pd.DataFrame(index=pd.date_range(start=day, periods=14, freq='D')).reset_index() for day in lt_dates]
lt_days_before = [pd.DataFrame(index=pd.date_range(end=day, periods=14, freq='D')).reset_index() for day in lt_dates]
# Concatenating the periods
df_mask = pd.concat(objs=[pd.concat(lt_days_after), pd.concat(lt_days_before)]).sort_values('index').drop_duplicates(ignore_index=True)
# Flagging days
df['grouped'] = df['index'].isin(df_mask['index'])
# Creating the groups
df['slice'] = (~df['grouped']).cumsum()
groups = df.loc[df['grouped'], 'slice'].unique()
groups_dict = {y: x for x, y in enumerate(groups)}
# Filtering non interested values
df = df.loc[df['grouped']]
df['slice'].replace(groups_dict, inplace=True)
# Plotting
rows = len(groups_dict) | {
"domain": "codereview.stackexchange",
"id": 43697,
"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, pandas, matplotlib",
"url": null
} |
python, pandas, matplotlib
df['slice'].replace(groups_dict, inplace=True)
# Plotting
rows = len(groups_dict)
# Function to fill the subplots
def subplot_df(_ax, x):
sns.lineplot(
x="index",
y='value',
ci=None,
data=df[df['slice'] == x],
ax=_ax
)
_ax.set_xlabel('')
f, ax = plt.subplots(
nrows=rows,
figsize=(12, 2*rows),
sharex=False,
sharey=False
)
# Filling a single or multiple subplots
if rows != 0:
for x in range(rows):
subplot_df(ax[x], x)
else:
subplot_df(ax, 0)
Answer: Avoid passing strings for parameters like start when they come from application constants and not the user; use date instances instead.
You rely on reset_index too much - this can go away and be replaced with direct construction of the dataframe. One consequence of your approach is that there's a column called index, which is not a good idea because attribute access for the column is broken (i.e. you can't write df.index).
Your use of isin, the separate treatment of after and before, and your enumerate and replace can go away. Consider instead a broadcast comparison of time deltas.
Suggested
from datetime import date
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
rng = np.random.default_rng(12345)
df = pd.DataFrame({
'when': pd.date_range(
start=date(2019, 1, 1), periods=1035, freq='D'
),
'value': rng.integers(low=-100, high=30_000, size=1035)
})
# Creating a boolean for interesting values
selected = df.value < 0
all_selected = np.abs(
df['when'].values[:, np.newaxis] -
df['when'][selected].values[np.newaxis, :]
) < pd.to_timedelta(14, unit='D')
df['grouped'] = np.bitwise_or.reduce(all_selected, axis=1)
grouped = np.zeros(1+len(selected), dtype=bool)
grouped[1:] = df.grouped
changes = np.abs(np.diff(grouped))
df['slice'] = changes.cumsum() // 2
# Filtering non interesting values
df = df.loc[df.grouped, :] | {
"domain": "codereview.stackexchange",
"id": 43697,
"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, pandas, matplotlib",
"url": null
} |
python, pandas, matplotlib
# Filtering non interesting values
df = df.loc[df.grouped, :]
# Plotting
rows = round(changes.sum() // 2)
# Function to fill the subplots
def subplot_df(ax: plt.Axes, x: int) -> None:
sns.lineplot(
x='when',
y='value',
ci=None,
data=df[df['slice'] == x],
ax=ax,
)
ax.set_xlabel('')
f, ax = plt.subplots(
nrows=rows,
figsize=(12, 2*rows),
sharex=False,
sharey=False,
)
# Filling a single or multiple subplots
if rows == 0:
subplot_df(ax, 0)
else:
for x in range(rows):
subplot_df(ax[x], x)
plt.show() | {
"domain": "codereview.stackexchange",
"id": 43697,
"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, pandas, matplotlib",
"url": null
} |
beginner, haskell, functional-programming, lambda, collatz-sequence
Title: Meta Collatz Sequence
Question: Context
Chapter 6 of Learn You A Haskell contains a function called chain, which outputs the Collatz sequence of a given input.
(In short, it takes a natural number. If that number is even, it divides it by two. If it's odd, it multiplies it by 3 and then adds 1 to that. It then takes the resulting number and applies the same thing to it, which produces a new number and so on).
Here's the book's implementation of that function:
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain n
| even n = n : chain (n `div` 2)
| odd n = n : chain (n * 3 + 1)
There's a function a little later in the chapter, which returns the number of chains with a starting number between 1 and 100 where the chain is longer than 15, here's that function:
numLongChains' :: Int -> Int
numLongChains' n = length (filter (\xs -> length xs > 15) (map chain [1..n]))
My code
I attempted to write a function that would output how many chains you'd have to generate in order to get the number of "long chains" equal to a certain amount. (For example, generating 100 chains produces 66 "long chains", you can see this by running numLongChains' 100).
Here's that function (written for Iron Maiden's "human number", 666):
humanNumLongChains :: (Integral a) => a -> [[a]] -> a
humanNumLongChains n xs
| length (filter (\ys -> length ys > 15) xs) == 666 = n
| otherwise = humanNumLongChains (n + 1) (xs ++ [chain (n + 1)])
I'm fairly new to Haskell (and purely functional programming in general), this function seems a bit messy to me, all feedback is welcome. | {
"domain": "codereview.stackexchange",
"id": 43698,
"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": "beginner, haskell, functional-programming, lambda, collatz-sequence",
"url": null
} |
beginner, haskell, functional-programming, lambda, collatz-sequence
Answer: Preliminaries
Because code reviews are all about how you can improve your code, it can sometimes feel like reviewers are tearing apart the code you spent so long writing. I like to begin my review with a few words of encouragement. First, your code works and appears bug-free. Second, you seem to get Haskell enough to explore your own problems successfully. Both are no small feat -- keep it up!
Small steps
First, it's unclear to me how humanNumLongChains is supposed to be invoked, or what the function name means. From what I gather, you're looking to find the inverse of numLongChains' at 666 (i.e. what n you need to give to numLongChains' to produce 666). The n and xs are accumulator arguments which are to be initialized to specific values. It's also not immediately clear that n should be initialized to 0; I was putting 1 at first until I realized that it wouldn't check the chain for 1 if I did that.
Let's do specify the initial arguments and give our "function" a new name.
invNumLongChains1 :: Int
invNumLongChains1 = humanNumLongChains 0 []
I wrote "function" since now it's been revealed that what we really have is just a value, which appears to be 730.
I see no reason why it couldn't be a function proper. Instead of hard-coding 666, we could take that as an argument.
invNumLongChains2 :: Int -> Int
invNumLongChains2 numChains = go 0 []
where
go :: Int -> [[Int]] -> Int
go n chains
| length (filter (\ys -> length ys > 15) chains) == numChains = n
| otherwise = humanNumLongChains (n + 1) (chains ++ [chain (n + 1)]) | {
"domain": "codereview.stackexchange",
"id": 43698,
"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": "beginner, haskell, functional-programming, lambda, collatz-sequence",
"url": null
} |
beginner, haskell, functional-programming, lambda, collatz-sequence
Note that go is a common convention for helper functions scoped locally to the main function. I'm not a huge fan of it, but I didn't want to spend longer thinking of a better name. This helper function is pretty much just humanNumLongChains copy/pasted anyway.
Now we can invoke invNumLongChains2 666 and get 730.
Efficiency
The biggest spot for inefficiency in your program is your use of lists. Unfortunately, lists in Haskell don't know their own length, so each invocation of length is O(n)!
The first simple change we can make is to instead of accumulating a list of chains, accumulate a list of chain lengths.
invNumLongChains3 :: Int -> Int
invNumLongChains3 numChains = go 0 []
where
go :: Int -> [Int] -> Int
go n chainLengths
| length (filter (\chainLength -> chainLength > 15) chainLengths) == numChains = n
| otherwise = go (n + 1) (chainLengths ++ [length $ chain (n + 1)])
You can look at the type signature of go to quickly see the change: we've gone from taking a [[Int]] to just a regular [Int].
Unfortunately, there are two other places where lists are used inefficiently. The first is the fact that we're still using length on our filtered list and the second is that you're using (++) to append to the list. Unfortunately, (++) is also O(n) even though you're only appending a single element. This is because it needs to traverse the whole linked list to append it.
It's not difficult to see that we don't even need the list of lengths. We can just keep track of a single number representing how many long chains we've seen so far.
invNumLongChains4 :: Int -> Int
invNumLongChains4 numChains = go 0 0
where
go :: Int -> Int -> Int
go n numLongChains
| numLongChains == numChains = n
| otherwise = if length (chain (n + 1)) > 15
then go (n + 1) (numLongChains + 1)
else go (n + 1) numLongChains | {
"domain": "codereview.stackexchange",
"id": 43698,
"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": "beginner, haskell, functional-programming, lambda, collatz-sequence",
"url": null
} |
beginner, haskell, functional-programming, lambda, collatz-sequence
Now go has gone from taking a [Int] to a single Int, and our argument has changed from [] to 0 to reflect this.
Getting lazier
I'm running out of steam a little, but I wanted to leave two alternate versions of your function that make use of laziness. I think they are both equivalently efficient to invNumLongChains4 (maybe a little less, depending on how the compiler optimizes things), but they turn the problem on its head a little bit.
Instead of iterating over n and accumulating a count of long chain lengths, the idea is to create an infinite list where the element at position n represents the number of long chains at n. Then we just find the index of 666 in that infinite list. This works because Haskell is lazy, so we only evaluate the elements of this list when we check them!
Some notes: Because elemIndex returns a Maybe, we need to extract the value using fromJust. This is usually bad practice (you would want to instead keep the result a Maybe) because it will error if there is no element. However, because we're using it on an infinite list we will never get a Nothing back (the code will just infinitely loop if it can't find a match). The other part is that elemIndex 0-indexes and we're starting our list from 1, so we need to add 1 to the result it finds.
Here is the first rewrite. I tried to break things apart enough to make it clear what's going on.
invNumLongChains5 :: Int -> Int
invNumLongChains5 numChains = (+1) $ fromJust $ elemIndex numChains longChainCounts
where
chains :: [[Int]]
chains = map chain [1..]
countLongChains :: Int -> [[Int]] -> [Int]
countLongChains prevCount (chain:chains)
| length chain > 15 = prevCount + 1 : countLongChains (prevCount + 1) chains
| otherwise = prevCount : countLongChains prevCount chains
longChainCounts :: [Int]
longChainCounts = countLongChains 0 chains | {
"domain": "codereview.stackexchange",
"id": 43698,
"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": "beginner, haskell, functional-programming, lambda, collatz-sequence",
"url": null
} |
beginner, haskell, functional-programming, lambda, collatz-sequence
In the second rewrite, I make use of a standard function called scanl1 to replace the helper function countLongChains. It's all right if this doesn't make sense to you! If you're really interested in understanding how it works, let me know in a comment and I can try to pull together some time to explain.
invNumLongChains6 :: Int -> Int
invNumLongChains6 numChains = (+1) . fromJust $ elemIndex numChains longChainCounts
where
isLongEnough :: [Int] -> Int
isLongEnough chain
| length chain > 15 = 1
| otherwise = 0
longChainCounts :: [Int]
longChainCounts = scanl1 (+) $ map (isLongEnough . chain) [1..]
I'm no Haskell guru, but I would probably prefer invNumLongChains4 to invNumLongChains6 for readability's sake. However, I do think that the latter could be considered a more "functional" approach, which is why I included it.
Try it Online!
Here's a TIO snippet with all the functions, in case you wanted to play around with them. Or, more likely, in case I forgot to copy/paste an update I made to my answer -- the TIO snippet should have everything up-to-date.
Try it Online!
Postscripts
I use Int instead of (Integral a) => a because there are places where I compare the variable with that type to length x. For historical reasons, length x returns an Int. It's a little annoying to have to put fromIntegral so I instead just use narrow the type to Int.
I would probably also want to pull out the magic number 15 that is present for the length, but decided against it for simplicity's sake.
There's another major point on efficiency: memoizing chain. But I decided that this was too much to discuss in my review.
I would recommend as an exercise that you test the efficiency of all of these rewrites. I didn't, and I'm somewhat-maybe-slightly worried I'm wrong about my efficiency assessments (especially of invNumLongChains5 and invNumLongChains6). | {
"domain": "codereview.stackexchange",
"id": 43698,
"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": "beginner, haskell, functional-programming, lambda, collatz-sequence",
"url": null
} |
python, programming-challenge, time-limit-exceeded
Title: Time limit error in 'The Minion Game' using python in Hacker Rank
Question: This is the question link for the quick reference.
Problem :
There are two players Kevin and Stuart have to play a game in which they're pleased to create multiple strings and will get +1 score for each sub string for which Kevin would select the sub string starting from vowels and Stuart will select for consonants only.
Input :
String in capital
Output :
Winner name and their score separated with space
Note :
length of string should varies from 0 to 10^6
this is my code given below:
#!/usr/bin/env python3 | {
"domain": "codereview.stackexchange",
"id": 43699,
"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, programming-challenge, time-limit-exceeded",
"url": null
} |
python, programming-challenge, time-limit-exceeded
def minion_game(string):
# Verification of basic functionalty
for character in string:
if 0<=ord(character)<65 or 90<ord(character)<=255 or len(string)>10**6:
return None
# list of vowels and consonant
vowel=[]
consonant=[]
for num in range(65,91,1):
if num == 65 or num == 69 or num == 73 or num == 79 or num == 85:
vowel.extend(chr(num))
else:
consonant.extend(chr(num))
#Test string
#print(''.join(vowel) + '\n' + ''.join(consonant))
score={'Stuart' : 0, 'Kevin' : 0}
for iteration in range(1,len(string)+1):
count= iteration
for index in range(0,len(string)):
if count<=len(string):
char = string[index:count]
count+=1
#Check for one character
if len(char)==1:
if char[0] in vowel:
score['Kevin']+=1
elif char[0] in consonant:
score['Stuart']+=1
#Check for sub string
else:
#logic goes here
temp_string = string
if char[0] in vowel:
#logic goes here
for i in range(len(temp_string)):
if char in temp_string:
a=temp_string.find(char)
score['Kevin']+=1
temp_string = ''.join(list(temp_string).pop(a))
elif char[0] in consonant:
#logic goes here
for i in range(len(temp_string)):
if char in temp_string:
a=temp_string.find(char)
score['Stuart']+=1
temp_string = ''.join(list(temp_string).pop(a))
#Test string
#print(score) | {
"domain": "codereview.stackexchange",
"id": 43699,
"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, programming-challenge, time-limit-exceeded",
"url": null
} |
python, programming-challenge, time-limit-exceeded
#Test string
#print(score)
#Winner Selection
if score['Kevin']>score['Stuart']:
print("Kevin "+ str(score['Kevin']))
elif score['Kevin']==score['Stuart']:
print("Draw")
else:
print("Stuart "+ str(score['Stuart'])) | {
"domain": "codereview.stackexchange",
"id": 43699,
"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, programming-challenge, time-limit-exceeded",
"url": null
} |
python, programming-challenge, time-limit-exceeded
if __name__ == '__main__':
s = input()
minion_game(s)
This codes runs fine the only problem i observe is the time complexity which I'm not able to solve.
Answer: The number of substrings with a fixed starting point is just the length of the remaining string. Also you might want to use the string module a bit + some literals instead of ord. Additionally membership lookup is much faster in sets than lists. You can use these to simplify things down a lot:
import string
VOWELS = set('aeiouAEIOU')
CONSONANTS = set(string.ascii_letters) - VOWELS
def new_minion_game(s):
total_len = len(s)
kevin = 0
stuart = 0
for index, character in enumerate(s):
if character in VOWELS:
kevin += total_len - index
elif character in CONSONANTS:
stuart += total_len - index
return kevin, stuart
On my system this was approx. 200x faster. | {
"domain": "codereview.stackexchange",
"id": 43699,
"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, programming-challenge, time-limit-exceeded",
"url": null
} |
python, object-oriented, programming-challenge, finance
Title: Geektrust coding challenge: simulating a marketplace for loans
Question: This is the my solution to a coding challenge in Geektrust. The question is linked here.
A shortened version would be as follows.
The aim is to simulate a marketplace for banks to lend money to borrowers and receive payments for the loans. It takes as input:
The bank name, borrower name, principal, interest and term.
Lump sum payments if any.
Given the bank name, borrower name, and EMI number, the program should print the total amount paid by the user (including the EMI number mentioned) and the remaining number of EMIs.
The output should be
Amount paid so far, and number of EMIs remaining for the user with the bank
These are the commands the program takes as input
LOAN BANK_NAME BORROWER_NAME PRINCIPAL NO_OF_YEARS RATE_OF_INTEREST
PAYMENT BANK_NAME BORROWER_NAME LUMP_SUM_AMOUNT EMI_NO
BALANCE BANK_NAME BORROWER_NAME AMOUNT_PAID EMI_NO
This is my solution to the problem
import math
from sys import argv
LOAN = "LOAN"
PAYMENT = "PAYMENT"
BALANCE = "BALANCE"
MONTHS_IN_A_YEAR = 12
HUNDRED = 100
def round_to_whole_no(n):
return math.ceil(n)
class Bank:
def __init__(self, name):
self.name = name
class BankLoan:
def __init__(self, **kwargs):
self.bank = kwargs['bank']
self.principal = kwargs['principal']
self.rate_of_interest = kwargs['rate_of_interest']
self.no_of_years = kwargs['no_of_years']
self.borrower = kwargs['borrower']
def interest(self):
return self.principal * self.no_of_years * (self.rate_of_interest / HUNDRED)
def total_amount(self):
return self.interest() + self.principal
def emi_amount(self):
return round_to_whole_no(self.total_amount() / (self.no_of_years * MONTHS_IN_A_YEAR))
def no_of_emi(self):
return self.no_of_years * MONTHS_IN_A_YEAR
class Borrower:
def __init__(self, name):
self.name = name | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
class Borrower:
def __init__(self, name):
self.name = name
class LedgerEntry:
def __init__(self, bank_loan=None, payment=None):
self.bank_loan = bank_loan
self.payment = payment
def add_payment(self, payment):
self.payment = payment
def balance(self):
if self.payment is None:
return self.bank_loan.total_amount()
else:
return self.bank_loan.total_amount() - self.payment.lump_sum_amount
def amount_paid(self, emi_no):
if self.payment is None:
return emi_no * self.bank_loan.emi_amount()
else:
if emi_no >= self.payment.emi_no:
return self.payment.lump_sum_amount +\
(self.balance()
if ((emi_no * self.bank_loan.emi_amount()) + self.payment.lump_sum_amount) >
self.bank_loan.total_amount()
else emi_no * self.bank_loan.emi_amount())
else:
return emi_no * self.bank_loan.emi_amount()
def no_of_emi_left(self, emi_no):
if self.payment is None:
return self.bank_loan.no_of_emi() - emi_no
else:
remaining_principal = self.bank_loan.total_amount() - self.amount_paid(emi_no=emi_no)
remaining_emi = round_to_whole_no(remaining_principal / self.bank_loan.emi_amount())
return remaining_emi
class Ledger(dict):
def __init__(self):
super().__init__()
def add_entry_to_ledger(self, bank_name, borrower_name, ledger_entry):
self[bank_name] = {}
self[bank_name][borrower_name] = ledger_entry
class Payment:
def __init__(self):
pass
def __init__(self, **kwargs):
self.bank_loan = kwargs['bank_loan']
self.lump_sum_amount = kwargs['lump_sum_amount']
self.emi_no = kwargs['emi_no']
def main():
ledger = Ledger() | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
def main():
ledger = Ledger()
if len(argv) != 2:
raise Exception("File path not entered")
file_path = argv[1]
f = open(file_path, 'r')
lines = f.readlines()
for line in lines:
if line.startswith(LOAN):
bank_name, borrower_name, principal, no_of_years, rate_of_interest = line.split()[1:]
bank = Bank(name=bank_name)
borrower = Borrower(name=borrower_name)
bank_loan = BankLoan(bank=bank,
borrower=borrower,
principal=float(principal),
no_of_years=float(no_of_years),
rate_of_interest=float(rate_of_interest))
ledger_entry = LedgerEntry(bank_loan=bank_loan)
ledger.add_entry_to_ledger(bank_name=bank_name, borrower_name=borrower_name,
ledger_entry=ledger_entry)
if line.startswith(PAYMENT):
bank_name, borrower_name, lump_sum_amount, emi_no = line.split()[1:]
ledger_entry = ledger[bank_name][borrower_name]
payment = Payment(bank_loan=ledger_entry.bank_loan,
lump_sum_amount=float(lump_sum_amount),
emi_no=float(emi_no))
ledger_entry.add_payment(payment)
ledger[bank_name][borrower_name] = ledger_entry
if line.startswith(BALANCE):
bank_name, borrower_name, emi_no = line.split()[1:]
ledger_entry = ledger[bank_name][borrower_name]
amount_paid = int(ledger_entry.amount_paid(emi_no=float(emi_no)))
no_of_emis_left = int(ledger_entry.no_of_emi_left(emi_no=float(emi_no)))
print(bank_name, borrower_name, str(amount_paid), str(no_of_emis_left))
if __name__ == "__main__":
main() | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
if __name__ == "__main__":
main()
The automated review of the code by Geektrust has reported the code to have poor Object Oriented modelling and that it breaks encapsulation.
Answer: Out of all of your constants, only one is worth keeping, MONTHS_IN_A_YEAR; the others are less useful than having no declared constant at all.
round_to_whole_no first of all obscures what actually happens: I'd naively assume that this rounds up or down, but it only rounds up. But it's also less useful than having no function at all; just call ceil directly.
Add PEP484 type hints.
You have some kwarg abuse: for instance, in BankLoan's constructor, you know exactly what the arguments need to be: so why not write them out?
Bank as it stands is not useful. You could reframe it as containing loans, in which case it would be useful.
Your BankLoan.interest etc. would be better-modelled with @property.
Broadly, this code seems... not right? I don't read anything in the problem description guaranteeing that there will be at most one lump sum payment. If there is more than one lump sum payment on a loan, I doubt that your code will do the right thing.
It's not a good idea to inherit from dict in this case: you should has-a rather than is-a, for your database lookup pattern.
Use argparse.
For important financials, usually prefer Decimal instead of float.
main does too much. You need to delegate to routines in the classes.
Suggested
import argparse
import math
from bisect import bisect
from decimal import Decimal
from itertools import islice
from locale import setlocale, currency, LC_ALL
from typing import TextIO, NamedTuple, Iterable, Iterator
MONTHS_PER_YEAR = 12
class LoanRecord(NamedTuple):
bank_name: str
borrower_name: str
principal: Decimal # P
tenure_years: Decimal # N
interest_rate: Decimal # R | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
@classmethod
def parse(
cls,
bank_name: str, borrower_name: str,
principal: str, no_of_years: str, interest_rate: str,
) -> 'LoanRecord':
return cls(
bank_name=bank_name, borrower_name=borrower_name,
principal=Decimal(principal),
tenure_years=Decimal(no_of_years),
interest_rate=Decimal(interest_rate),
)
class PaymentRecord(NamedTuple):
# in sortation priority
emi_no: int
bank_name: str
borrower_name: str
lump_sum: Decimal
@classmethod
def parse(
cls,
bank_name: str, borrower_name: str,
lump_sum: str, emi_no: str,
) -> 'PaymentRecord':
return cls(
bank_name=bank_name, borrower_name=borrower_name,
lump_sum=Decimal(lump_sum), emi_no=int(emi_no),
)
class BalanceRecord(NamedTuple):
bank_name: str
borrower_name: str
emi_no: int
@classmethod
def parse(
cls, bank_name: str, borrower_name: str, emi_no: str,
) -> 'BalanceRecord':
return cls(
bank_name=bank_name, borrower_name=borrower_name, emi_no=int(emi_no),
)
class Loan:
def __init__(self, record: LoanRecord) -> None:
self.interest_rate = record.interest_rate
self.principal = record.principal
self.tenure_years = record.tenure_years
self.lump_payments: list[PaymentRecord] = []
def process_payment(self, payment: PaymentRecord) -> None:
i = bisect(a=self.lump_payments, x=payment)
self.lump_payments.insert(i, payment)
def iter_payments(self) -> Iterator[int]:
i_start = 0
emi_amount = self.emi_amount
for lump_payment in self.lump_payments:
for i in range(i_start, lump_payment.emi_no):
yield emi_amount
yield emi_amount + lump_payment.lump_sum
i_start = lump_payment.emi_no
while True:
yield emi_amount | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
while True:
yield emi_amount
def iter_payments_to_end(self) -> Iterator[int | Decimal]:
owing = self.total_amount
for payment in self.iter_payments():
new_owing = owing - payment
if new_owing < 0:
yield owing
return
yield payment
if new_owing == 0:
return
owing = new_owing
def replay(self, emi_no: int) -> tuple[
Decimal, # amount paid
int, # payment periods left
]:
payments = self.iter_payments_to_end()
paid = sum(islice(payments, emi_no))
payments_remaining = sum(1 for _ in payments)
return paid, payments_remaining
def describe(self, emi_no: int) -> str:
paid, payments_left = self.replay(emi_no)
return f'{currency(paid)} {payments_left}'
@property
def interest(self) -> Decimal: # I
return self.principal * self.tenure_years * self.interest_rate/100
@property
def total_amount(self) -> Decimal: # A
return self.principal + self.interest
@property
def emi_amount(self) -> int:
return math.ceil(
self.total_amount / self.tenure_years / MONTHS_PER_YEAR
)
class Bank:
def __init__(self, name: str) -> None:
self.name = name
self.loans: dict[str, Loan] = {}
def __str__(self) -> str:
return self.name
def process_loan(self, loan: LoanRecord) -> None:
self.loans[loan.borrower_name] = Loan(loan)
def process_payment(self, payment: PaymentRecord) -> None:
self.loans[payment.borrower_name].process_payment(payment)
def describe_balance(self, balance: BalanceRecord) -> str:
loan = self.loans[balance.borrower_name]
return f'{self.name} {balance.borrower_name} {loan.describe(balance.emi_no)}'
class Database:
def __init__(self) -> None:
self.banks: dict[str, Bank] = {} | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
class Database:
def __init__(self) -> None:
self.banks: dict[str, Bank] = {}
def _get_bank(self, record: LoanRecord | PaymentRecord | BalanceRecord) -> Bank:
bank = self.banks.get(record.bank_name)
if bank is None:
bank = self.banks[record.bank_name] = Bank(record.bank_name)
return bank
def process_loan(self, loan: LoanRecord) -> None:
self._get_bank(loan).process_loan(loan)
def process_payment(self, payment: PaymentRecord) -> None:
self._get_bank(payment).process_payment(payment)
def describe_balance(self, balance: BalanceRecord) -> str:
return self._get_bank(balance).describe_balance(balance)
def parse_args() -> TextIO:
parser = argparse.ArgumentParser(description='Ledger Co. marketplace processor')
parser.add_argument(
'filename', type=open,
help='Name of the transaction file containing LOAN, PAYMENT and BALANCE commands',
)
return parser.parse_args().filename
def process_lines(database: Database, lines: Iterable[str]) -> Iterator[str]:
for line in lines:
record_type, *fields = line.split()
match record_type:
case 'LOAN':
loan = LoanRecord.parse(*fields)
database.process_loan(loan)
case 'PAYMENT':
payment = PaymentRecord.parse(*fields)
database.process_payment(payment)
case 'BALANCE':
balance = BalanceRecord.parse(*fields)
yield database.describe_balance(balance)
case _:
raise ValueError(f'Invalid record type {record_type}')
def main() -> None:
setlocale(LC_ALL, '')
database = Database()
with parse_args() as f:
for balance_desc in process_lines(database=database, lines=f):
print(balance_desc)
if __name__ == "__main__":
main()
For this sample input:
LOAN MBI Dale 10000 5.5 3.9
PAYMENT MBI Dale 1270 5
BALANCE MBI Dale 12 | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, object-oriented, programming-challenge, finance
For this sample input:
LOAN MBI Dale 10000 5.5 3.9
PAYMENT MBI Dale 1270 5
BALANCE MBI Dale 12
The output is:
MBI Dale $3490.00 47
Further optimisation is possible by calculating segments between lump sum payments in one shot instead of iterating over every single payment period. | {
"domain": "codereview.stackexchange",
"id": 43700,
"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, object-oriented, programming-challenge, finance",
"url": null
} |
python, performance, recursion, numpy
Title: Optimising compatibility-conflict graph solution - python recursive routine
Question: Background
I'm implementing an algorithm which localises overlapping sound sources using the time-difference-of-arrivals across 3 sensors [1]. Compatible 'triples' (e.g. with only 2 common sensors) need to be joined up to make larger N sensor graphs. The compatible triples are found using a recursive routine (```combine_all``) until no new solutions are found.
The routine runs well when there are small # of triples, but I've empirically observed for every 10X increase in triple number, there's a ~10^5.5 increase in run-time (using linear regression) - which is problematic (meaning up to 12 hours of run-time on my actual data).
Reference
[1] Kreissig & Yang 2013, Fast and reliable TDOA assignment in multi-source reverberant environments, ICASSP 2013 paper link.
Code and initial profiling
The combine_all routine accepts the compatibility-conflict matrix describing the compatibility/conflict of all triple pairs. From the currently available triples - their in/compatibility to the current solution are checked and kept or eliminated. The compatible nodes are checked by get_Nvl, and incompatible nodes are checked by get_not_Nvl.
Initial profiling with iPython %lprun told me the get_Nvl and get_not_Nvl is where ~80% (40% and 40% each) is spent in combine_all - and I've tried my best to optimise the current code with no luck.
import numpy as np
from itertools import chain, product | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
python, performance, recursion, numpy
def combine_all(Acc, V, l, X):
'''
Parameters
----------
Acc : (N_triples,N_triples) np.array
The compatibility-conflict graph. Value of 1 means compatible node pair, -1 is incompatible, 0 is undefined.
V_t : set
V_tilda. The currently considered vertices (a sub-set of V, all vertices)
l : set
The solution consisting of the currently compatible vertices.
Returns
-------
solutions_l : list with sublists
A somewhat messy output - must be run through ```format_combineall``` to get
nice output.
'''
# determine N_v(l) and !N_v(l)
# !N_v(l) are the vertices incompatible with the current solution
N_vl = get_Nvl(Acc, V, l)
N_not_vl = get_NOT_Nvl(Acc, V, l)
solutions_l = []
if len(N_vl) == 0:
solutions_l.append(l)
else:
# remove conflicting neighbour
V = V.difference(N_not_vl)
# unvisited compatible neighbours
Nvl_wo_X = N_vl.difference(X)
for n in Nvl_wo_X:
Vx = V.difference(set([n]))
lx = l.union(set([n]))
solution = combine_all(Acc, Vx, lx, X)
if solution:
solutions_l.append(solution)
X = X.union(set([n]))
return solutions_l
def get_Nvl(Acc, V_t, l):
'''Checks for compatible vertices
Essentially, two for loops run across the
available triples (v in V_t) and the current solution set (u in l)
- to access the ```Acc[v,u]``` entries. If all ```Acc[v,u]``` values
are +1, then ```v``` is compatible with the current solution ```l```.
If any of the ```Acc[v,u]``` values is -1 then that ```v``` is not compatible anymore. | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
python, performance, recursion, numpy
Returns
-------
Nvl : set
Solution of vertices that are compatible to at least one other vertex
and not in conflict with any of the other vertices.
'''
Nvl = []
if len(l)>0:
for v in V_t:
for u in l:
if Acc[v,u]==1:
Nvl.append(v)
elif Acc[v,u]==-1:
if v in Nvl:
Nvl.pop(Nvl.index(v))
return set(Nvl)
else:
return V_t
def get_Nvl_fast(Acc, V_t, l):
'''See CombineAll for docs
'''
if len(l)>0:
all_uv = np.array(np.meshgrid(V_t, l)).T.reshape(-1,2)
def get_acc(X):
return Acc[X[0], X[1]]
Acc_values = np.apply_along_axis(get_acc, 1, all_uv)
rows_w_min1 = np.where(Acc_values<0)
v_vals_w_conflicts = np.unique(all_uv[rows_w_min1,0])
Nvl = np.setdiff1d(V_t, v_vals_w_conflicts)
return Nvl
else:
return V_t
def get_NOT_Nvl(Acc:np.array, V:set, l:set):
N_not_vl = []
if len(l)>0:
for v in V:
for u in l:
if Acc[v,u]==-1:
N_not_vl.append(v)
elif Acc[v,u]==1:
if v in N_not_vl:
N_not_vl.pop(N_not_vl.index(v))
else:
N_not_vl = []
return set(N_not_vl)
# ---- not performance related section -- formats output into easily readable
# form
def format_combineall(output):
semiflat = flatten_combine_all(output)
only_sets = []
for each in semiflat:
if isinstance(each, list):
for every in each:
if isinstance(every, set):
only_sets.append(every)
elif isinstance(each, set):
only_sets.append(each)
return only_sets | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
python, performance, recursion, numpy
def flatten_combine_all(entry):
if isinstance(entry, list):
if len(entry)==1:
return flatten_combine_all(entry[0])
else:
return list(map(flatten_combine_all, entry))
elif isinstance(entry, set):
return entry
else:
raise ValueError(f'{entry} can only be set or list')
if __name__ == '__main__':
# compatibility-conflict graph from [1]
A = np.array([[ 0, 1, 0, 0,-1,-1],
[ 1, 0, 1, 1, 0, 1],
[ 0, 1, 0,-1, 1, 0],
[ 0, 1,-1, 0,-1, 0],
[-1, 0, 1,-1, 0, 1],
[-1, 1, 0, 0, 1, 0]])
qq = combine_all(A, set(range(6)), set([]), set([]))
neat_output = format_combineall(qq)
# Expected answer:
# >>> print(neat_output)
# >>> [{0, 1, 2}, {0, 1, 3}, {1, 2, 4, 5}, {1, 3, 5}]
No luck with optimisation experiments
Since the get_Nvl + get_not_Nvl is where most of the time spent - I've focussed on performing optimisations there. To begin with I worked only get_Nvl (both Nvl functions have very similar structure.
In the current get_Nvl implementation - there are two for loops, with i,j referencing values in the Acc compatibility-conflict matrix. I've tried multiple things that have lead to no improvement or even increase in runtime, of which here I report the two that I can now recollect.
Converting serial loop-in-loop (i,j) into a direct i,j product - that can be used to check the values of Acc in a map call.
converting the loop-in-loop into a numpy iterable form (np.apply_along_axis) (e.g. see get_Nvl_fast)
Converting the if,else flow into dictionary calls. (e.g. action_to_take[Acc[v,u]] instead of if Acc[v,u]==-1:...) | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
python, performance, recursion, numpy
Solutions to speeding up the code?
I've run out of ideas on how to speed up the code in Python - and am now considering using a C++ implementation that I can call from Python (though my C++ is non-existent/rusty).
I'd be grateful for ideas on how to speed up my Python code before investing too deep into another language!
Answer: Style & Maintenance
Prior to optimisation fussiness,
Use PEP484 type hints.
Docstrings are typically in double quotes rather than single quotes.
Do a PEP8 pass with a linter or good IDE; they will point out e.g. that you need spaces around ==.
You're so close to having a unit test! Write an assert.
Performance
Some of this will make a difference and some won't. It's good that you're profiling; keep doing that.
You've missed some opportunities for early return; pursue this, for example when you get_NOT_Nvl(Acc, V, l).
Rather than V = V.difference, just V -=.
Rather than set([n]), prefer {n}; but better yet don't do a set-to-set operation at all. Clone the set and then use .discard and .add as needed, since this is a single-element operation.
get_Nvl needs to operate on Nvl as a set instead of as a list cast to a set. I anticipate this helping, since Nvl.pop() and Nvl.index() are much more inefficient than a set discard. The same applies to get_NOT_Nvl.
More broadly, Python is bad at recursion. If you absolutely must have a recursive solution, as you fear: it is time to brush up on C++.
Suggested
import numpy as np
def combine_all(Acc: np.ndarray, V: set[int], l: set[int], X: set[int]) -> list[set[int]]:
"""
Parameters
----------
Acc : (N_triples,N_triples) np.array
The compatibility-conflict graph. Value of 1 means compatible node pair, -1 is incompatible, 0 is undefined.
V_t : set
V_tilda. The currently considered vertices (a sub-set of V, all vertices)
l : set
The solution consisting of the currently compatible vertices. | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
python, performance, recursion, numpy
Returns
-------
solutions_l : list with sublists
A somewhat messy output - must be run through ```format_combineall``` to get
nice output.
"""
# determine N_v(l) and !N_v(l)
# !N_v(l) are the vertices incompatible with the current solution
N_vl = get_Nvl(Acc, V, l)
if len(N_vl) == 0:
return [l]
solutions_l = []
# remove conflicting neighbour
V -= get_NOT_Nvl(Acc, V, l)
# unvisited compatible neighbours
N_vl -= X
X = set(X)
for n in N_vl:
Vx = set(V)
Vx.discard(n)
lx = set(l)
lx.add(n)
solution = combine_all(Acc, Vx, lx, X)
if solution:
solutions_l.append(solution)
X.add(n)
return solutions_l
def get_Nvl(Acc: np.ndarray, V_t: set[int], l: set[int]) -> set[int]:
"""Checks for compatible vertices
Essentially, two for loops run across the
available triples (v in V_t) and the current solution set (u in l)
- to access the ```Acc[v,u]``` entries. If all ```Acc[v,u]``` values
are +1, then ```v``` is compatible with the current solution ```l```.
If any of the ```Acc[v,u]``` values is -1 then that ```v``` is not compatible anymore.
Returns
-------
Nvl : set
Solution of vertices that are compatible to at least one other vertex
and not in conflict with any of the other vertices.
"""
if len(l) < 1:
return V_t
Nvl = set()
for v in V_t:
for u in l:
a = Acc[v, u]
if a == 1:
Nvl.add(v)
elif a == -1:
Nvl.discard(v)
return Nvl
def get_NOT_Nvl(Acc: np.array, V: set[int], l: set[int]) -> set[int]:
if len(l) < 1:
return set()
N_not_vl = set()
for v in V:
for u in l:
if Acc[v, u] == -1:
N_not_vl.add(v)
elif Acc[v, u] == 1:
N_not_vl.discard(v)
return N_not_vl | {
"domain": "codereview.stackexchange",
"id": 43701,
"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, recursion, numpy",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.