text stringlengths 1 2.12k | source dict |
|---|---|
java, performance, parsing, localization
Title: Finding an arbitrary word in a string of words given an offset
Question: Background
Given a string (s) and an offset into that string (offset), find the whole word that can be found at the given offset. (Helpful for auto-completing text.)
Code
Consider:
import static java.lang.Character.isSpaceChar;
public final class TestWordParsing {
public TestWordParsing() {
}
public void run() {
final String p = "Hello World!";
test( getWordAt( p, 0 ).equals( "Hello" ), 0 );
test( getWordAt( p, 3 ).equals( "Hello" ), 3 );
test( getWordAt( p, 5 ).equals( "Hello" ), 5 );
test( getWordAt( p, 6 ).equals( "World!" ), 6 );
test( getWordAt( p, p.length() ).equals( "World!" ), p.length() );
// Should fail.
test( getWordAt( p, 0 ).equals( "World!" ), 0 );
}
/**
* Given an arbitrary offset into a string, this returns the word at that
* index. The inputs and outputs include:
*
* <ul>
* <li>surrounded by space: <code>hello | world!</code> ("");</li>
* <li>end of word: <code>hello| world!</code> ("hello");</li>
* <li>start of a word: <code>hello |world!</code> ("world!");</li>
* <li>within a word: <code>hello wo|rld!</code> ("world!");</li>
* <li>end of a paragraph: <code>hello world!|</code> ("world!");</li>
* <li>start of a paragraph: <code>|hello world!</code> ("hello!"); or</li>
* <li>after punctuation: <code>hello world!|</code> ("world!").</li>
* </ul>
*
* @param s The string to scan for a word.
* @param offset The offset within s to begin searching for the nearest word
* boundary, must not be out of bounds of s.
*
* @return The word in s at the offset.
*
* @see getWordBegan( String, int )
* @see getWordEnded( String, int )
*/
public String getWordAt( final String s, final int offset ) {
final int posBegan = getWordBegan( s, offset );
final int posEnded = getWordEnded( s, offset );
return s.substring( posBegan, posEnded );
} | {
"domain": "codereview.stackexchange",
"id": 44042,
"lm_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, performance, parsing, localization",
"url": null
} |
java, performance, parsing, localization
return s.substring( posBegan, posEnded );
}
/**
* Returns the index into s where a word begins.
*
* @param s A non-null String.
* @param offset Index into s to begin searching backwards for a word.
*
* @return The index where a word begins.
*/
public int getWordBegan( final String s, int offset ) {
while( offset > 0 && isWordCharacter( s.charAt( offset - 1 ) ) ) {
offset--;
}
return offset;
}
/**
* Returns the index into s where a word ends.
*
* @param s A non-null String.
* @param offset Index into s to begin searching forwards for a word.
*
* @return The index where a word ends.
*/
public int getWordEnded( final String s, int offset ) {
final int length = s.length();
while( offset < length && isWordCharacter( s.charAt( offset ) ) ) {
offset++;
}
return offset;
}
/**
* Returns true if the given character can be reasonably expected to be part
* of a word, including punctuation marks.
*
* @param c The character to compare.
*
* @return false The character is a space character.
*/
private boolean isWordCharacter( char c ) {
return !isSpaceChar( c );
}
/**
* Poor man's unit testing.
*
* @param result Whether the test passed.
* @param index Index into the paragraph that was tested.
*/
private void test( boolean result, final int index ) {
System.out.printf( "%s: %d\n", result ? "Passed" : "Failed", index );
}
public static void main( final String args[] ) {
(new TestWordParsing()).run();
}
}
Expected Output
The code produces (as expected):
Passed: 0
Passed: 3
Passed: 5
Passed: 6
Passed: 12
Failed: 0
Additional Information | {
"domain": "codereview.stackexchange",
"id": 44042,
"lm_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, performance, parsing, localization",
"url": null
} |
java, performance, parsing, localization
Additional Information
The phrase Hello--K&R--World! is three distinct words, which should return Hello, K&R, or World!, depending on the initial offset. However, that condition wasn't stated originally.
The index for the start of the word within the string is required because the word will be replaced with different text.
Question
How can the code be improved?
Eliminate duplication between getWordBegan and getWordEnded?
Considerations for internationalization?
Optimizations?
Safeguards around invalid indexes?
Readability of comments (e.g., preconditions, postconditions)?
Answer: pros
you have automated tests with your code.
you use proper naming
you respect single abstraction layer principle
you provided a SSCCE
Cons
you use rather hard to read constructions (isWordCharacter( s.charAt( offset - 1 ) ) is not too bad but could be improved...)
chose better names for your identifiers, there is no need for single character names.
Eliminate duplication between getWordBegan and getWordEnded?
One solution could be to use regular expressions in a creative way:
public int getWordStarted(final String s, int offset) {
Matcher matcher = findBorder("\\w+$", s.substring(0, offset));
return matcher.start();
}
public int getWordEnded(final String s, int offset) {
Matcher matcher = findBorder("^\\w+", s.substring(offset));
return offset+matcher.end();
}
private Matcher findBorder(String wordBorderPattern, String substring) {
Pattern startOfWord = Pattern.compile(wordBorderPattern);
Matcher matcher = startOfWord.matcher(substring);
// when position is not inside a word 'matcher.find()' returns false!
matcher.find();
return matcher;
} | {
"domain": "codereview.stackexchange",
"id": 44042,
"lm_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, performance, parsing, localization",
"url": null
} |
java, performance, parsing, localization
here is an alternative solution without the need of finding start/end index separately. This implementation fails your test test(getWordAt(p, p.length()).equals("World!"), p.length()); but IMHO this is correct since index p.length() is indeed outside the string...:
public String getWordAt(final String s, final int offset) {
checkRange(s, offset);
Matcher wordMatcher = findWordAtIndex(s, offset);
checkOffsetPointedToWord(offset, wordMatcher);
return wordMatcher.group();
}
private void checkOffsetPointedToWord(final int offset, Matcher wordMatcher) {
if (wordMatcher.start() > offset) {
throw new IllegalArgumentException(offset + " does not point to a word!");
}
}
private Matcher findWordAtIndex(final String s, final int offset) {
Pattern wordPatern = Pattern.compile("\\w+", Pattern.CASE_INSENSITIVE);
Matcher wordMatcher = wordPatern.matcher(s);
while (wordMatcher.find() && wordMatcher.end() < offset) {
; // just loop
// we could also write the semicolon at the end of the while
// without the '{}' block but I'd rather show this NOOP
// explicitly.
}
return wordMatcher;
}
private void checkRange(final String s, final int offset) {
// we need to check the range explicitly because the loop
// will not throw an exception.
if (0 > offset || s.length() <= offset) {
throw new IllegalArgumentException(offset + " is outside String");
}
} | {
"domain": "codereview.stackexchange",
"id": 44042,
"lm_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, performance, parsing, localization",
"url": null
} |
java, performance, parsing, localization
Considerations for internationalization?
the char datatype is UTF-16.
Any charset conversions must be done when converting the input into a Java String object.
Optimizations?
Never optimize for performance unless you have a prove, that a particular piece of code is a performance problem!
Safeguards around invalid indexes?
Invalid indexes throw exceptions. Catch them and convert them into user friendly error messages. Range checks clutter the code and hide the important implementation details.
Someone may argue that this is flow control which should not be done with exceptions. But IMHO this this is a corner case where I tend to use Exceptions rather than a bunch of if/else cascades at the top of the methods...
Readability of comments (e.g., preconditions, postconditions)?
for my taste this are to much comments for this little code.
I'd be OK with this comments if they where at interface methods. There we need good comments to help the future implementer to understand the contract behind the method.
But on implementations themselves I'd rather see no comments at all.
There comments should explain why the code is the way it is, not what it does. So in your comments I'd only keep the assumption, that the parameters must not be null. | {
"domain": "codereview.stackexchange",
"id": 44042,
"lm_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, performance, parsing, localization",
"url": null
} |
python, python-3.x, comparative-review
Title: Comparison of two ways of looping in Python
Question: I wrote a small script to demonstrate two ways of looping in Python: with and without using the index. I want to know which way is better. Please see the example:
####################################################################################################
# Imagine there is some registration info of some people and their nationalities
# Stored in a Python dictionary
people_nationality_info = {'person_1': 'UK',
'person_2': 'Iceland',
'person_3': 'France',
'person_4': 'Spain',
'person_5': 'Norway',
'person_6': 'Sweden',
'person_7': 'Denmark',
'person_8': 'Germany'}
# Now some people are present at a meeting
# and also there is a new person "person_x" who is not currently registered
people_at_the_meeting = ['person_3','person_5','person_6','person_x']
# Now check the nationality of each person at the meeting
# method 1:
for i in range(len(people_at_the_meeting)):
if people_at_the_meeting[i] in people_nationality_info:
j = list(people_nationality_info.keys()).index(people_at_the_meeting[i])
print(people_at_the_meeting[i],list(people_nationality_info.values())[j],sep=" : ")
else:
people_nationality_info[people_at_the_meeting[i]] = input("Where are you from?")
# method 2:
for person in people_at_the_meeting:
if person in people_nationality_info:
print(person,people_nationality_info[person],sep=" : ")
else:
people_nationality_info[person] = input("Where are you from?") | {
"domain": "codereview.stackexchange",
"id": 44043,
"lm_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, comparative-review",
"url": null
} |
python, python-3.x, comparative-review
When I was given this task, I wrote method 1 straight away. But some time later I realized it can be done using method 2.
I wrote both methods. Both ways work, but I would like to know which is better, more Pythonic, closer to Python's best practices?
My first programming language is R, and due to the way I was trained, my intuition is always to use index.
Answer: For loops...
...if you only need the elements:
for element in collection:
...
...if you need the elements and their indices:
for idx, element in enumerate(collection):
...
...if you only need the indices (do you? that's rare):
for idx in range(len(collection)):
...
Your case is the first since you never use the index for any purpose other than accessing the element of the collection you're iterating over. | {
"domain": "codereview.stackexchange",
"id": 44043,
"lm_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, comparative-review",
"url": null
} |
java, simulation
Title: Simulating a toilet seat usage in Java
Question: (See also the next iteration.)
I have this small simulation program simulating a toilet seat. The toilet seat may be in two positions: up or down. If a male arrives to the toilet to urinate, and notices that it is down, he must put it upwards. What we are measuring, are two strategies:
Each visitor leaves the seat in the same position as they used it.
Each visitor puts the seat down.
My code follows:
package com.github.coderodde.simulation.toiletseat;
import java.util.Objects;
import java.util.Random;
public final class ToiletSeatSimulator {
private static final int MINIMUM_QUEUE_LENGTH = 1;
private static enum Gender {
FEMALE,
MALE,
}
private static enum Operation {
URINATE,
POOP,
}
private static enum ToiletSeatPosition {
UP,
DOWN,
}
private final int queueLength;
private final double femailProportion;
private final double urinationProportion;
private final boolean closeDown;
private final Random random;
private ToiletSeatPosition toiletSeatPosition;
private int seatsMoved = 0;
public ToiletSeatSimulator(int queueLength,
double femaileProportion,
double urinationProportion,
boolean closeDown,
Random random) {
this.queueLength = checkQueueLength(queueLength);
this.femailProportion = checkFemaleProportion(femaileProportion);
this.urinationProportion =
checkUrinationProportion(urinationProportion);
this.closeDown = closeDown;
this.random = Objects.requireNonNull(random, "The Random is null.");
this.toiletSeatPosition = ToiletSeatPosition.DOWN;
} | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
public int simulate() {
for (int i = 0; i < queueLength; i++) {
performOperation(getRandomGender(),
getRandomOperation());
}
return seatsMoved;
}
private void performOperation(Gender gender, Operation operation) {
switch (operation) {
case URINATE:
performUrination(gender);
break;
case POOP:
performPoop(gender);
break;
default:
throw new IllegalStateException(
"Unkwnown Gender enum: " + gender);
}
if (closeDown && toiletSeatPosition == ToiletSeatPosition.UP) {
toiletSeatPosition = ToiletSeatPosition.DOWN;
seatsMoved++;
}
}
private void performUrination(Gender gender) {
switch (gender) {
case FEMALE:
performFemaleUrination();
break;
case MALE:
performMaleUrination();
break;
default:
throw new IllegalStateException(
"Unknown Gender enum: " + gender);
}
}
private void performFemaleUrination() {
if (toiletSeatPosition == ToiletSeatPosition.UP) {
toiletSeatPosition = ToiletSeatPosition.DOWN;
seatsMoved++;
}
}
private void performMaleUrination() {
if (toiletSeatPosition == ToiletSeatPosition.DOWN) {
toiletSeatPosition = ToiletSeatPosition.UP;
seatsMoved++;
}
}
private void performPoop(Gender gender) {
switch (gender) {
case FEMALE:
performFemalePoop();
break;
case MALE:
performMalePoop();
break; | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
case MALE:
performMalePoop();
break;
default:
throw new IllegalStateException(
"Unknown Gender enum: " + gender);
}
}
private void performFemalePoop() {
if (toiletSeatPosition == ToiletSeatPosition.UP) {
toiletSeatPosition = ToiletSeatPosition.DOWN;
seatsMoved++;
}
}
private void performMalePoop() {
if (toiletSeatPosition == ToiletSeatPosition.UP) {
toiletSeatPosition = ToiletSeatPosition.DOWN;
seatsMoved++;
}
}
private Gender getRandomGender() {
double coin = random.nextDouble(); // In the range [0, 1).
return coin < femailProportion ? Gender.FEMALE : Gender.MALE;
}
private Operation getRandomOperation() {
double coin = random.nextDouble();
return coin < urinationProportion ? Operation.URINATE : Operation.POOP;
}
private static int checkQueueLength(int queueLength) {
if (queueLength < MINIMUM_QUEUE_LENGTH) {
throw new IllegalArgumentException(
"Queue length is too small: "
+ queueLength
+ ". Must be at most "
+ MINIMUM_QUEUE_LENGTH
+ ".");
}
return queueLength;
}
private static double checkFemaleProportion(double femaleProportion) {
if (Double.isInfinite(femaleProportion)) {
throw new IllegalArgumentException(
"Female proportion is infinite in absolute value: "
+ femaleProportion);
}
if (Double.isNaN(femaleProportion)) {
throw new IllegalArgumentException("Female proportion is NaN.");
} | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
if (femaleProportion < 0.0 || femaleProportion > 1.0) {
throw new IllegalArgumentException(
"Female proportion is out of bounds: "
+ femaleProportion
+ ". Must be within closed range [0,1].");
}
return femaleProportion;
}
private static double checkUrinationProportion(double urinationProportion) {
if (Double.isInfinite(urinationProportion)) {
throw new IllegalArgumentException(
"Urination proportion is infinite in absolute value: "
+ urinationProportion);
}
if (Double.isNaN(urinationProportion)) {
throw new IllegalArgumentException("Urination proportion is NaN.");
}
if (urinationProportion < 0.0 || urinationProportion > 1.0) {
throw new IllegalArgumentException(
"Urination proportion is out of bounds: "
+ urinationProportion
+ ". Must be within closed range [0,1].");
}
return urinationProportion;
}
}
The demo follows:
package com.github.coderodde.simulation.toiletseat;
import java.util.Random;
public final class Demo {
private static final int QUEUE_LENGTH = 1000;
private static final double FEMALE_PROPORTION = 0.55;
private static final double URINATION_PROPORTION = 0.2;
public static void main(String[] args) {
long seed = System.currentTimeMillis();
System.out.println("<<< Seed = " + seed + ">>>");
Random random1 = new Random(seed);
Random random2 = new Random(seed);
ToiletSeatSimulator simulator1 =
new ToiletSeatSimulator(
QUEUE_LENGTH,
FEMALE_PROPORTION,
URINATION_PROPORTION,
false,
random1); | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
System.out.println(
"Number of seat moves when changing seat position "
+ "on demand: "
+ simulator1.simulate());
ToiletSeatSimulator simulator2 =
new ToiletSeatSimulator(
QUEUE_LENGTH,
FEMALE_PROPORTION,
URINATION_PROPORTION,
true,
random2);
System.out.println(
"Number of seat moves when changing seat position back to "
+ "closed: "
+ simulator2.simulate());
}
}
The typical output is:
<<< Seed = 1666884294029>>>
Number of seat moves when changing seat position on demand: 146
Number of seat moves when changing seat position back to closed: 162
Critique request
As always, I would like to hear any comments. Especially, I doubt the correctness of my implementation, since the above figures are rather optimistic to me. | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
Answer: Normally I encourage people to write more functions rather than fewer, but in this case I think it needs to come back the other way.
I would change a few of the variable names, but then we all have our own style and preferences. For instance, the overall context of "Toilet" can be given once in the name of the class and then we know what sort of seat it is and can just use Seat rather than ToiletSeat.
If you just specify the range that is valid for the doubles, you don't need to check for infinites and NaN, as those aren't in the range!
You can leave out the default branch of the switches - that way the compiler can alert you if you update the instances of the enum and forget to specify how they get handled in the switch.
GENERALLY speaking, when I use switch, I like to just state what we're going to do in the case, and then return. I find it simpler to not have to worry about code that might run after or setting state that gets checked later in the same method (increase cyclomatic complexity). Sometimes that means duplicating some code and that's okay.
You should set the starting seat position and movement count at the start of simulate so it isn't affected by previous runs.
We only need the total number of iterations in the simulate method, so we can take it as an argument there.
I think it's fine NOT to introduce more object oriented / polymorphic stuff, as it's just not needed here and not likely (?) to be needed in the future.
import java.util.Objects;
import java.util.Random;
public final class ToiletSeatSim {
private final double femaleRatio;
private final double peeRatio;
private final boolean alwaysLeaveSeatDown;
private final Random random;
private SeatPosition seatPosition;
private int movements = 0; | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
private SeatPosition seatPosition;
private int movements = 0;
public ToiletSeatSim(Random random, double femaleRatio,
double peeRatio, boolean alwaysLeaveSeatDown) {
if (femaleRatio < 0.0 || femaleRatio > 1.0) {
throw new IllegalArgumentException("Female ratio is out of bounds: "
+ femaleRatio + ". Must be within closed range [0,1].");
}
if (peeRatio < 0.0 || peeRatio > 1.0) {
throw new IllegalArgumentException("Pee ratio is out of bounds: " + peeRatio
+ ". Must be within closed range [0,1].");
}
this.random = Objects.requireNonNull(random, "The Random is null.");
this.femaleRatio = femaleRatio;
this.peeRatio = peeRatio;
this.alwaysLeaveSeatDown = alwaysLeaveSeatDown;
}
public int simulate(int iterations) {
seatPosition = SeatPosition.DOWN;
movements = 0;
for (int i = 0; i < iterations; i++) {
Gender gender = getRandomGender();
Operation operation = getRandomOperation();
performOperation(operation, gender);
}
return movements;
}
private static enum SeatPosition {
UP,
DOWN,
}
private void setSeatPosition(SeatPosition position) {
if (this.seatPosition == position) {
return;
}
this.seatPosition = position;
movements++;
}
private static enum Gender {
FEMALE,
MALE,
}
private Gender getRandomGender() {
return random.nextDouble() < femaleRatio ? Gender.FEMALE : Gender.MALE;
} | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
java, simulation
private static enum Operation {
PEE,
POOP,
}
private void performOperation(Operation operation, Gender gender) {
switch (operation) {
case POOP:
setSeatPosition(SeatPosition.DOWN);
return;
case PEE:
switch (gender) {
case FEMALE:
setSeatPosition(SeatPosition.DOWN);
return;
case MALE:
setSeatPosition(SeatPosition.UP);
if (alwaysLeaveSeatDown) {
setSeatPosition(SeatPosition.DOWN);
}
return;
}
}
}
private Operation getRandomOperation() {
return random.nextDouble() < peeRatio ? Operation.PEE : Operation.POOP;
}
} | {
"domain": "codereview.stackexchange",
"id": 44044,
"lm_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, simulation",
"url": null
} |
python, validation, email
Title: Function to validate that an email address meets some requirements
Question: I want to create a function that checks if an email has a username that is 5 to 20 characters long, starts with an alphabet letter and ends with one domain names of (.org, .net, .org). It also corrects, if the user enters a capital letter. I am fully aware of that the code does not make sense as employing regular expressions is the best way, but this is just an exercises for me to built better codes in python. So I was wondering, which would the best way if a code needs to check multiple things and eventually returns True/False (like in this example).
def is_valid_email(raw_email):
email = raw_email.lower()
try:
name, domain_name = email.split('@')
except ValueError:
return False
else:
name_check = all([len(name) < 20, len(name) > 5, name[0].isalpha()])
domains = (".com", ".net", ".org")
domain_check = any([domain_name.endswith(domain)
for domain in domains])
return name_check and domain_check
print(is_valid_email('username@domain.org'))
Answer: You can make it easier to read by transforming the logic into a series of early returns:
TOP_LEVEL_DOMAINS = ("com", "net", "org")
def is_valid_email(email):
if '@' not in email:
return False
name, domain_name = email.split('@', 1)
if '.' not in domain_name:
return False
if domain_name.split('.')[-1] not in TOP_LEVEL_DOMAINS:
return False
if len(name) < 5 or len(name) > 20:
return False
if not name[0].isalpha():
return False
return True | {
"domain": "codereview.stackexchange",
"id": 44045,
"lm_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, validation, email",
"url": null
} |
python, validation, email
if not name[0].isalpha():
return False
return True
There is another advantege: since we process each check separately, you can wrap the result into a Result class and send the reason for why the email is invalid instead of plain False.
Don't use all() when you can just do ... and ... and .... To rephrase the same: don't create collections for no reason.
Don't use exceptions for handling normal flow, they are not designed for it. Also it's much slower (if you call this function very often).
Note that real email addresses can contain non-latin letters, be case-sensitive and up to 256 symbols long. | {
"domain": "codereview.stackexchange",
"id": 44045,
"lm_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, validation, email",
"url": null
} |
java, random
Title: Rolling my own PRNG in Java
Question: I have this pseudorandom number generator:
package com.github.coderodde.util;
public class Random {
private static final long MASK = 0xba42_87df_9103_cd55L;
private static final long LARGE_PRIME = 2396568697254547L;
private static final int TURN_OFF_INT_SIGN_BIT = 0x7fff_ffff;
private long counter;
private final long seed;
public Random(long seed) {
this.seed = seed;
}
public Random() {
this(System.nanoTime());
}
public int nextInt() {
return ((int)((seed + (counter += LARGE_PRIME)) ^ MASK))
& TURN_OFF_INT_SIGN_BIT;
}
public int nextInt(int bound) {
checkBound(bound);
return nextInt() % bound;
}
private static void checkBound(int bound) {
if (bound < 1) {
throw new IllegalArgumentException(
"Bad bound: " + bound + ". Must be positive.");
}
}
}
And the demo program is:
package com.github.coderodde.util;
public class Demo {
public static void main(String[] args) {
Random random = new Random(1L);
for (int i = 0; i < 20; i++) {
System.out.println(random.nextInt(1000));
}
}
}
Typical output
977
282
95
928
493
782
715
828
697
218
687
896
341
86
651
284
873
50
423
472
Critique request
As always, I would like to hear anything that comes to mind.
Answer: This PRNG has some unfortunate characteristics.
The easiest to spot is that the least significant bit of the counter has a period of 2. It will only ever alternate between even and odd. Adding the seed and XOR-ing by MASK does not change anything about that, and for an even bound that property leaks out into the result. | {
"domain": "codereview.stackexchange",
"id": 44046,
"lm_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, random",
"url": null
} |
java, random
Given a M of the form (1 << k) - 1, both (a + b) & M == (a & M) + (b & M) & M and (a ^ b) & MA == (a & M) ^ (b & M), which means that the bitwise AND with TURN_OFF_INT_SIGN_BIT could be moved inside the expression, and then it becomes clear that this is really a 31-bit PRNG. counter and seed and MASK and LARGE_PRIME could be int, and the PRNG would work exactly the same. By the way LARGE_PRIME & TURN_OFF_INT_SIGN_BIT (and this is the quantity that matters, not LARGE_PRIME itself) is no longer a prime, but I'm also not convinced that it needs to be a prime.
Basically this PRNG comes down to doing this, this changes the values that counter goes through but it shouldn't change the actual results (I didn't verify that):
public int nextInt() {
return (((counter++ * 568406675) + seed) ^ 0x9103_cd55) & 0x7fff_ffff;
}
The XOR doesn't fundamentally change anything (it flips some bits in a completely static way, if we wear "XOR goggles" with the same constant then its influence disappears entirely), so let's ignore it. The part that is supposed to be random, is the bottom 31 bits of counter++ * 568406675. Now admittedly, taking a simple counter and "mixing it up" is a legitimate strategy for implementing a PRNG (as long as there is enough mixing), and multiplication by a well-chosen constant is a good piece of the puzzle, and 568406675 is not even a bad choice (well, a fortunate accident, not really a choice). But just one step of mixing is not much. Subsequent results are highly correlated, and the mixing only goes from the least significant bit up, the upper bits are never mixed into the lower bits. That gives the lower bits very short periods (like an LCG, which this PRNG is also similar to, but with the multiplier set to 1 - which is not good). | {
"domain": "codereview.stackexchange",
"id": 44046,
"lm_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, random",
"url": null
} |
java, random
The overload int nextInt(int bound) uses the classic biased range reduction, which can be noticeable for large values of bound. This range reduction is also especially weak when bound is a low power of two, resulting in an output sequence with a very short period. | {
"domain": "codereview.stackexchange",
"id": 44046,
"lm_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, random",
"url": null
} |
python, beginner
Title: Print a range with selected numbers omitted
Question: I need to print those numbers in console:
0
1
2
3
-
5
6
7
8
-
10
11
12
13
-
15
16
17
18
As you can see I am not printing 4, 9, 14.
So I coded this:
top = 18
counter = 0
print("Using option 1")
for i in range(top -2):
print(counter)
if counter == 3 or counter == 8 or counter == 13:
counter = counter + 2
else:
counter = counter + 1
print("Using option 2")
i = -1
while i < top:
if i == 3 or i == 8 or i == 13:
i = i + 2
print(i)
else:
i = i +1
print(i)
The output of the above code is:
Using option 1
0
1
2
3
5
6
7
8
10
11
12
13
15
16
17
18
Using option 2
0
1
2
3
5
6
7
8
10
11
12
13
15
16
17
18
As you can see my code is working well.
In option1 I used a for loop.
And in option2 I used a while loop.
So I would like to know if there is a way to make some of that option more dynamic just by using the top value, or improve the algorithm.
Answer:
Save your non-printed into single set exceptions = (4, 9, 14), that way you can test it nicely as index in exceptions or index not in exceptions for negative.
Rather than trying to fiddle and increment your counter value yourself, just use range index and print only if you want it to print:
Example:
top = 20
exceptions = set((4, 9, 14,))
for index in range(top):
if index not in exceptions:
print(index)
If you were to go more in functional way (I recommend that), you can use filter function:
top = 20
exceptions = set((4, 9, 14,))
for index in filter(lambda i: i not in exceptions, range(top)):
print(index)
Edit:
Changed exceptions from tuple to set as suggested in a comment. | {
"domain": "codereview.stackexchange",
"id": 44047,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
c++, computational-geometry
Title: Function to find the closest points between two line segements | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
Question: The following function is supposed to return the points p1 on line segment a, and p2 line segment b, such that |p1 - p2| is minimized.
point_pair get_closest_points(line_segment const& a, line_segment const& b)
{
auto const intersect = intersection(extension(a), extension(b));
if(line_segment::valid(intersect.a))
{
if(line_segment::valid(intersect.b))
{
auto const loc_a = point_at(a, intersect.a);
auto const loc_b = point_at(b, intersect.b);
return point_pair{loc_a, loc_b};
}
else
{
auto const loc_b = point_at(extension(b), line_segment::clamp(intersect.b));
auto const proj = project(extension(a), loc_b);
auto const loc_a = point_at(extension(a), proj);
return point_pair{loc_a, loc_b};
}
}
else
{
if(line_segment::valid(intersect.b))
{
auto const loc_a = point_at(extension(a), line_segment::clamp(intersect.a));
auto const proj = project(extension(b), loc_a);
auto const loc_b = point_at(extension(b), proj);
return point_pair{loc_a, loc_b};
}
else
{
auto const loc_a = point_at(extension(a), line_segment::clamp(intersect.a));
auto const proj_a_on_b = project(extension(b), loc_a);
if(line_segment::valid(proj_a_on_b))
{
return point_pair{loc_a, point_at(extension(b), proj_a_on_b)};
}
else
{
auto const loc_b = point_at(extension(b), line_segment::clamp(intersect.b));
auto const proj_b_on_a = project(extension(a), loc_b);
if(line_segment::valid(proj_b_on_a))
{
return point_pair{point_at(extension(a), proj_b_on_a), loc_b};
}
else
{
return point_pair{loc_a, loc_b}; | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
else
{
return point_pair{loc_a, loc_b};
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
Helper functions used:
line extension(line_segment a) converts a line segment and extends it to a line
line_intersection intersection(line a, line b), computes the parameters of a and b that corresponds to the closest points on the lines.
bool line_segment::valid(line_parameter t), checks that t is a valid parameter for a line_segment (should be between 0 and 1)
point point_at(line a, line_parameter t) returns the point on a that corresponds to t
line_parameter line_segment::clamp(line_parameter t) clamps t to the valid range
line_parameter project(line l, point p) projects p on l
From my testing, the function appears to work. Questions:
Is there some case that is not handled properly? As a precondition, a and b are assumed be non-parallel and to have non-zero length.
Can I get rid of some branches?
Answer: You should've written a pseudo code explaining what the algo does and why it works. That would've helped reviewers to understand your code easier and also perhaps you would've been able to find out that the algorithm doesn't provide the right answer in some cases. Sometimes it will give a pair that isn't minimal or even one of the points might not belong to its' segment. The following cases are not handled correctly:
In the branch where intersect.a is valid and intersect.b is not valid, your loc_a taken as a projection of a point from b to extension(a) - it doesn't necessarily fall into a. An example of this scenario is segment_a = {(-1,0),(1,0)} segment_b = {(100,100), (101,101)} | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
In case both intersect.a and intersect.b are not valid, and projections of loc_a and loc_b onto the other extending lines do not fall into their respective segments - then it is not necessary that {loc_a,loc_b} is the optimal pair. It might be the case that you need to switch loc_a or loc_b for the other endvertex of their respective segment. An example of this scenario is segment_a = {(1,0),(2,0)} segment_b = {(100,100), (101,101)}: {(2,0), (100, 100)} is optimal but the algorith returns {(1,0),(100,100)}.
Let me write an example of algorithm that is both much clearer and has no if/else branching depth.
// finds the closest point to b on the segment a
point get_closet_point(line_segment const& a, point const& b);
// computes distance between the two points
double distance(point_pair const& a);
point_pair get_closest_points(line_segment const& a, line_segment const& b)
{
auto const intersect = intersection(extension(a), extension(b));
if(line_segment::valid(intersect.a) && line_segment::valid(intersect.b))
{
auto const loc_a = point_at(a, intersect.a);
auto const loc_b = point_at(b, intersect.b);
return point_pair{loc_a, loc_b};
}
std::optional<point_pair> candidate_a, candidate_b;
if(!line_segment::valid(intersect.a))
{
auto const loc_a = point_at(extension(a), line_segment::clamp(intersect.a));
auto const loc_b = get_closet_point(b, loc_a );
candidate_a = {loc_a, loc_b};
}
if(!line_segment::valid(intersect.b))
{
auto const loc_b = point_at(extension(b), line_segment::clamp(intersect.b));
auto const loc_a = get_closet_point(a, loc_b );
candidate_b = {loc_a, loc_b};
} | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
if(candidate_a.has_value() && candidate_b.has_value())
{
if(distance(*candidate_a) < distance(*candidate_b))
{
return *candidate_a;
}
else
{
return *candidate_b;
}
}
if(candidate_a)
{
return *candidate_a;
}
else
{
return *candidate_b;
}
}
The idea of the algorithm is as follows: if the closest points between the extending lines belong to the segments then it is clearly the answer.
Otherwise, one needs to consider only the endvertices of the segments. For each of these 4 points, search for closest point in the other segment. We get 4 candidates of point pairs, now one just needs to check the 4 candidates and find the closest pair.
It happens that it is unnecessary to check all 4 candidates. It is sufficient to consider only the segment' endvertices that are the closest to the extending lines' closest points. In case the extending lines' closest point is inside the segment then there is no need to include its' envertices into candidates.
It is not exactly easy to prove that it works but it is doable. | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
c++, computational-geometry
For general writing. Hope the example is helpful for you to see how code can be simplified and flattened. A repetitive piece of code can be made into a function if can be given a clear name. Or into a local lambda/closure if it has no uses outside the function or cannot be given understandable name.
The function line_intersection intersection(line a, line b). The name is very misleading. It doesn't do what intersection is supposed to do.
Also, it accepts the extending lines but the output is usable for the segments. I find this behavior odd. Hypothetically, getting the extending lines can remove the information about its' original line segments. It's like you rely on behavior that isn't inherently promised.
Also, some people to do things this way, but I generally prefer member function over global free function as it is much easier to find and use them for associated classes. If you want to keep them free, it's better to put them into a namespace that clarifies to whom they belong and it will be much easier to search for them. | {
"domain": "codereview.stackexchange",
"id": 44048,
"lm_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++, computational-geometry",
"url": null
} |
java, simulation
Title: Simulating a toilet seat usage in Java - follow-up
Question: (See the previous iteration.)
This time, I removed the stuff I don't need in my demo runner. Also, I consolidated some code that seemed DRY to me.
Simulation rules
When a female arrives, she ensures that the seat is down before performing the urge. She leaves the seat down before exiting.
When a male arrives to pee, he makes sure the seat is up and pees. After peeing, if we require all the visitors to put down the seat, the male puts it down. Otherwise, the seat remains upwards.
When a male arrives to poo, the case 1 applies.
Here it goes:
package com.github.coderodde.simulation.toiletseat;
import java.util.Random;
public final class ToiletSeatSimulator {
private static enum Gender {
FEMALE,
MALE,
}
private static enum Operation {
PEE,
POOP,
}
private static enum SeatPosition {
UP,
DOWN,
}
private final int queueLength;
private final double femaleRatio;
private final double peeRatio;
private final boolean alwaysLeaveSeatDown;
private final Random random;
private SeatPosition seatPosition = SeatPosition.DOWN;
private int movements = 0;
public ToiletSeatSimulator(int queueLength,
double femaileProportion,
double urinationProportion,
boolean alwaysLeaveSeatDown,
Random random) {
this.queueLength = queueLength;
this.femaleRatio = femaileProportion;
this.peeRatio = urinationProportion;
this.alwaysLeaveSeatDown = alwaysLeaveSeatDown;
this.random = random;
}
public int simulate() {
for (int i = 0; i < queueLength; i++) {
performOperation(getRandomGender(),
getRandomOperation());
}
return movements;
} | {
"domain": "codereview.stackexchange",
"id": 44049,
"lm_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, simulation",
"url": null
} |
java, simulation
return movements;
}
private void performOperation(Gender gender, Operation operation) {
switch (operation) {
case POOP:
setSeatPosition(SeatPosition.DOWN);
return;
case PEE:
switch (gender) {
case FEMALE:
setSeatPosition(SeatPosition.DOWN);
return;
case MALE:
setSeatPosition(SeatPosition.UP);
if (alwaysLeaveSeatDown) {
setSeatPosition(SeatPosition.DOWN);
}
return;
}
}
}
private void setSeatPosition(SeatPosition seatPosition) {
if (this.seatPosition != seatPosition) {
this.seatPosition = seatPosition;
movements++;
}
}
private Gender getRandomGender() {
double coin = random.nextDouble(); // In the range [0, 1).
return coin < femaleRatio ? Gender.FEMALE : Gender.MALE;
}
private Operation getRandomOperation() {
double coin = random.nextDouble();
return coin < peeRatio ? Operation.PEE : Operation.POOP;
}
}
... and the demo driver is:
package com.github.coderodde.simulation.toiletseat;
import java.util.Random;
public final class Demo {
private static final int QUEUE_LENGTH = 1000;
private static final double FEMALE_RATIO = 0.55;
private static final double PEE_RATIO = 0.9;
public static void main(String[] args) {
long seed = System.currentTimeMillis();
System.out.println("<<< Seed = " + seed + " >>>");
Random random1 = new Random(seed);
Random random2 = new Random(seed); | {
"domain": "codereview.stackexchange",
"id": 44049,
"lm_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, simulation",
"url": null
} |
java, simulation
Random random1 = new Random(seed);
Random random2 = new Random(seed);
ToiletSeatSimulator simulator1 =
new ToiletSeatSimulator(
QUEUE_LENGTH,
FEMALE_RATIO,
PEE_RATIO,
false,
random1);
System.out.println(
"Number of seat moves when changing seat position "
+ "on demand: "
+ simulator1.simulate());
ToiletSeatSimulator simulator2 =
new ToiletSeatSimulator(
QUEUE_LENGTH,
FEMALE_RATIO,
PEE_RATIO,
true,
random2);
System.out.println(
"Number of seat moves when changing seat position back to "
+ "closed: "
+ simulator2.simulate());
}
}
Critique request
Now, what do you think? Did I improve anything?
Answer:
private void performOperation(Gender gender, Operation operation) {
switch (operation) {
case POOP:
setSeatPosition(SeatPosition.DOWN);
return;
case PEE:
switch (gender) {
case FEMALE:
setSeatPosition(SeatPosition.DOWN);
return;
case MALE:
setSeatPosition(SeatPosition.UP);
if (alwaysLeaveSeatDown) {
setSeatPosition(SeatPosition.DOWN);
}
return;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44049,
"lm_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, simulation",
"url": null
} |
java, simulation
return;
}
}
}
This could be written more briefly:
private void performOperation(PositionPreference preference, Operation operation) {
switch (preference) {
case STANDER:
if (operation == PEE) {
setSeatPosition(SeatPosition.UP);
if (leaveSeatAsUsed) {
return;
}
}
case SITTER:
setSeatPosition(SeatPosition.DOWN);
return;
}
}
or even more briefly without the switch (may also be more readable and maintainable)
private void performOperation(PositionPreference preference, Operation operation) {
if ((preference == STANDER) && (operation == PEE)) {
setSeatPosition(SeatPosition.UP);
if (leaveSeatAsUsed) {
return;
}
}
setSeatPosition(SeatPosition.DOWN);
}
Either has exactly the same behavior as the original but only uses two setSeatPosition calls rather than four. We now cover three situations with one case:
Person is a SITTER.
Person is performing a non-PEE operation.
Person is a STANDER who performed a PEE operation with leaveSeatAsUsed false.
Changing to leaveSeatAsUsed may be clearer about what the variable does. Also, this way, we only use the variable to prevent the default behavior. Otherwise, we can fall through to the next case.
We don't need Gender (actually the wrong term here; sex would be more relevant). A PositionPreference gives us all the relevant information without making any assumptions about gender or sex.
If the person is a SITTER, we don't care about the Operation. Such people always put the seat down.
Obviously, other names should change outside this block of code for consistency. | {
"domain": "codereview.stackexchange",
"id": 44049,
"lm_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, simulation",
"url": null
} |
c#
Title: Creating a Method Called ValidString to validate user inputs
Question: I am completely new to this coding thing and am completely lost. I've been asked
"Create a method called ValidString that will return true/false if the string that is passed in is not null and not empty. You should use the IsNullOrEmpty or the IsNullOrWhiteSpace methods of the string class to check if the string is empty."
Currently I have
public static bool ValidString(string value)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
else
{
return true;
}
}
I'm not sure if this is right or not as whenever I input anything that's a blank input it continues like nothing is wrong.
I apologize if this is something super simple, I'm completely inexperienced when it comes to coding and being on a deployment with trash internet doesn't help.
Answer: A string with a white space " " has a length of 1 and is therefore not empty. A string s is empty when it is not null and when s.Length == 0.
Your method is correct; however, you can simplify it:
public static bool ValidString(string value)
{
return !String.IsNullOrEmpty(value);
}
IsNullOrEmpty returns true when you want to return false and vice versa. Therefore you can invert the Boolean result with the NOT operator !.
Usage example:
string input;
while (true) {
input = GetUserInput();
if (ValidString(input)) {
break;
}
Console.WriteLine("Your input is not valid. Try again!");
}
Process(input); | {
"domain": "codereview.stackexchange",
"id": 44050,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
Title: Shader Program OpenGL
Question: I am new to OpenGL learning it on amazing website learnopengl.com
I wanted to a convenient way to use shader programs thats why I created this struct, please review it.
ShaderProgram.h
#ifndef HELLO_TRIANGLE_SHADERPROGRAM_H
#define HELLO_TRIANGLE_SHADERPROGRAM_H
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <string>
#include <variant>
struct ShaderProgram {
void loadFromFile(const char* vertexFile, const char* fragmentFile);
void loadFromSource(const char* vertexSource, const char* fragmentSource);
unsigned int getProgram() const;
bool isSuccess() const;
const std::string_view& getErrorMessage() const;
private:
std::variant<unsigned int, std::string_view> data;
};
#endif //HELLO_TRIANGLE_SHADERPROGRAM_H
ShaderProgram.cpp
#include "ShaderProgram.h"
void ShaderProgram::loadFromSource(const char *vertexSource, const char *fragmentSource)
{
unsigned int vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShaderId, 1, &vertexSource, nullptr);
glCompileShader(vertexShaderId);
int success;
char log[512];
glGetShaderiv(vertexShaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShaderId, 512, nullptr, log);
data = log;
return;
}
unsigned int fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShaderId, 1, &fragmentSource, nullptr);
glCompileShader(fragmentShaderId);
glGetShaderiv(fragmentShaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShaderId, 512, nullptr, log);
data = log;
return;
}
unsigned int program = glCreateProgram();
glAttachShader(program, vertexShaderId);
glAttachShader(program, fragmentShaderId);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success); | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(program, 512, nullptr, log);
data = log;
return;
}
data = program;
glDeleteShader(vertexShaderId);
glDeleteShader(fragmentShaderId);
}
void ShaderProgram::loadFromFile(const char *vertexFilePath, const char *fragmentFilePath)
{
try
{
std::ifstream vertexFile(vertexFilePath);
std::string vertexFileContent((std::istreambuf_iterator<char>(vertexFile)), std::istreambuf_iterator<char>());
std::ifstream fragmentFile(fragmentFilePath);
std::string fragmentFileContent((std::istreambuf_iterator<char>(fragmentFile)),
std::istreambuf_iterator<char>());
loadFromSource(vertexFileContent.c_str(), fragmentFileContent.c_str());
} catch (std::exception &e)
{
data = e.what();
}
}
unsigned int ShaderProgram::getProgram() const
{
return std::get<unsigned int>(data);
}
bool ShaderProgram::isSuccess() const
{
return std::holds_alternative<unsigned int>(data);
}
const std::string_view &ShaderProgram::getErrorMessage() const
{
return std::get<std::string_view>(data);
}
Please review this and advise is there a better way to this.
Thanks in advance.
UPDATE: Implementing suggestions mentioned in the answer, please review this aswell as development is a constant process. Thanks all in advance.
Shader.h
namespace shader_program
{
enum class ShaderType
{
VERTEX,
FRAGMENT
};
enum class SourceType
{
RAW,
FILE
};
struct Shader
{
Shader(const std::string_view &source, ShaderType shaderType, SourceType sourceType);
~Shader();
unsigned int getId() const;
private:
unsigned int shader = 0;
}; | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
unsigned int getId() const;
private:
unsigned int shader = 0;
};
struct ShaderProgram
{
ShaderProgram(const std::string_view &vertexSource, const std::string_view &fragmentSource,
SourceType vertexSourceType, SourceType fragmentSourceType);
~ShaderProgram();
void use() const;
private:
unsigned int program;
};
} // shader_program
Shader.cpp
shader_program::Shader::Shader(const std::string_view &source, shader_program::ShaderType shaderType,
shader_program::SourceType sourceType)
{
auto content = source.data(); // Assuming raw data
if (sourceType == SourceType::FILE)
{
std::ifstream ifs(source.data());
if (!ifs.good())
{
throw std::runtime_error("Invalid shader file");
}
content = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()).data();
if (!ifs.eof())
{
throw std::runtime_error("Invalid shader file");
}
}
shader = glCreateShader(shaderType == ShaderType::VERTEX ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
glShaderSource(shader, 1, &content, nullptr);
glCompileShader(shader);
int success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
int len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len == 0)
{
glDeleteShader(shader);
shader = 0;
throw std::runtime_error("Could not compile shader and could not obtain any log");
}
std::vector<char> log(len);
glGetShaderInfoLog(shader, log.size(), &len, log.data());
glDeleteShader(shader);
shader = 0;
throw std::runtime_error({log.begin(), log.end()});
}
} | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
}
shader_program::Shader::~Shader()
{
// No need to delete not created shader
if (shader != 0)
{
glDeleteShader(shader);
}
}
unsigned int shader_program::Shader::getId() const
{
return shader;
}
shader_program::ShaderProgram::ShaderProgram(const std::string_view &vertexSource,
const std::string_view &fragmentSource,
shader_program::SourceType vertexSourceType,
shader_program::SourceType fragmentSourceType)
{
Shader vertexShader(vertexSource, ShaderType::VERTEX, vertexSourceType);
Shader fragmentShader(fragmentSource, ShaderType::FRAGMENT, fragmentSourceType);
program = glCreateProgram();
if (program == 0)
{
throw std::runtime_error("Could not create a shader program");
}
glAttachShader(program, vertexShader.getId());
int error = glGetError();
if (error != GL_NO_ERROR)
{
std::string errorStr = "Attaching vertex shader failed with code: " + std::to_string(error);
glDeleteProgram(program);
program = 0;
throw std::runtime_error(errorStr);
}
glAttachShader(program, fragmentShader.getId());
error = glGetError();
if (error != GL_NO_ERROR)
{
std::string errorStr = "Attaching fragment shader failed with code: " + std::to_string(error);
glDeleteProgram(program);
program = 0;
throw std::runtime_error(errorStr);
}
glLinkProgram(program);
int success;
glGetProgramiv(program, GL_LINK_STATUS, &success); | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
int success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
int len;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
if (len == 0)
{
glDeleteProgram(program);
program = 0;
throw std::runtime_error("Could not link program and could not obtain any log");
}
std::vector<char> log(len);
glGetProgramInfoLog(program, log.size(), &len, log.data());
glDeleteProgram(program);
program = 0;
throw std::runtime_error({log.begin(), log.end()});
}
}
shader_program::ShaderProgram::~ShaderProgram()
{
// No need to delete not created program
if (program != 0)
{
glDeleteProgram(program);
}
}
void shader_program::ShaderProgram::use() const
{
if (program == 0)
{
throw std::runtime_error("Cannot use not created program");
}
glUseProgram(program);
}
Thanks again. | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
Answer: Use of std::string_view
I see you are using std::string_view, but unfortunately in a completely incorrect way. A std::string_view is a non-owning view of a string. This means the string itself has to be stored somewhere else. When you call getShaderInfoLog(), the log message is stored into the local variable log[], and the std::string_view created from that will still point to the local variable. When loadFromSource() returns however, the variable log[] no longer exists, and the std::string_view points to memory which might no longer contain the string. The solution here is to make data contain a std::string instead of a std::string_view.
Where you should have used std::string_view instead is for the function parameters, like loadFromFile() and loadFromSource().
Error handling
I see you have thought about handling errors, but again it has not been done in a good way. You are using a try-catch block in loadFromFile(), but there is no guarantee that exceptions are thrown on all possible errors. For example, if you try to pass a non-existing filename, then that code will not throw any exception on Linux. At the very least, check that vertexFile.eof() == true after reading into vertexFileContent, and similar for fragmentFile.
Using a std::variant to store success or an error message is not the worst idea, but it has issues. Here it works because the two types are different, but what if the success type would be the same as the error type? C++23 will introduce std::expected, which is similar to a std::variant, but avoids the issue by making it very explicit what the success and error types are. | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
But even then, std::expected is meant to be used as a return type. By making loadFromFile return void, you are putting distance between performing an action and checking whether it succeeded. It would be much better if loadFromFile() would immediately return whether it was succesful or not, in such a way that the caller has to handle it immediately. So I would either have it return a std::expected (or a std::variant until we wait for C++23), or perhaps even better would be to throw an exception on error.
Also consider that almost everything can go wrong in a program. You did take into account that compiling and linking the shader source could go wrong, but you did not account for glGetShaderInfoLog() itself possibly returning an error. In that case, log[] might not have been written to. Consider zeroing the first character of log[] just to prevent a possible out-of-bounds read in this admittedly unlikely scenario.
Make the struct more useful
Your struct ShaderProgram implements the bare minimum for loading and compiling a shader program, and then getting the handle. But it could do much more: | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, error-handling, graphics, opengl, shaders
Turn loadFromFile() and loadFromSource() into constructors. This will save some lines of code for the caller.
Add a destructor, so the code using it doesn't have to call glDeleteProgram() manually.
Maybe add a use() member function that calls glUseProgram().
Consider that with the above, you could write:
{
ShaderProgram program(vertexSource, fragmentSource);
program.use();
while (true) {
// render frames
...
}
} | {
"domain": "codereview.stackexchange",
"id": 44051,
"lm_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++, error-handling, graphics, opengl, shaders",
"url": null
} |
c++, pointers
Title: Class that can only be created and deleter through smart pointer
Question: I would like to expose a nullable referance of a "mesh" object, so I am returning a const pointer. However, I explicitly want to prevent anyone handling this from deleting the object. The following is my solution.
Mesh class
class IMesh
{
public:
virtual ~IMesh() = 0; // pure abstract
protected:
IMesh() = default; // prevent creation outside of class
private:
void operator delete(void * p){::operator delete(p);} // prevent deletion outside of class
friend struct std::default_delete<IMesh>; // allow deletion by smart pointer
};
class Mesh : IMesh
{
public:
static std::unique_ptr<IMesh> Create()
{
std::unique_ptr<IMesh> px {new Mesh{}};
return px;
}
private:
Mesh() = default; // prevent creation outside of class
};
MeshLoader class can get intances of the Meshes
class MeshLoader
{
public:
explicit MeshLoader(gef::Platform& platform_);
Result LoadMeshScene(string const & filepath);
IMesh const * GetMesh(string const& name);
private:
gef::Platform& platform_;
gef::Scene model_scene_;
std::map<string, std::unique_ptr<IMesh>> meshes;
};
GetMesh() function
IMesh const * AnimationSystem::MeshLoader::GetMesh(string const & name)
{
const auto mesh = meshes.find(name);
if(mesh == meshes.end())
return nullptr;
return mesh->second.get();
}
Consumers can then call:
auto mesh = meshLoader.GetMesh("ID");
And use this mesh as they like.
However, attempring to call:
delete mesh;
Will produce the following compliation error
[C2248] 'IMesh::operator delete': cannot access private member declared in class 'IMesh'
Is this a good solution? Are there any dangers I'm missing? Is ::operator delete(p); going to delete my object as expected? | {
"domain": "codereview.stackexchange",
"id": 44052,
"lm_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++, pointers",
"url": null
} |
c++, pointers
Answer: It might be simpler to make your class a wrapper around the smart pointer, internally. (Although then you would need to re-invent the shared_ptr and weak_ptr if you need them.) The simplest implementation might be, using IMesh = std::unique_ptr<Mesh>;.
Because the destructor is private: and not protected:, subclasses cannot be deleted. If you fix this by letting all derived classes use the destructor, however, there is now an easy way to work around the restrictions, by deriving a subclass that adds a public: constructor and destructor. You might consider this an advantage or a disadvantage.
Another way this implementation is more restrictive than it should be, if what you want is to allow smart pointers and only smart pointers, is that this blocks STL smart pointers with custom deleters.
I suppose I would frame-challenge this. The language is not really designed to enforce the use of this type only through a smart pointer. There’s no particular advantage to doing so: you’ve already blocked people from creating a new Mesh on the heap, or a Mesh on the stack. Forcing programmers to create a std::vector<std::shared_ptr<IMesh>> instead of a std::vector<Mesh> whose memory is just as safely-managed as a smart pointer is pessimal. You’re blocking other legitimate patterns as well, such as smart pointers to structures containing a mesh.
It’s probably possible to work around these restrictions if the programmer needs to, but consider whether it would be better just to use smart pointers exclusively in your own API, and not try to have the compiler enforce this on every use of the class in client code. | {
"domain": "codereview.stackexchange",
"id": 44052,
"lm_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++, pointers",
"url": null
} |
c++, unit-testing
Title: N dimensional array index utility Improved
Question: This is a continuation from a previous question; I updated the code with the suggestions and added an additional iteration.
Templates are not an option because of the usage: The objects are stored as a class members where the sizes are not known at compile time
Iterators are not used, not even for scan_kernel because I could not find a way to introduce them; I'm still open to suggestions
Because of the new constructor I've had some trouble with the rule of 5, and I'm not sure about the duplication either, but there is a usecase where a new object needs to be constructed from another with a different padding so this is the best I could support it..
The biggest problem with this is I do not know how to test scan_kernel; Otherwise how could this be improved?
Thank you very much for the great suggestions so far!
header:
#include <cstdint>
#include <vector>
#include <optional>
#include <functional>
class NDArrayIndex{
public:
NDArrayIndex(
const std::vector<std::uint32_t>& dimensions, const std::vector<std::int32_t>& padding = {},
const std::vector<std::uint32_t>& position = {}
);
NDArrayIndex(const NDArrayIndex& other, const std::vector<std::int32_t>& padding = {});
/** @brief Sets the position to all zeroes
*
* @return Reference to the object
*/
NDArrayIndex& reset(){
return set(std::vector<std::uint32_t>(size(), 0));
}
/** @brief updates the position of the object based on the given argument
*
* @param[in] position The position to move the object to; Must be within bounds!
*
* @return Reference to the object
*/
NDArrayIndex& set(const std::vector<std::uint32_t>& position); | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @brief updates the position of the object based on the given arguments
*
* @param[in] dimension The dimension to set the position of; Must be within bounds!
* @param[in] position The position to move the object to; Must be within bounds!
*
* @return Reference to the object
*/
NDArrayIndex& set(std::uint32_t dimension, std::uint32_t position);
/** @brief updates the position of the object to go to the next position in the buffer range
*
* @return The index of the highest dimension the step modified
*/
std::uint32_t step();
/** @brief updates the position of the object to go to direction given in the arguments if the new position is inside bounds,
* throws an exception of the new position is not inside bounds
*
* @param[in] dimension The dimension to move the object on
* @param[in] delta The number of steps to move the objects position in the given dimension
*
* @return Reference to the object
*/
NDArrayIndex& step(std::uint32_t dimension, std::int32_t delta = 1);
const std::vector<std::uint32_t>& position() const{
return m_position;
}
/** @brief updates the position of the object based on the given argument
*
* @param[in] position The position to base the calculations on
*
* @return The value of the mapped index, if there is any
*/
std::optional<std::uint32_t> calculate_mapped_position(const std::vector<std::uint32_t>& position) const;
/** @brief Provides the index of the current position in the underlying buffer, if there is any
*
* @return the index pointing to the actual position, if it is mappable to the internal buffer
*/
std::optional<std::uint32_t> mapped_position() const{
return m_mappedIndex;
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @brief Tells if the given position is inside the indexing interval provided by the dimensions and padding of the object
*
* @param[in] position The position to base the calculations on
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_bounds(const std::vector<std::uint32_t>& position, std::uint32_t dimension = 0u, std::int32_t delta = 0) const;
/** @brief Tells if the stored position is inside the indexing interval provided by the dimensions and padding of the object
*
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_bounds(std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_bounds(m_position, dimension, delta);
}
/** @brief Tells if the given position is inside the indexing interval provided by the dimensions and padding of the object
*
* @param[in] index The index object supporting the position to base the check upon
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_bounds(const NDArrayIndex& index, std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_bounds(index.position(), dimension, delta);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @brief Tells if the given position is mappable to the buffer range determined by the dimensions and padding
*
* @param[in] position The position to base the calculations on
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_content(const std::vector<std::uint32_t>& position, std::uint32_t dimension = 0u, std::int32_t delta = 0) const;
/** @brief Tells if the stored position is mappable to the buffer range determined by the dimensions and padding
*
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_content(std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_content(m_position, dimension, delta);
}
/** @brief Tells if the given position is mappable to the buffer range determined by the dimensions and padding
*
* @param[in] index The index object supporting the position to base the check upon
* @param[in] dimension An optional dimension parameter to help shift the parameter
* @param[in] delta The number of steps to move the objects position temporarily in the given dimension for the relevant check
*
* @return true if the given position is inside bounds
*/
bool inside_content(const NDArrayIndex& index, std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_content(index.position(), dimension, delta);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @struct IntervalPart
* @brief Describes part of an interval excluding the direction it lies on
* @var position_start the absolute starting position of the interval relevan part
* @var steps_inside_target the size of the interval's relevant part
*/
struct IntervalPart{
std::uint32_t position_start;
std::uint32_t steps_inside_target;
};
/** @brief Tells which parts of the provided range relative to the stored direction are mappable to
* the buffer range determined by the dimensions and padding
*
* @param[in] dimension The direction of the range relative to the currently stored position
* @param[in] delta The size of the range starting from the stored position
*
* @return A vector of the parts of the interval inside the bounds of the objects buffer range:
* {position, size}:
* |->absolute position inside the given dimension,
* |--------->number of steps still inside the defined ranges in the direction of the given dimension
*/
std::vector<IntervalPart> mappable_parts_of(
const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta
) const; | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @brief Tells which parts of the stored range relative to the stored direction are mappable to
* the buffer range determined by the dimensions and padding
*
* @param[in] dimension The direction of the range relative to the currently stored position
* @param[in] delta The size of the range starting from the stored position
*
* @return A vector of the parts of the interval inside the bounds of the objects buffer range:
* {position, size}:
* |->absolute position inside the given dimension,
* |--------->number of steps still inside the defined ranges in the direction of the given dimension
*/
std::vector<IntervalPart> mappable_parts_of(std::uint32_t dimension, std::int32_t delta) const{
return mappable_parts_of(m_position, dimension, delta);
}
/** @brief Tells the size of the internal buffer range, which maps every item in the NDArray to a one dimensional array
*
* @return Reference to the object
*/
std::uint32_t buffer_size() const{
return m_bufferSize;
}
/** @brief Returns the number of dimensions
*
* @return The number of dimensions
*/
std::uint32_t size() const{
return m_dimensions.size();
}
/** @brief Returns the number of elements inside bounds under the given dimension
*
* @param[in] dimension the dimension to query the size for
*
* @return the number of elements ( including padding ) the given dimension contains
*/
std::uint32_t operator[](std::int32_t dimension) const{
return m_padding[dimension] + m_dimensions[dimension] + m_padding[dimension];
}
/** @brief Tells if the Object contains any padding at all
*
* @return true, if any padding dimension is non-zero
*/
bool has_padding(){
return (static_cast<std::uint32_t>(std::count(m_padding.begin(), m_padding.end(), 0)) < m_padding.size());
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
/** @brief Runs a given function through a kernel, starting from the stored position.
* The provided function is being called once every time kernel iteration hits the
* beginning of dimension[0] in the provided kernel. The arguments are called with
* the mapped index values inside this object, along with the count of elements available
* from the start until the end of dimension[0]. The position of the object is updated along
* with the position of the kernel during iteration, and is restored after iteration is finished.
*
* @param kernel the kernel dimensions to use for iteration
* @param[in] fun the function to call for each kernel iteration.
* Arguments: void(mapped_position, interval size)
*/
void scan_kernel(NDArrayIndex& kernel, std::function<void(std::uint32_t, std::uint32_t)> fun);
private:
const std::vector<std::uint32_t> m_dimensions;
const std::vector<std::int32_t> m_padding;
const std::vector<std::uint32_t> m_strides;
const std::uint32_t m_bufferSize;
std::vector<std::uint32_t> m_position;
std::optional<std::uint32_t> m_mappedIndex;
};
source:
#include <cassert>
#include <numeric>
#include <algorithm>
#include <cmath>
std::vector<std::int32_t> init_padding(
const std::vector<std::uint32_t>& dimensions, const std::vector<std::int32_t>& padding
){
if(1 == padding.size())
return std::vector<std::int32_t>(dimensions.size(), padding[0]);
if(1 < padding.size()){
assert(dimensions.size() == padding.size());
return padding;
}
return std::vector<std::int32_t>(dimensions.size(), 0);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
std::vector<std::uint32_t> init_strides(
const std::vector<std::uint32_t>& dimensions, const std::vector<std::int32_t>& padding
){
assert(dimensions.size() == padding.size());
std::vector<std::uint32_t> strides;
std::uint32_t prev_stride = 1u;
std::int32_t prev_padding = padding[0];
std::uint32_t dim = 0;
for(const std::uint32_t& dimension : dimensions){
strides.push_back(prev_stride);
prev_stride *= dimension + 2 * std::min(0, prev_padding);
prev_padding = padding[dim++];
}
return strides;
}
std::vector<std::uint32_t> init_position(
const std::vector<std::uint32_t>& dimensions, const std::vector<std::uint32_t>& position
){
if(0 < position.size()){
assert(dimensions.size() == position.size());
return {position};
}
return std::vector<std::uint32_t>(dimensions.size(), 0);
}
} /* namespace */
namespace rafko_utilities {
NDArrayIndex::NDArrayIndex(
const std::vector<std::uint32_t>& dimensions, const std::vector<std::int32_t>& padding,
const std::vector<std::uint32_t>& position
)
: m_dimensions(dimensions)
, m_padding(init_padding(m_dimensions, padding))
, m_strides(init_strides(dimensions, m_padding))
, m_bufferSize(std::accumulate(m_dimensions.begin(), m_dimensions.end(), 1.0,
[](const std::uint32_t& partial, const std::uint32_t& element){ return partial * element; }
))
, m_position(init_position(m_dimensions, position))
, m_mappedIndex(calculate_mapped_position(m_position))
{
assert(0 == std::count(m_dimensions.begin(), m_dimensions.end(), 0));
assert(inside_bounds(m_position));
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
NDArrayIndex::NDArrayIndex(const NDArrayIndex& other, const std::vector<std::int32_t>& padding)
: m_dimensions(other.m_dimensions)
, m_padding(init_padding(m_dimensions, padding))
, m_strides(init_strides(m_dimensions, m_padding))
, m_bufferSize(other.m_bufferSize)
, m_position(other.m_position)
, m_mappedIndex(calculate_mapped_position(m_position))
{
assert(0 == std::count(m_dimensions.begin(), m_dimensions.end(), 0));
assert(inside_bounds(m_position));
}
NDArrayIndex& NDArrayIndex::set(const std::vector<std::uint32_t>& position){
assert(position.size() == m_position.size());
assert(inside_bounds(position));
m_position = position;
m_mappedIndex = calculate_mapped_position(m_position);
assert( (!m_mappedIndex.has_value())||(m_mappedIndex.value() < m_bufferSize) );
return *this;
}
NDArrayIndex& NDArrayIndex::set(std::uint32_t dimension, std::uint32_t position){
assert(dimension < size());
m_position[dimension] = position;
m_mappedIndex = calculate_mapped_position(m_position);
assert( (!m_mappedIndex.has_value())||(m_mappedIndex.value() < m_bufferSize) );
assert(inside_bounds(m_position));
return *this;
}
std::uint32_t NDArrayIndex::step(){
std::uint32_t dim = 0;
bool changed = false;
while(dim < m_dimensions.size()){
if(inside_bounds(dim, 1)){
step(dim, 1);
break;
}else{
changed = true;
m_position[dim] = 0u;
}
++dim;
}
if(dim >= m_dimensions.size()){
m_mappedIndex = 0u; /* Overflow happened, start from the beginning */
return m_dimensions.size() - 1;
}else{
if(changed)m_mappedIndex = calculate_mapped_position(m_position);
assert(m_mappedIndex < m_bufferSize);
return dim;
}
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
NDArrayIndex& NDArrayIndex::step(std::uint32_t dimension, std::int32_t delta){
const std::int32_t new_position = static_cast<std::int32_t>(m_position[dimension]) + delta;
if(
(new_position < 0)
||(
new_position >= static_cast<std::int32_t>(m_dimensions[dimension] + (2 * std::max(0, m_padding[dimension])))
)
)throw std::runtime_error(
"Current position d[" + std::to_string(dimension) + "] + " + std::to_string(delta) + " out of bounds!"
);
m_position[dimension] = new_position;
bool new_position_is_inside_content = inside_content(m_position);
if(m_mappedIndex.has_value() && new_position_is_inside_content){ /* m_mappedIndex has a value if the previous position was valid */
m_mappedIndex.value() += m_strides[dimension] * delta;
assert(m_mappedIndex < m_bufferSize);
}else if(new_position_is_inside_content){ /* if the new position is inside bounds, then the mapped index can be caluclated */
m_mappedIndex = calculate_mapped_position(m_position);
}else m_mappedIndex = {}; /* No mapped index for positions inside the padding */
return *this;
}
std::optional<std::uint32_t> NDArrayIndex::calculate_mapped_position(const std::vector<std::uint32_t>& position) const{
assert(position.size() == m_strides.size());
if(!inside_content(position))
return {};
std::uint32_t result_index = 0u;
for(std::uint32_t dim = 0; dim < position.size(); ++dim){
result_index += (position[dim] - std::max(m_padding[dim], -m_padding[dim])) * m_strides[dim];
}
return result_index;
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
bool NDArrayIndex::inside_bounds(const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta) const{
std::uint32_t dim = 0;
return std::all_of(position.begin(), position.end(),
[this, &dim, dimension, delta](const std::uint32_t& pos){
std::int32_t position = static_cast<std::int32_t>(pos);
if(dim == dimension) position += delta;
++dim;
return(
(0 <= position)
&&( position < (2 * std::max(int64_t{0}, static_cast<int64_t>(m_padding[dim - 1])) + static_cast<int64_t>(m_dimensions[dim - 1])) )
);
}
);
}
bool NDArrayIndex::inside_content(const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta) const{
std::uint32_t dim = 0;
return std::all_of(position.begin(), position.end(),
[this, &dim, dimension, delta](const std::uint32_t& pos){
std::int32_t actual_position = static_cast<std::int32_t>(pos);
if(dim == dimension) actual_position += delta;
++dim;
return(
(std::max(m_padding[dim - 1], -m_padding[dim - 1]) <= actual_position)
&&(actual_position < static_cast<std::int32_t>(m_dimensions[dim - 1] + m_padding[dim - 1]))
);
}
);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
std::vector<NDArrayIndex::IntervalPart> NDArrayIndex::mappable_parts_of(
const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta
) const{
std::vector<NDArrayIndex::IntervalPart> result;
bool part_in_progress = false;
for(std::int32_t delta_index = 0; delta_index < delta; delta_index += std::copysign(1, delta)){
const bool current_position_in_inside_content = inside_content(position, dimension, delta_index);
if(current_position_in_inside_content && part_in_progress){
assert(0 < result.size());
++result.back().steps_inside_target; /* Increase the size of the current part of the interval */
}else if(current_position_in_inside_content){ /* If the interval iteration became inside bounds */
result.push_back({(position[dimension] + delta_index), 1}); /* Add the new part as a result */
part_in_progress = true;
}else part_in_progress = false;
}
return result;
}
void NDArrayIndex::scan_kernel(NDArrayIndex& kernel, std::function<void(std::uint32_t, std::uint32_t)> fun){
assert(!kernel.has_padding());
assert(size() == kernel.size());
std::vector<std::uint32_t> original_position = m_position;
kernel.reset();
do{ /* Acquire interval inside bounds of the mappable buffer and call the function with it */
std::vector<NDArrayIndex::IntervalPart> parts_inside_content = mappable_parts_of(m_position, 0, kernel[0]);
if(mapped_position().has_value() && (0 < parts_inside_content.size())){
auto& [start_pos, interval_size] = parts_inside_content[0];
fun(mapped_position().value() - m_position[0] + start_pos, interval_size);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
try{ /* Step in dimension[1], because dimension[0] should stay at position 0 */
kernel.step(1,1); /* throws exception if the position goes out of bounds */
step(1,1);
std::cout << "^";
}catch(...){ /* In case dimension[1] is out of bounds, step to the next position by the interface with wrap around */
std::cout << ">";
kernel.set(0, kernel[0] - 1); /* set the first dimensions position inside the kernel to the last */
std::uint32_t modified_dimension = kernel.step();
/*!Note: Because of overflow, the position in dimension[0] will reset to zero */
if((kernel.mapped_position().has_value())&&(kernel.mapped_position().value() != 0)){
for(std::uint32_t dim = 0; dim < modified_dimension; ++dim){
m_position[dim] = original_position[dim];
}
++m_position[modified_dimension];
m_mappedIndex = calculate_mapped_position(m_position);
}
}
}while( /* when the mapped position for the kernel points to the start of the first dimension, and the end of the others */
(kernel.mapped_position().has_value()) /* the kernel is iterated through */
&&(0 != kernel.mapped_position().value())
);
set(original_position);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
test:
TEST_CASE("Testing NDArray Indexing with a 2D array without padding", "[NDArray]"){
std::uint32_t width = rand()%100;
std::uint32_t height = rand()%100;
rafko_utilities::NDArrayIndex idx({width, height});
REQUIRE(!idx.has_padding());
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = rand()%width;
std::uint32_t y = rand()%height;
idx.set({x,y});
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE(idx.mapped_position().value() == (x + (y * width)));
std::uint32_t elements_after_x_row = width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == idx.mappable_parts_of(0,width)[0].position_start);
REQUIRE(elements_after_x_row == idx.mappable_parts_of(0,width)[0].steps_inside_target);
/*!Note: using width in the above interfaces because it is guaranteed
* that an interval of that size spans over the relevant dimension
* */
if(y < (height - 1u))REQUIRE( idx.step(1,1).mapped_position() == (x + ((y + 1) * width)) );
else CHECK_THROWS(idx.step(1,1));
}
REQUIRE(idx.buffer_size() == (width * height));
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == i);
idx.step();
}
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
TEST_CASE("Testing NDArray Indexing with a 2D array with positive padding", "[NDArray][padding]"){
std::uint32_t width = 1 + rand()%20;
std::uint32_t height = 1 + rand()%20;
std::int32_t padding_x = rand()%5;
std::int32_t padding_y = rand()%5;
rafko_utilities::NDArrayIndex idx({width, height}, {padding_x, padding_y});
REQUIRE(idx.has_padding());
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = padding_x + rand()%(width);
std::uint32_t y = padding_y + rand()%(height);
idx.set({x,y});
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE( idx.mapped_position().value() == (x - padding_x + ((y - padding_y) * width)) );
std::uint32_t elements_after_x_row = padding_x + width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == idx.mappable_parts_of(0,width)[0].position_start);
REQUIRE(elements_after_x_row == idx.mappable_parts_of(0,width)[0].steps_inside_target);
if((static_cast<std::int32_t>(y) >= padding_y) && (y < (height + padding_y - 1)))
REQUIRE( idx.step(1,1).mapped_position() == (x - padding_x + ((y - padding_y + 1) * width)) );
else CHECK_NOTHROW(idx.step(1,1));
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
REQUIRE(idx.buffer_size() == (width * height));
std::uint32_t x = 0u;
std::uint32_t y = 0u;
std::uint32_t reference_mapped_position = 0u;
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
if(
(padding_x <= static_cast<std::int32_t>(x) && x < (padding_x + width))
&&(padding_y <= static_cast<std::int32_t>(y) && y < (padding_y + height))
){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == reference_mapped_position);
++reference_mapped_position;
}else{
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value() == false);
}
if(x < padding_x + width + padding_x - 1){
REQUIRE(idx.step() == 0u);
++x;
}else{
REQUIRE(idx.step() == 1u);
x = 0;
++y;
}
}
}
TEST_CASE("Testing NDArray Indexing with a 2D array with negative padding", "[NDArray][padding]"){
std::uint32_t width = 11 + rand()%20;
std::uint32_t height = 11 + rand()%20;
std::int32_t padding_x = -rand()%5;
std::int32_t padding_y = -rand()%5;
rafko_utilities::NDArrayIndex idx({width, height}, {padding_x, padding_y});
REQUIRE(idx.has_padding());
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = -padding_x + rand()%(width + 2 * padding_x);
std::uint32_t y = -padding_y + rand()%(height + 2 * padding_y);
idx.set({x,y}); | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE( idx.mapped_position().value() == (x + padding_x + ((y + padding_y) * (width + 2 * padding_x))) );
std::uint32_t elements_after_x_row = padding_x + width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == idx.mappable_parts_of(0,width)[0].position_start);
REQUIRE(elements_after_x_row == idx.mappable_parts_of(0,width)[0].steps_inside_target);
if((static_cast<std::int32_t>(y) > -padding_y) && (y < (height + padding_y - 1)))
REQUIRE( idx.step(1,1).mapped_position() == (x + padding_x + ((y + padding_y + 1) * (width + 2 * padding_x))) );
else CHECK_NOTHROW(idx.step(1,1));
}
REQUIRE(idx.buffer_size() == (width * height));
std::uint32_t x = 0u;
std::uint32_t y = 0u;
std::uint32_t reference_mapped_position = 0u;
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
if(
(-padding_x <= static_cast<std::int32_t>(x) && x < (padding_x + width))
&&(-padding_y <= static_cast<std::int32_t>(y) && y < (padding_y + height))
){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == reference_mapped_position);
++reference_mapped_position;
}else{
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value() == false);
}
if(x < (width - 1)){
REQUIRE(idx.step() == 0u);
++x;
}else{
REQUIRE(idx.step() == 1u);
x = 0;
++y;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
Answer: Surprising behavior of the copy constructor
The second constructor takes another NDArrayIndex and a padding vector as arguments. However, because the padding argument has a default value, this second constructor is also a valid copy constructor. However, instead of making an exact copy of other, it will zero the padding sizes. Maybe this just really is what you want if you explicitly call the copy constructor, but consider that copies might be made implicitly at some point. It's much better to avoid any surprises, and have the copy constructor copy the padding as well. I suggest writing:
NDArrayIndex(const NDArrayIndex& other, const std::vector<std::int32_t>& new_padding);
NDArrayIndex(const NDArrayIndex& other) = default; | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
Incomplete Doxygen documentation
It's great to see Doxygen comments being added! However, not all functions have been documented: it's missing for the constructors and for position().
Some functions don't have all parameters documented, like mappable_parts_of() missing documentation for the parameter position.
You can also add a comment for the class as a whole, explaining what its purpose is.
I strongly recommend enabling the WARN_AS_ERROR configuration option and running Doxygen as part of the regular build process.
Use of [in] and [out]
Parameters that are passed by value don't need the [in] annotation. It is only required for const pointers and references.
You should also use [out] when you are passing non-const pointers and references. You missed that for the parameter kernel of scan_kernel().
Don't use exceptions for non-exceptional situations
In scan_kernel(), you call kernel.step(1,1), and if this throws an exception you wrap around and try again. Consider that exceptions are free if you don't throw them, but can be horribly expensive if you do. So you should not use exceptions just to signal something that will happen normally in an expected situation. Create a step_or_wrap() function or something similar that does what you need in scan_kernel() and that doesn't throw anything.
Use of 32-bit integers
As already mentioned by Toby Speight, there is actually no guarantee that std::int32_t exists, but I consider that highly unlikely these days. But more importantly, using 32-bit integers limits the maximum size of the arrays. For a high-dimensional array it might not make sense to have large sizes for the individual dimensions, but consider that their product might be quite large, and by even using 32-bit integers for m_mappedIndex, you limit yourself to arrays of at most 4 billion elements, which is not as large a number as it used to be. | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
There is also the issue that you have to use signed integers for some things, so effectively you only correctly handle arrays of 2 billion elements.
I strongly recommend that instead of hardcoding the use of 32-bit integers, you use std::size_t for indexes, counts and sizes.
Adding iterators | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
Iterators are not used, not even for scan_kernel because I could not find a way to introduce them; I'm still open to suggestions
It's really not that hard to add iterators. Iterators are just a way to store and manipulate a position. Your class NDArrayIndex is pretty much doing everything an iterator does, so you could make it an official iterator by ensuring it conforms to the appropriate concepts, for example std::input_iterator (see LegacyInputIterator for a more explicit list of requirements):
class NDArrayIndex {
public:
struct span {
std::size_t mapped_position;
std::size_t size;
};
using value_type = span;
using reference_type = span&;
using iterator_category = std::input_iterator;
span operator->() const;
span operator*() const;
NDArrayIndex& operator++();
bool operator==(const NDArrayIndex& other) const;
...
};
NDArrayIndex::span NDArrayIndex::operator*() const {
std::vector<NDArrayIndex::IntervalPart> parts_inside_content = mappable_parts_of(m_position, 0, kernel[0]);
auto& [start_pos, interval_size] = parts_inside_content[0];
return {start_pos, interval_size};
}
NDArrayIndex& operator++() {
kernel.step_or_wrap(1, 1);
return *this;
}
...
This allows you to write:
NDArrayIndex begin{...};
NDArrayIndex end = begin;
end.set(/* to end of array */);
for (auto it = begin; it != end; ++it) {
auto [start_pos, interval_size] = *it;
fun(start_pos, interval_size);
}
Ideally, you would add begin() and end() methods to NDArray that return NDArrayIndexes, so that you can then write:
NDArray array{...};
for (auto [start_pos, interval_size]: array) {
fun(start_Pos, interval_size);
} | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
c++, unit-testing
for (auto [start_pos, interval_size]: array) {
fun(start_Pos, interval_size);
}
Of course, I omitted several parts that are left as an excercise for the reader. You'll also notice it's a bit different from the usual iterators; those return references to the data in the container. You could make it so NDArrayIndex stores a reference to the NDArray it is indexing, so instead of the struct span I defined above, operator*() could return an actual std::span that directly references the data in the array. | {
"domain": "codereview.stackexchange",
"id": 44053,
"lm_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++, unit-testing",
"url": null
} |
php, array, json
Title: delete multidimentional array value in php | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
Question: I made a program that converts JSON to a PHP array and checks every value of the multidimensional array with a loop and if a value matches certain values then it deletes that key and value and converts it back to JSON. I am trying to make this with less code.
I use a nested foreach loop to check every element in the array. I give it condition like if value == 0 or empty string or null then delete it but it occupies too many lines of code. It is not a good method for too many multidimensional array so I was looking for a better solution.
This is my JSON:
{
"UniqueId": "PO3589472",
"FareType": 2,
"BookedBy": "Api ",
"OrderBy": "Api ",
"ClientBalance": 0,
"Error": null,
"Success": true,
"TktTimeLimit": "2022-08-10T14:11:45",
"Category": 21,
"Status": 21,
"RefundMethod": 1,
"TravelItinerary": {
"ItineraryInfo": {
"ItineraryPricing": {
"BaseFare": 8469250,
"ServiceTax": 0,
"TotalTax": 993000,
"TotalFare": 9462250,
"TotalCommission": 0,
"Currency": "IRR"
},
"CustomerInfoes": [
{
"Customer": {
"Gender": 0,
"PassengerType": 1,
"PassportNumber": "",
"NationalId": "1829961233",
"Nationality": "IR",
"DateOfBirth": "1996-07-08T00:00:00",
"PassportExpireDate": "0001-01-01T00:00:00",
"PassportIssueCountry": "IR",
"PassportIssueDate": "2022-08-10T00:00:00",
"PaxName": {
"PassengerFirstName": "MAJID",
"PassengerMiddleName": null,
"PassengerLastName": "MAJIDIFAR",
"PassengerTitle": 0
}
},
"ETickets": "8151405444745",
"ETicketNumbers": [
{ | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
"ETicketNumbers": [
{
"ETicketNumber": "8151405444745",
"EticketStatus": 1,
"IsRefunded": false,
"DateOfIssue": "2022-08-10T13:58:47",
"AirlinePnr": "TXNXM",
"TotalRefund": 0
}
]
}
],
"ReservationItems": [
{
"AirEquipmentType": "737",
"AirlinePnr": "TXNXM",
"ArrivalAirportLocationCode": "ABD",
"ArrivalDateTime": "2022-08-17T23:25:00",
"ArrivalTerminal": "",
"Baggage": "20KG",
"DepartureAirportLocationCode": "THR",
"DepartureDateTime": "2022-08-17T22:05:00",
"DepartureTerminal": "Terminal 4",
"FlightNumber": "3750",
"JourneyDuration": "01:20",
"JourneyDurationPerMinute": 0,
"MarketingAirlineCode": "EP",
"OperatingAirlineCode": "EP",
"ResBookDesigCode": "Y",
"StopQuantity": 0,
"IsCharter": false,
"TechnicalStops": [],
"IsReturn": false,
"CabinClassCode": 1
}
],
"TripDetailPtcFareBreakdowns": [
{
"PassengerTypeQuantity": {
"PassengerType": 1,
"Quantity": 1
},
"TripDetailPassengerFare": {
"BaseFare": 8469250,
"ServiceTax": 0,
"Tax": 993000,
"TotalFare": 9462250,
"Commission": 0,
"Currency": "IRR"
}
}
],
"PhoneNumber": "09359276735",
"Email": "info@iran-tech.com",
"ItineraryFareFamily": null
}, | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
"Email": "info@iran-tech.com",
"ItineraryFareFamily": null
},
"BookingNotes": [],
"Services": []
},
"ValidatingAirlineCode": "EP",
"DirectionInd": 1,
"OnlineCheckIn": false,
"AirRemark": [],
"curl_error": false} | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
this is my php code
<?php
$jsondata = file_get_contents("test_php.json");
$json = json_decode($jsondata, true); | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
foreach($json as $keys1 => $values1){
if($values1 == 0 || $values1 == "" || $values1 == "Api " || !isset($values1) ){
unset($json[$keys1]);
}else{
if(is_array($values1)){
foreach($values1 as $keys2 => $values2){
if($values2 == 0 || $values2 == "" || $values2 == "Api " || !isset($values2) ){
unset($json[$keys1][$keys2]);
}else{
if(is_array($values2)){
foreach($values2 as $keys3 => $values3){
if($values3 == 0 || $values3 == "" || $values3 == "Api " || !isset($values3) ){
unset($json[$keys1][$keys2][$keys3]);
}else{
if(is_array($values3)){
foreach($values3 as $keys4 => $values4){
if($values4 == 0 || $values4 == "" || $values4 == "Api " || !isset($values4) ){
unset($json[$keys1][$keys2][$keys3][$keys4]);
}else{
if(is_array($values4)){
foreach($values4 as $keys5 => $values5){
if($values5 == 0 || $values5 == "" || $values5 == "Api " || !isset($values5) ){
unset($json[$keys1][$keys2][$keys3][$keys4][$keys5]);
}else{
if(is_array($values5)){
foreach($values5 as $keys6 => $values6){
if($values6 == 0 || $values6 == "" || $values6 == "Api " || !isset($values6) ){ | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
unset($json[$keys1][$keys2][$keys3][$keys4][$keys5][$keys6]);
}else{
if(is_array($values6)){
foreach($values6 as $keys7 => $values7){
if($values7 == 0 || $values7 == "" || $values7 == "Api " || !isset($values7) ){
unset($json[$keys1][$keys2][$keys3][$keys4][$keys5][$keys6][$keys7]);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
php, array, json
}
}
}
}
}
$path = "test_php(final).json";
$converter = json_encode($json, JSON_PRETTY_PRINT);
// print_r($v);
$open = fopen($path, 'w');
fwrite($open, $converter);
fclose($open);
// print_r($json);
?>
Answer: Use recommended/idiomatic spacing
Mick has already answered the main question about reducing the code by utilizing a recursive function. Notice in that sample code that there is a space following keywords like foreach and if, as well as one space between a closing parenthesis and the opening brace. Take for example the foreach and if statements on the first two lines of the function:
foreach ($input as &$value) {
if (is_array($value)) {
This is common in idiomatic PHP code, and is recommended by the PHP Standards Recommendations guide PSR-12. The original code does not have such spaces - for example:
foreach($json as $keys1 => $values1){
if($values1 == 0 || $values1 == "" || $values1 == "Api " || !isset($values1) ){
Writing to a file can be a single line instead of three
It is fine to call fopen(), fwrite() and fclose(), though the same can be achieved by calling file_put_contents().
file_put_contents($path, $converter);
This approach can be slightly slower so if performance is a concern then it may be wise to keep the current tactic of calling the three functions instead. | {
"domain": "codereview.stackexchange",
"id": 44054,
"lm_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, array, json",
"url": null
} |
c#, asp.net-mvc
Title: Dynamically MVC controls | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
Question: I am working project where I need to build ASP.net control based on JSON data. I am using the method below GetMeetingPollingQuestion to create this model.
Any suggestions/comments are greatly appreciated to improve the code further. Thanks.
JSON | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
Any suggestions/comments are greatly appreciated to improve the code further. Thanks.
JSON
[{"MeetingPollingQuestionId":1,"MeetingPollingQuestionType":"LongAnswerText","MeetingPollingId":1,"SequenceOrder":1,"MeetingPollingParts":[{"MeetingPollingPartsId":1,"Type":"Question","MeetingPollingQuestionId":1,"MeetingPollingPartsValues":[{"MeetingPollingPartsValuesId":1,"Type":"label","QuestionValue":"Do you have additional comments or concerns with these changes to the Guidelines?","FileManagerId":0,"FileName":null,"FileData":null,"FileType":null}]}]},{"MeetingPollingQuestionId":12,"MeetingPollingQuestionType":"MultipleChoice","MeetingPollingId":1,"SequenceOrder":2,"MeetingPollingParts":[{"MeetingPollingPartsId":35,"Type":"Question","MeetingPollingQuestionId":12,"MeetingPollingPartsValues":[{"MeetingPollingPartsValuesId":63,"Type":"label","QuestionValue":"Do you approve the following statement to be added for all current rituximab indications in the Guidelines: “An FDA-approved biosimilar is an appropriate substitute for rituximab”? ","FileManagerId":0,"FileName":null,"FileData":null,"FileType":null}]},{"MeetingPollingPartsId":36,"Type":"Image","MeetingPollingQuestionId":12,"MeetingPollingPartsValues":[{"MeetingPollingPartsValuesId":64,"Type":"FileManagerId","QuestionValue":null,"FileManagerId":14716,"FileName":"B-cell_1.2022_panel vote_Page_02 - Copy.png","FileData":"iVBORw.....","FileType":"image/png"}]},{"MeetingPollingPartsId":37,"Type":"Answers","MeetingPollingQuestionId":12,"MeetingPollingPartsValues":[{"MeetingPollingPartsValuesId":65,"Type":"Answers","QuestionValue":"Yes","FileManagerId":0,"FileName":null,"FileData":null,"FileType":null},{"MeetingPollingPartsValuesId":66,"Type":"Answers","QuestionValue":"No","FileManagerId":0,"FileName":null,"FileData":null,"FileType":null},{"MeetingPollingPartsValuesId":67,"Type":"Answers","QuestionValue":"Abstain","FileManagerId":0,"FileName":null,"FileData":null,"FileType":null}]}]}] | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
Method
public IEnumerable<MeetingPollingQuestionViewModel> GetMeetingPollingQuestion()
{
List<MeetingPollingQuestionViewModel> vm = new List<MeetingPollingQuestionViewModel>();
//JSON Data parse into class Model and set to object ListofMeetingPollingQuestion
foreach (MeetingPollingQuestion MeetingPollingQuestion in ListofMeetingPollingQuestion)
{
int SequenceOrder = MeetingPollingQuestion.SequenceOrder;
switch (MeetingPollingQuestion.MeetingPollingQuestionType)
{
case "LongAnswerText":
MeetingPollingQuestionViewModel LongAnswerText = new MeetingPollingQuestionViewModel();
LongAnswerText.QuestionType = "LongAnswerText";
var MeetingPollingParts = MeetingPollingQuestion.MeetingPollingParts;
var LongAnswerQuestion = MeetingPollingParts.FirstOrDefault(part => part.Type == "Question");
var labelControl = LongAnswerQuestion.MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "label");
LongAnswerText.labelControl = $"{SequenceOrder}. {labelControl.QuestionValue}'";
LongAnswerText.textboxControl = $"textboxfor_{labelControl.MeetingPollingPartsValuesId}";
vm.Add(LongAnswerText);
break;
case "MultipleChoice":
MeetingPollingQuestionViewModel MultipleChoice = new MeetingPollingQuestionViewModel();
MultipleChoice.QuestionType = "MultipleChoice";
var MultipleChoiceMeetingPollingParts = MeetingPollingQuestion.MeetingPollingParts;
var MultipleChoiceQuestion = MultipleChoiceMeetingPollingParts.FirstOrDefault(part => part.Type == "Question");
var MultipleChoicelabelControl = MultipleChoiceQuestion.MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "label");
MultipleChoice.labelControl = $"{SequenceOrder}. {MultipleChoicelabelControl.QuestionValue}'"; | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
var MultipleChoiceImage = MultipleChoiceMeetingPollingParts.FirstOrDefault(part => part.Type == "Image");
var MultipleChoiceImageControl = MultipleChoiceImage.MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "FileManagerId");
if (MultipleChoiceImageControl.FileManagerId != 0){
MultipleChoice.imageSRC = MultipleChoiceImageControl.FileData;
}
var MultipleChoiceAnswers = MultipleChoiceMeetingPollingParts.FirstOrDefault(part => part.Type == "Answers");
var MultipleChoiceAnswersControl = MultipleChoiceAnswers.MeetingPollingPartsValues.ToList();
List<CBRBControl> RadioButtonlist = new List<CBRBControl>();
foreach (var item in MultipleChoiceAnswersControl)
{
CBRBControl RadioButton = new CBRBControl();
RadioButton.Value = item.MeetingPollingPartsValuesId.ToString();
RadioButton.Label = item.QuestionValue;
RadioButtonlist.Add(RadioButton);
}
multipleChoice.RadioButtonName = $"radioList_{MultipleChoiceAnswers.MeetingPollingQuestionId}";
multipleChoice.RadioButtonList = RadioButtonlist;
vm.Add(MultipleChoice);
break;
}
}
return vm;
}
}
Model
public class MeetingPollingQuestionViewModel
{
public string QuestionType { get; set; }
public string labelControl { get; set; }
public string textboxControl { get; set; }
public string imageControl { get; set; }
public byte[] imageSRC { get; set; }
public string RadioButtonName { get; set; }
public List<CBRBControl> RadioButtonList { get; set; }
}
public class CBRBControl
{
public string Label { get; set; }
public string Value { get; set; }
} | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
Answer: Gerneral advice
look at this line
List<MeetingPollingQuestionViewModel> vm = new List<MeetingPollingQuestionViewModel>();
this variable name vm showed be plural because it's a list vms .. and you can use the simplified new expression
List<MeetingPollingQuestionViewModel> vms = new();
your foreach loop could be more readable if you use var key word and short variable name
foreach (var Question in ListofMeetingPollingQuestion)
it's more readable than
foreach (MeetingPollingQuestion MeetingPollingQuestion in ListofMeetingPollingQuestion)
Redundancy elimination
Looke at this of code for each case it's nearly identical
foreach (MeetingPollingQuestion MeetingPollingQuestion in ListofMeetingPollingQuestion)
{
int SequenceOrder = MeetingPollingQuestion.SequenceOrder;
switch (MeetingPollingQuestion.MeetingPollingQuestionType)
{
case "LongAnswerText":
MeetingPollingQuestionViewModel LongAnswerText = new MeetingPollingQuestionViewModel();
LongAnswerText.QuestionType = "LongAnswerText";
var MeetingPollingParts = MeetingPollingQuestion.MeetingPollingParts;
var LongAnswerQuestion = MeetingPollingParts.FirstOrDefault(part => part.Type == "Question");
var labelControl = LongAnswerQuestion.MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "label");
LongAnswerText.labelControl = $"{SequenceOrder}. {labelControl.QuestionValue}'";
//... code
vm.Add(LongAnswerText);
break;
case "MultipleChoice":
MeetingPollingQuestionViewModel MultipleChoice = new MeetingPollingQuestionViewModel();
MultipleChoice.QuestionType = "MultipleChoice";
var MultipleChoiceMeetingPollingParts = MeetingPollingQuestion.MeetingPollingParts; | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
var MultipleChoiceQuestion = MultipleChoiceMeetingPollingParts.FirstOrDefault(part => part.Type == "Question");
var MultipleChoicelabelControl = MultipleChoiceQuestion.MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "label");
MultipleChoice.labelControl = $"{SequenceOrder}. {MultipleChoicelabelControl.QuestionValue}'";
//... code
vm.Add(MultipleChoice);
break;
}
}
in both cases you create a new view model and change the same property and create same variables with different names and at the end add this view model in your list
foreach (var Question in ListofMeetingPollingQuestion)
{
int SequenceOrder = Question.SequenceOrder;
MeetingPollingQuestionViewModel vm = new();
vm.QuestionType = Question.MeetingPollingQuestionType;
var MeetingPollingParts = Question.MeetingPollingParts;
var QuestionObj = MeetingPollingParts.FirstOrDefault(part => part.Type == "Question");
var label = QuestionObj .MeetingPollingPartsValues.FirstOrDefault(part => part.Type == "label");
vm.labelControl = $"{SequenceOrder}. {label.QuestionValue}'";
switch (Question.MeetingPollingQuestionType)
{
case "LongAnswerText":
//... code
break;
case "MultipleChoice":
//... code
break;
}
vms.Add(vm);
}
Bad type
your code use string literals such as ("LongAnswerText", "MultipleChoice", "FileManagerId", "label", "Question" ,... etc) you should avoid this technique because this string's value is not checked at compile time Read more resons whe you should not use magic strings try useing Enums or constant value insted
for example define this enum
public enum QuestionType
{
LongAnswerText,
MultipleChoice
} | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c#, asp.net-mvc
then change the type MeetingPollingQuestionType to beQuestionType then give your code the compiler check superpower as following
switch (Question.MeetingPollingQuestionType)
{
case QuestionType.LongAnswerText:
//... code
break;
case QuestionType.MultipleChoice:
//... code
break;
} | {
"domain": "codereview.stackexchange",
"id": 44055,
"lm_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#, asp.net-mvc",
"url": null
} |
c, strings, parsing
Title: if you gaze long enough into strtok, strtok will gaze back into you
Question: The tokenise function below splits a given string at the indicated delimiters. As with strtok, it modifies the string by adding '\0's at the end of each token.
A pointer to the start of each token string is placed into the output array.
#include <string.h>
/*
* Wrapper around strtok
*
* Splits a string at characters in "delimiters", writing each token to "output".
* Delimiter characters in the source are overwritten with '\0'.
* Stops tokenising if "output_size" is reached.
*
* Returns 0 if "source", "delimiters", or "output" are NULL.
* Returns 0 if "output_size" is 0.
*
* "source" must NOT be a string literal (modifying one is undefined behaviour).
* "output" must be at least "output_size" long.
*
* Example usage:
* char[] src = "a b c";
* char* out[3];
* size_t n = tokenise(src, " ", out, 3);
*
*/
size_t tokenise(char* source, char const* delimiters, char** output, size_t output_size)
{
if (!source) return 0;
if (!delimiters) return 0;
if (!output) return 0;
if (output_size < 1) return 0;
char* const* start = output;
char* const* end = output + output_size;
*output = strtok(source, delimiters);
while (*output && ++output != end)
*output = strtok(NULL, delimiters);
return output - start;
}
#include <stdio.h>
#include <stdbool.h>
void test(bool conditional)
{
if (!conditional)
printf("failed!\n");
}
void test_null_source_returns_zero()
{
char* output[1];
test(tokenise(NULL, " ", output, 1) == 0);
}
void test_null_delimiters_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, NULL, output, 1) == 0);
test(source[0] != '\0');
}
void test_null_output_returns_zero()
{
char source[] = " ";
test(tokenise(source, " ", NULL, 1) == 0);
test(source[0] != '\0');
} | {
"domain": "codereview.stackexchange",
"id": 44056,
"lm_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, strings, parsing",
"url": null
} |
c, strings, parsing
void test_zero_output_size_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, " ", output, 0) == 0);
test(source[0] != '\0');
}
void test_empty_source_returns_zero()
{
char source[] = "";
char* output[1];
test(tokenise(source, " ", output, 1) == 0);
}
void test_source_without_delimiters_returns_one()
{
char source[] = "sdlfkj";
char* output[1];
test(tokenise(source, " ", output, 1) == 1);
}
void test_source_with_only_delimiters_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, " ", output, 1) == 0);
test(source[0] != '\0');
}
void test_empty_delimiters_returns_one()
{
char source[] = "abc";
char* output[1];
test(tokenise(source, "", output, 1) == 1);
test(strcmp(output[0], source) == 0);
}
void test_source_starts_with_delimiter()
{
char source[] = " abc";
char* output[1];
test(tokenise(source, " ", output, 1) == 1);
test(source[0] != '\0');
test(strcmp(output[0], "abc") == 0);
}
void test_source_ends_with_delimiter()
{
char source[] = "a 123 ";
char* output[2];
test(tokenise(source, " ", output, 2) == 2);
test(source[5] == '\0');
test(source[6] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "123") == 0);
}
void test_source_starts_and_ends_with_delimiter()
{
char source[] = " a bbb cccc dd ";
char* output[4];
test(tokenise(source, " ", output, 4) == 4);
test(source[3] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "bbb") == 0);
test(strcmp(output[2], "cccc") == 0);
test(strcmp(output[3], "dd") == 0);
}
void test_small_output_size_stops_tokenising()
{
char source[] = "a b c d";
char* output[2];
test(tokenise(source, " ", output, 2) == 2);
test(source[3] == '\0');
test(source[5] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "b") == 0);
} | {
"domain": "codereview.stackexchange",
"id": 44056,
"lm_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, strings, parsing",
"url": null
} |
c, strings, parsing
void test_large_output_size_stops_at_end_of_source()
{
char source[] = "a b c d";
char* output[53];
test(tokenise(source, " ", output, 53) == 4);
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "b") == 0);
test(strcmp(output[2], "c") == 0);
test(strcmp(output[3], "d") == 0);
}
int main(void)
{
test_null_source_returns_zero();
test_null_delimiters_returns_zero();
test_null_output_returns_zero();
test_zero_output_size_returns_zero();
test_empty_source_returns_zero();
test_source_without_delimiters_returns_one();
test_source_with_only_delimiters_returns_zero();
test_empty_delimiters_returns_one();
test_source_starts_with_delimiter();
test_source_ends_with_delimiter();
test_source_starts_and_ends_with_delimiter();
test_small_output_size_stops_tokenising();
test_large_output_size_stops_at_end_of_source();
printf("done!\n");
}
Online version.
General feedback is welcome.
Are there any missing tests / edge cases?
Is there a better way to calculate the return size? (i.e. without the start variable`)
Some things (the contents of output and '\0's in the source) are tested as side-effects of the named test functions. Perhaps these should be separate named test cases?
I usually do C++ stuff. Is there anything more C-ish that I'm missing? | {
"domain": "codereview.stackexchange",
"id": 44056,
"lm_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, strings, parsing",
"url": null
} |
c, strings, parsing
Answer: The tokenise() function is clear and succinct; I can't find anything to dislike. A couple of minor suggestions: wrap the declaration to a shorter line length, and consider changing the interface to terminate the output list with a null pointer (so that it's like argv).
It's great that you've included the unit tests for review. I love unit tests!
I recommend using an established test framework for the tests. It's fine to use a C++ unit-test framework for this, if we compile separately using extern "C" (as in this answer of mine). The big advantage you'll get is better diagnostics when tests fail: instead of just failed! in the output, you'll see which test failed, and the actual and expected values that caused the failure.
Yes, you can write your own EXPECT() macro (and I sometimes do, to make a simple test harness), but you'll find over time that it drifts towards the functionality of the existing unit-test libraries.
You might want to add a function/macro to test the output list of strings, to simplify this repetition:
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "bbb") == 0);
test(strcmp(output[2], "cccc") == 0);
test(strcmp(output[3], "dd") == 0);
If you're writing the tests in C++, you get to use standard collections to make that side of things more readable:
test_strings_eq({"a", "bbb", "cccc", "dd"}, output); | {
"domain": "codereview.stackexchange",
"id": 44056,
"lm_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, strings, parsing",
"url": null
} |
python, file-system, logging, amazon-web-services
Title: Simple server log backup script utilising AWS
Question: I have server side log files written to various directories throughout the course of a week. I have the need to optionally compress, and archive these files to AWS.
The script I have come up with takes a config file defining the include glob to look for matches, and offers optional removal of the source files once the process has completed.
python aws_bkup.py path/to/config.cfg
A sample config file can be found in the project directory: https://github.com/twanas/aws-bkup
I would be most appreciative of feedback on the code style and areas it can be improved.
from __future__ import print_function
import re
import errno
import os
from glob import glob
from os.path import join, basename, splitext
from os import environ, remove
from shutil import copy, rmtree
from uuid import uuid4
import gzip
from configparser import ConfigParser
from datetime import date, timedelta
import subprocess
def gz(src, dest):
""" Compresses a file to *.gz
Parameters
----------
src: filepath of file to be compressesd
dest: destination filepath
"""
filename = splitext(basename(src))[0]
destpath = join(dest, '{}.gz'.format(filename))
blocksize = 1 << 16 #64kB
with open(src) as f_in:
f_out = gzip.open(destpath, 'wb')
while True:
block = f_in.read(blocksize)
if block == '':
break
f_out.write(block)
f_out.close()
def aws_sync(src, dest):
""" Synchronise a local directory to aws
Parameters
----------
src: local path
dest: aws bucket
"""
cmd = 'aws s3 sync {} {}'.format(src, dest)
push = subprocess.call(cmd, shell=True)
def today():
""" Returns a string format of today's date """
return date.today().strftime('%Y%m%d') | {
"domain": "codereview.stackexchange",
"id": 44057,
"lm_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, file-system, logging, amazon-web-services",
"url": null
} |
python, file-system, logging, amazon-web-services
def fwe():
""" Returns a string format of the next friday's date """
d = date.today()
while d.weekday() != 4:
d += timedelta(1)
return d
def regex_match(string, pattern):
""" Returns if there is a match between parameter and regex pattern """
pattern = re.compile(pattern)
return pattern.match(string)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def aws_bkup(section, include, exclude, s3root, categorize_weekly=True, compress=True, remove_source=True):
""" Transfers a backup of any local files matching the user's criteria to AWS.
Parameters
----------
include: regex pattern to use for the file inclusion(s)
exclude: regex pattern to use for the file exclusion(s)
s3root: AWS root in which to send the backup
categorize_weekly: switch between daily and weekly folder groupings
compress: switch to compress outbound files to AWS
"""
folder = '{}'.format(fwe() if categorize_weekly else today())
tmp_root = join('/tmp', str(uuid4()))
tmp_dir = join(tmp_root, folder)
mkdir_p(tmp_dir)
for file in glob(include):
if regex_match(file, exclude):
continue
print('Processing: {}'.format(file))
if compress:
gz(file, tmp_dir)
else:
copy(file, tmp_dir)
if remove_source:
remove(file)
aws_dest = join(s3root, section)
print('Syncronizing {} to s3'.format(tmp_dir))
aws_sync(tmp_root, aws_dest)
if os.path.exists(tmp_root):
rmtree(tmp_root)
print('Done')
if __name__ == "__main__":
import sys
args = sys.argv
if len(args) < 2:
print("Usage: python -m aws-bkup /path/to/config.cfg")
sys.exit()
config = ConfigParser()
config.read(args[1]) | {
"domain": "codereview.stackexchange",
"id": 44057,
"lm_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, file-system, logging, amazon-web-services",
"url": null
} |
python, file-system, logging, amazon-web-services
config = ConfigParser()
config.read(args[1])
environ['AWS_ACCESS_KEY_ID'] = config.get('aws', 'access_id')
environ['AWS_SECRET_ACCESS_KEY'] = config.get('aws', 'secret_key')
environ['AWS_DEFAULT_REGION'] = config.get('aws', 'region')
for section in config.sections():
if section != 'aws':
print('Starting {}'.format(section))
aws_bkup(
section,
config.get(section, 'include'),
config.get(section, 'exclude'),
config.get('aws', 's3root'),
config.getboolean(section, 'categorize_weekly'),
config.getboolean(section, 'compress'),
config.getboolean(section, 'remove_source')
)
Answer: After a quick read-through, I’ve spotted two items:
with not used for f_out
The code:
with open(src) as f_in:
f_out = gzip.open(destpath, 'wb')
#...
f_out.close()
should be replaced with:
with open(arc) as f_in, gzip.open(destpath, 'wb') as f_out:
#...
Reg-ex pattern repeatedly compiled
The function regex_match() takes a string and compiles it to a pattern, and then matches a string to that pattern. The same pattern string is repeatedly passed to regex_match. This string should be compiled to a pattern by the caller, and the resulting pattern reused for each match. This means the calls to regex_match could be replaced by exclude_pattern.match(file)
Argument quoting
If src or dest contain spaces, this command may become confused.
cmd = 'aws s3 sync {} {}'.format(src, dest)
push = subprocess.call(cmd, shell=True) | {
"domain": "codereview.stackexchange",
"id": 44057,
"lm_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, file-system, logging, amazon-web-services",
"url": null
} |
python, file-system, logging, amazon-web-services
Since you are using the shell=True argument, it may also be a vector for arbitrary command injection!
Instead of formatting the command into a string, with proper quoting, and requiring the .call() command to parse it, you can simply pass in an array of arguments to the call. No need to worry about spaces or proper escaping/quoting -- and arbitrary command injection becomes much harder:
cmd = ['aws', 's3', 'sync', src, dest]
push = subprocess.call(cmd, shell=True)
Additional notes:
push is neither returned or used.
Also, while subprocess.call(...) is still acceptable, as of Python 3.5 subprocess.run(...) is the preferred interface. | {
"domain": "codereview.stackexchange",
"id": 44057,
"lm_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, file-system, logging, amazon-web-services",
"url": null
} |
c#, .net, rabbitmq
Title: RabbitMQ ConnectionFactory wrapper
Question: This is a wrapper around RabbitMQ.Client's ConnectionFactory. Here is the simplest Producer/Consumer RabbitMQ example https://github.com/delaneybrian/jumpstartCS-rabbitmq-csharp/tree/master/1-First-RabbitMQ-App.
I would like to get a code review over that factory method and its dependencies because I feel like the properties Username, Password, CurrentConnection, etc. should not be within the factory because of the single responsibility principle (SRP). There is a lot to comment such as Lazy<T>, etc.
public sealed class RabbitConnectionFactory : IRabbitConnectionFactory
{
private readonly IConnectionFactory _connectionFactory;
private readonly Lazy<IConnection> _lazyConnection;
private readonly Lazy<IModel> _lazyChannel;
public RabbitConnectionFactory(IConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
_lazyConnection = new Lazy<IConnection>(() =>
_connectionFactory.CreateConnection(), LazyThreadSafetyMode.ExecutionAndPublication);
_lazyChannel = new Lazy<IModel>(() =>
CurrentConnection.CreateModel(), LazyThreadSafetyMode.ExecutionAndPublication);
}
public static IRabbitConnectionFactory From<TOptions>(TOptions options) where TOptions : RabbitBaseOptions
{
ArgumentNullException.ThrowIfNull(options);
return new RabbitConnectionFactory(FromConfig(options));
}
private static IConnectionFactory FromConfig(RabbitBaseOptions baseOptions)
{
ArgumentNullException.ThrowIfNull(baseOptions); | {
"domain": "codereview.stackexchange",
"id": 44058,
"lm_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#, .net, rabbitmq",
"url": null
} |
c#, .net, rabbitmq
return new ConnectionFactory
{
HostName = baseOptions.Host,
Port = baseOptions.Port,
VirtualHost = baseOptions.VirtualHost,
UserName = baseOptions.User,
Password = baseOptions.Password,
RequestedHeartbeat = baseOptions.RequestedHeartbeat,
Ssl = new SslOption
{
Enabled = baseOptions.Tls.Enabled,
ServerName = baseOptions.Host,
Version = baseOptions.Tls.Enabled ? baseOptions.Tls.Protocols : SslProtocols.None,
AcceptablePolicyErrors = baseOptions.Tls.AcceptablePolicyErrors,
CertificateValidationCallback = baseOptions.Tls.CertificateValidationCallback
}
};
}
public string UserName => _connectionFactory.UserName;
public string Password => _connectionFactory.Password;
public string VirtualHost => _connectionFactory.VirtualHost;
public IConnection CurrentConnection => _lazyConnection.Value;
public IModel CurrentChannel => _lazyChannel.Value;
public IConnection CreateConnection() => _connectionFactory.CreateConnection();
public IModel CreateModel() => CurrentConnection.CreateModel();
public void Dispose()
{
if (_lazyChannel.IsValueCreated)
{
_lazyChannel.Value.Dispose();
}
if (_lazyConnection.IsValueCreated)
{
_lazyConnection.Value.Dispose();
}
}
}
public record RabbitSslOptions
{
public bool Enabled { get; init; }
public SslProtocols Protocols { get; init; } = SslProtocols.Tls12;
public SslPolicyErrors AcceptablePolicyErrors { get; init; } = SslPolicyErrors.None;
public RemoteCertificateValidationCallback? CertificateValidationCallback { get; set; }
}
public abstract record RabbitBaseOptions
{
public string Host { get; init; } = string.Empty;
public string VirtualHost { get; init; } = string.Empty; | {
"domain": "codereview.stackexchange",
"id": 44058,
"lm_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#, .net, rabbitmq",
"url": null
} |
c#, .net, rabbitmq
public string VirtualHost { get; init; } = string.Empty;
public string User { get; init; } = string.Empty;
public string Password { get; init; } = string.Empty;
public int Port { get; init; } = AmqpTcpEndpoint.UseDefaultPort;
public TimeSpan RequestedHeartbeat { get; set; } = TimeSpan.FromSeconds(60);
public RabbitSslOptions Tls { get; init; } = new();
}
public interface IRabbitConnectionFactory : IDisposable
{
/// <summary>
/// Username to use when authenticating to the server.
/// </summary>
string UserName { get; }
/// <summary>
/// Password to use when authenticating to the server.
/// </summary>
string Password { get; }
/// <summary>
/// Virtual host to access during this connection.
/// </summary>
string VirtualHost { get; }
IConnection CurrentConnection { get; }
IModel CurrentChannel { get; }
IConnection CreateConnection();
IModel CreateModel();
}
Answer: IRabbitConnectionFactory
Single or Multiple interfaces
As far as I can see this interface (in some degree) resembles/mimics the RabbitMq's IConnectionFactory
For me this mixture of properties (like UserName, Password, etc.) and methods (like CreateConnection) feels a bit odd
I would suggest to make an alternative version of this, where there are two interfaces (one with the UserName, Password and VirtualHost and another with the rest)
Naming
You have the following pairs of method - property:
CreateConnection, CurrentConnection
CreateModel, CurrentChannel
I would suggest to do some renaming to help the consumer of your util class
either CreateChannel
or CurrentModel
Connection
It feels a bit odd that you have the following | {
"domain": "codereview.stackexchange",
"id": 44058,
"lm_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#, .net, rabbitmq",
"url": null
} |
c#, .net, rabbitmq
either CreateChannel
or CurrentModel
Connection
It feels a bit odd that you have the following
The CreateConnection uses the RabbitMq's factory directly and creates a new connection every time when you call this method
The CurrentConnection uses the RabbitMq's factory directly as well but creates a new connection only at the very first usage then returns the same connection no matter how many times this property is accessed
Model / Channel
It feels a bit odd that
You can use the CreateModel or CurrentChannel without the need to initialize a connection
I'm unaware of the usage of this interface, but it feels like it would be enough to expose only this method and property pair (no need for the XYZConnections)
RabbitBaseOptions
As far as I can see you are not taking advantage of the fact that you have defined this structure as record
Defining it as an abstract class would be more convenient IMHO
I assume this structure is meant to be used with ASP.NET Core's Options pattern
If that's the case I would consider to use DataAnnotations as well
From the shared code piece it is unclear why the RequestedHeartbeat is the only mutable property inside this structure
If it is intentional then adding some documentation comment might bring clarity
If it in unintentional then change the set to init
RabbitSslOptions
Yet again this could be a simple class because you are not taking advantage of any features of the record
Why did you define the CertificateValidationCallback in a way that it has a setter rather than being an init-only property?
RabbitConnectionFactory
Please implement the IDisposable interface as it should be
The initialization of the lazy fields can be simplified
_lazyConnection = new(_connectionFactory.CreateConnection, LazyThreadSafetyMode.ExecutionAndPublication);
_lazyChannel = new(CurrentConnection.CreateModel, LazyThreadSafetyMode.ExecutionAndPublication); | {
"domain": "codereview.stackexchange",
"id": 44058,
"lm_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#, .net, rabbitmq",
"url": null
} |
c#, .net, rabbitmq
Inside the FromConfig I think it is unnecessary to perform a null check against the parameter
It is already done inside the From method
Since the RabbitBaseOptions is defined as abstract that's why you don't need to define the From as generic, simple just
public static IRabbitConnectionFactory From(RabbitBaseOptions options)
UPDATE #1
Btw isn't the Dispose pattern supposed to be like that since the class is basically sealed
You are right, I've missed that part this class is marked as sealed.
By you're not getting the advantages of record you mean the properties of the positional records i.e. removing the annoying nullability suggestions/warnings and the fact that it is IEquatable by default?
Yes, you are not taking advantage any of the above (based on the shared code fragment). If you don't need these extras then don't use it.
A record is just a class with some extra features.
A record struct will generate a struct with some extra features.
The CreateConnection uses the RabbitMq's factory directly and creates a new connection every time when you call this method, I was kinda confused on what to do with it. What would you suggest to me in order to deal with it?
If you don't need it then do not expose it via your interface. If you do need it then try to shape it in a way that suites your needs. If it is enough to return the lazily initialized (cached) connection every time then do not create a new one for each method call. | {
"domain": "codereview.stackexchange",
"id": 44058,
"lm_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#, .net, rabbitmq",
"url": null
} |
python
Title: Employee/Company system improved
Question: The following code tries to emulates a real employee/company relationship. I would like to recieve feedback on:
Any bad coding practices or code smells
Design in terms of practicality, effeciency, and ability to expand upon code
class Company():
def __init__(self, name, minimum_hiring_grades, required_work_experience_years,employee_leaves, employee_bonus_percent, employee_working_days) -> None:
self.name = name
self.minimum_hiring_grades = minimum_hiring_grades
self.required_work_experience_years = required_work_experience_years
self.employee_leaves = employee_leaves
self.employee_bonus_percent = employee_bonus_percent
self.employee_working_days = employee_working_days
self.employee_base = []
self.employees = []
def hire_employee(self, employee) -> None:
if employee.grades_percent_average >= self.minimum_hiring_grades and employee.work_experience_years >= self.required_work_experience_years:
print("You are hired!")
self.employee_base.append(employee)
employee.has_job = True
employee.working_days = self.employee_working_days
employee.bonus_percent = self.employee_bonus_percent
employee.available_leaves = self.employee_leaves
employee.salary_dollars = employee.grades_percent_average + employee.work_experience_years * 1000
employee.id = employee
else:
print("You did not meet our requirements.")
def give_leaves_employee(self, employee, leaves_required) -> None:
if leaves_required <= 3 and employee.available_leaves - leaves_required >= 0:
employee.available_leaves -= leaves_required
print("Leaves are granted.")
else:
print("Leaves can't be granted.") | {
"domain": "codereview.stackexchange",
"id": 44059,
"lm_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",
"url": null
} |
python
def print_self_employees(self):
self.employees = [employee.name for employee in self.employee_base]
print(self.employees)
def fire_employee(self, employee):
self.employee_del_attr(employee)
print(f"{employee.name} is fired from {self.name}")
def accept_employee_resignation(self, employee):
self.employee_del_attr(employee)
def employee_del_attr(self, employee):
self.employee_base.remove(employee)
del employee.company
del employee.salary_dollars
del employee.id
employee.has_job = False
class Employee:
def __init__(self, name, grades, work_experience_years):
self.name = name
self.grades_percent_average = grades
self.work_experience_years = work_experience_years
self.company = None
self.working_days = None
self.bonus_percent = None
self.has_job = False
self.id = None
def apply_in_company(self, company):
company.hire_employee(self)
def ask_for_leaves(self, leaves_required):
if self.has_job:
self.company.give_leaves_employee(self, leaves_required)
else:
print("You do not have a job!")
def resign_company(self, company) -> None:
self.company.accept_employee_resignation(self) | {
"domain": "codereview.stackexchange",
"id": 44059,
"lm_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",
"url": null
} |
python
Answer: It's hard to say much since the code isn't trying to solve anything yet.
Employee should be responsible for changing its own fields, Company doesn't need to know anything about it.
def hire_employee(self, employee) -> None:
if employee.grades_percent_average >= self.minimum_hiring_grades and employee.work_experience_years >= self.required_work_experience_years:
print("You are hired!")
self.employee_base.append(employee)
employee.has_job = True
employee.working_days = self.employee_working_days
employee.bonus_percent = self.employee_bonus_percent
employee.available_leaves = self.employee_leaves
employee.salary_dollars = employee.grades_percent_average + employee.work_experience_years * 1000
employee.id = employee
else:
print("You did not meet our requirements.")
can be turned into
# Company
def try_hire_employee(self, employee) -> None:
if (employee.grades_percent_average < self.minimum_hiring_grades or
employee.work_experience_years < self.required_work_experience_years):
print("You did not meet our requirements.")
return
print("You are hired!")
self.employee_base.append(employee)
employee.accept_offer(self)
...
# Employee
def accept_offer(self, company):
self.has_job = True
self.working_days = company.employee_working_days
self.bonus_percent = company.employee_bonus_percent
self.available_leaves = company.employee_leaves
self.salary_dollars = company.get_salary()
Same applies to employee_del_attr().
Field name id shadows built-in id() method and is not used anywhere.
Functions such as print_self_employees() that just print stuff are meant to be pure. You don't want to change anything just by looking at it, it's not quantum physics. Then again, self.employees is never used so there is no reason to update it in the first place. | {
"domain": "codereview.stackexchange",
"id": 44059,
"lm_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",
"url": null
} |
python, python-3.x
Title: Python list permutations in lexicographic order
Question: This code is about Lexicographic Ordering algorithms and its works but how can i change the style of the code to professional coding style?
from typing import List
def swap(_list: List, index1: int, index2: int):
_list[index1], _list[index2] = _list[index2], _list[index1]
return _list
def lexico_graphic(items: List):
paths = [items]
while True:
# step 1
largest_i = None
for i in range(len(items) - 1):
if items[i] < items[i + 1]:
largest_i = i
if largest_i is None:
return paths
# step 2
largest_j = 0
for j in range(len(items)):
if items[largest_i] < items[j]:
largest_j = j
# step 3
items = swap(items, largest_i, largest_j)
# step 4
items = items[:largest_i + 1] + items[:largest_i:-1]
paths.append(items)
thanks for your time
Answer: In Python objects are passed into functions by creating a reference that points to the same value, meaning that when you invoke your function swap() on list items, local _list refers to the exact same items object you passed in there. When you mutate _list in the next line (_list[index1], _list[index2] = _list[index2], _list[index1]) the underlying object changes, which means your function is no longer pure: you were trying to return a new list with 2 items swapped, but instead modified the original list.
If you don't want this function to mutate the original list you can write it like this:
def swap(_list: List, index1: int, index2: int):
new_list = _list[:] # equivalent to `_list.copy()`
new_list[index1], new_list[index2] = new_list[index2], new_list[index1]
return new_list | {
"domain": "codereview.stackexchange",
"id": 44060,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
As you can see the original list never changes.
If you instead wanted the function to mutate your list, you can get rid of the return statement:
def swap(_list: List, index1: int, index2: int):
_list[index1], _list[index2] = _list[index2], _list[index1]
and use it without the assignment:
swap(items, largest_i, largest_j)
# instead of
items = swap(items, largest_i, largest_j)
The algorithm looks fine, but naming may need some adjustments:
_list - underscores in python are used as access modifiers, this parameter can be named items for example
lexico_graphic - it's unclear what this function does by looking at its name | {
"domain": "codereview.stackexchange",
"id": 44060,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
c++, c++17
Title: Reservoir sampling Algorithm A-ExpJ for C++17
Question: Implementation of the Reservoir sampling algorithm A-ExpJ that allows sampling K random elements from a stream of elements according to their weights when we don't know the size of the stream in advance and don't have the memory to store all the elements of the stream.
Description of the algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling#Algorithm_A-ExpJ
I tried to make it as efficient time-wise as I could:
one allocation for all the data
not do anything if the object is not going to be added
the ability to construct objects in-place
not move objects while adding new ones
also tried to make it safe and support as many types as I could:
should work with custom arithmetic types as weights (bigint?), but not tested
should work with non-copyable and/or non-movable types
template<typename T, typename WeightType = float, typename URBG = std::mt19937, typename RandType = float>
class ReservoirSamplerWeighted
{
public:
ReservoirSamplerWeighted(size_t samplesCount, URBG&& rand = std::mt19937{std::random_device{}()})
: mSamplesCount(samplesCount)
, mRand(std::forward<URBG>(rand))
{
}
~ReservoirSamplerWeighted()
{
if (mData)
{
for (size_t i = 0; i < mAllocatedElementsCount; ++i)
{
mElements[i].~T();
}
for (size_t i = 0; i < mSamplesCount; ++i)
{
mQueuePrios[i].~RandType();
}
std::free(mData);
}
} | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_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++17",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.