text stringlengths 1 2.12k | source dict |
|---|---|
java, algorithm, array, comparative-review
Integer int2 =
linearTimeSelector.select(
array2,
k,
fromIndex,
toIndex);
assertEquals(int1, int2);
}
}
}
com.github.coderodde.algo.selection.LinearTimeSelectorTest.java:
package com.github.coderodde.algo.selection;
public class LinearTimeSelectorTest extends AbstractSelectorTest {
public LinearTimeSelectorTest() {
super(new LinearTimeSelector<>());
}
}
com.github.coderodde.algo.selection.RandomizedSelectorTest.java:
package com.github.coderodde.algo.selection;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
public class RandomizedSelectorTest extends AbstractSelectorTest {
public RandomizedSelectorTest() {
super(new RandomizedSelector<>());
}
@Test
public void partition() {
Integer[] array = { 2, 8, 7, 1, 3, 5, 6, 4 };
RandomizedSelector.partition(array, 0, array.length);
assertTrue(Arrays.equals(array, new Integer[] {
2, 1, 3, 4, 7, 5, 6, 8
}));
}
}
com.github.coderodde.algo.selection.SortingSelectorTest.java:
package com.github.coderodde.algo.selection;
public class SortingSelectorTest extends AbstractSelectorTest {
public SortingSelectorTest() {
super(new SortingSelector<>());
}
}
com.github.coderodde.algo.selection.SupportTest.java:
package com.github.coderodde.algo.selection;
import org.junit.Test;
public class SupportTest {
@Test(expected = IllegalArgumentException.class)
public void throwOnDuplicateElementInArray() {
Integer[] array = { 2, 3, 4, 5, 1, -1, 3 };
Support.checkArrayContainsNoDuplicatesElements(array);
}
@Test
public void passesOnNoDuplicateElementInArray() {
Integer[] array = { 2, 3, 4, 5, 1, -1 };
Support.checkArrayContainsNoDuplicatesElements(array);
}
} | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
com.github.coderodde.algo.selection.benchmark.SelectorBenchmark.java:
package com.github.coderodde.algo.selection.benchmark;
import com.github.coderodde.algo.selection.LinearTimeSelector;
import com.github.coderodde.algo.selection.RandomizedSelector;
import com.github.coderodde.algo.selection.Selector;
import com.github.coderodde.algo.selection.SortingSelector;
import com.github.coderodde.algo.selection.Support;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* This class implements the selector algorithm benchmark.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Sep 26, 2022)
* @since 1.6 (Sep 26, 2022)
*/
public final class SelectorBenchmark {
private static final int ARRAY_LENGTH = 10_000;
private static final int FROM_INDEX = 1000;
private static final int TO_INDEX = ARRAY_LENGTH - 1000;
private static final int MINIMUM_VALUE = -100_000;
private static final int MAXIMUM_VALUE = 100_000;
public static void main(String[] args) {
long seed = System.currentTimeMillis();
Random random = new Random(seed);
System.out.println("seed = " + seed);
Integer[] array1 =
Support.getArray(
random,
ARRAY_LENGTH,
MINIMUM_VALUE,
MAXIMUM_VALUE);
Integer[] array2 = array1.clone();
Integer[] array3 = array1.clone();
Selector<Integer> selector1 = new SortingSelector<>();
Selector<Integer> selector2 = new LinearTimeSelector<>();
Selector<Integer> selector3 = new RandomizedSelector<>();
List<Integer> results1 = warmup(selector1,
array1,
FROM_INDEX,
TO_INDEX); | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
List<Integer> results2 = warmup(selector2,
array2,
FROM_INDEX,
TO_INDEX);
List<Integer> results3 = warmup(selector3,
array3,
FROM_INDEX,
TO_INDEX);
if (results1.equals(results2) && results2.equals(results3)) {
System.out.println("Algorithms agreed on warmup.");
}
results1 = benchmark(selector1, array1, FROM_INDEX, TO_INDEX);
results2 = benchmark(selector2, array2, FROM_INDEX, TO_INDEX);
results3 = benchmark(selector3, array3, FROM_INDEX, TO_INDEX);
if (results1.equals(results2) && results2.equals(results3)) {
System.out.println("Algorithms agreed on benchmark.");
}
}
private static List<Integer> warmup(Selector<Integer> selector,
Integer[] array,
int fromIndex,
int toIndex) {
return run(selector, array, fromIndex, toIndex, false);
}
private static List<Integer> benchmark(Selector<Integer> selector,
Integer[] array,
int fromIndex,
int toIndex) {
return run(selector, array, fromIndex, toIndex, true);
}
private static List<Integer> run(Selector<Integer> selector,
Integer[] array,
int fromIndex,
int toIndex,
boolean print) {
List<Integer> results = new ArrayList<>(toIndex - fromIndex);
long duration = 0L; | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
List<Integer> results = new ArrayList<>(toIndex - fromIndex);
long duration = 0L;
for (int k = 0; k < toIndex - fromIndex; k++) {
shuffle(array, fromIndex, toIndex);
long startTime = System.currentTimeMillis();
results.add(selector.select(array, k, fromIndex, toIndex));
long endTime = System.currentTimeMillis();
duration += endTime - startTime;
}
if (print) {
System.out.println(
selector.getClass().getSimpleName()
+ " in "
+ duration
+ " milliseconds.");
}
return results;
}
private static <E> void shuffle(E[] array, int fromIndex, int toIndex) {
Random random = new Random();
List<E> list = new ArrayList<>(toIndex - fromIndex);
for (int i = fromIndex; i < toIndex; i++) {
list.add(array[i]);
}
Collections.shuffle(list, random);
for (int i = fromIndex; i < toIndex; i++) {
array[i] = list.get(i - fromIndex);
}
}
}
The typical output on my PC is:
seed = 1664257975649
Algorithms agreed on warmup.
SortingSelector in 9708 milliseconds.
LinearTimeSelector in 6910 milliseconds.
RandomizedSelector in 1432 milliseconds.
Algorithms agreed on benchmark.
Critique request
Is there any way to improve the code?
Answer: (I'm no fan of final for interfaces and classes, this seems to carry to sealed.)
one alternative to specifying <E extends Comparable<? super E>> was to accept a Comparator
- I guess that would have been beside the point of comparing algorithms, and complicating implementation. | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
defines the API for the selection algorithms is a laudable promise - I don't see com.github.coderodde.algo.selection.Selector live up to it:
• Will the contents of array stay unchanged, permuted, some values overwritten with others, or worse?
• Does k-smallest refer to [fromIndex, toIndex) or to all of array, with the implication all elements in [0, fromIndex) are smaller?
I see three implementations of select(E[] array, int k) in terms of select(array, k, fromIndex, toIndex) - and three inconsistent instances of parameter checking:
Selector could have provided a default implementation.
I guess this is one of the occasions where I'd prefer an abstract class for being able to provide final methods:
public abstract class Selector<E extends Comparable<? super E>> {
/** @param array likely to be permuted
@return a smallest element of <code>array</code> from <code>fromIndex</code>
to <code>toIndex</code> (exclusive) such that <code>k</code>
elements in range are no greater than it. */
protected abstract E permuting(E[] array, int k, int fromIndex, int toIndex);
/** @param array may be permuted
@return a smallest element of <code>array</code> from <code>fromIndex</code>
to <code>toIndex</code> (exclusive) such that <code>k</code>
elements in range are no greater than it. */
public final E select_permuting(E[] array, int k, int fromIndex, int toIndex) {
checkArray(array);
checkRangeIndices(fromIndex, toIndex);
if (0 == k)
return Collections.min(Arrays.asList(array).subList(fromIndex, toIndex));
if (k == toIndex - 1)
return Collections.max(Arrays.asList(array).subList(fromIndex, toIndex));
checkK(toIndex - fromIndex, k);
return permuting(array, k, fromIndex, toIndex);
} | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
/** @param array will not be modified
@return a smallest element of <code>array</code> from <code>fromIndex</code>
to <code>toIndex</code> (exclusive) such that <code>k</code>
elements in range are no greater than it. */
public final E select(E[] array, int k, int fromIndex, int toIndex) {
checkArray(array);
E[] range = Arrays.copyOfRange(array, fromIndex, toIndex);
return select_permuting(range, k, 0, range.length);
}
/** @param array will not be modified
@return an element of <code>array</code> such that <code>k</code>
elements are smaller than or equal to it. */
public final E select(E[] array, int k) {
checkArray(array);
return select_permuting(array.clone(), k, 0, array.length);
}
}
(When successfully defining a suitable
/** @param array will be permuted such that <code>k</code>
elements in range no greater than the
<code>k</code>th are at the beginning of the range
@return ???
*/
protected abstract ??? partition(E[] array, int k, int fromIndex, int toIndex);
, I'd add a final implementation of select_permuting(array, k, fromIndex, toIndex) using that.)
LinearTimeSelector
irritatingly introduces another interpretation of k in selectImpl()
(without documenting index).
creates a lot of arrays.
Once leftArrayLength and rightArrayLength are known, copy just the appropriate number of elements to an array created at the first partition and passed down from there if not wanting to modify array. | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
java, algorithm, array, comparative-review
I always found pivot selection in median-of-five-quickselect somewhat aloft:
It should be possible to establish bounds for the other "next level medians", not just the middle one in median-of-five.
If k was smaller(greater) than the lower(upper) limit for the 1st or 2nd(last or 4th) median, pick that as the pivot.
(Hardly much use: for sizeable samples, medians can be expected to be close. Small multisets better be handled differently altogether.) | {
"domain": "codereview.stackexchange",
"id": 43923,
"lm_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, algorithm, array, comparative-review",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
Title: Transliterate between Cyrillic and Latin scripts
Question: I want to get a code review on the following transliteration code. I wrote it because there were some libraries that I have tried and they were specifically failing with the name "Yuliya" from Latin to Cyrillic. I wrote unit tests for my functions.
Things I noticed:
I don't need it to support both standards GOST 16876-71 and ISO 9-95, because I would use it to transliterate from/to Bulgarian and if you pay attention to CyrillicLowercase and LatinLowercase, it's a bit different than these standards.
Having CyrillicUppercase and CyrillicLowercase separately is not great. I believe this snippet solves it. I mean it doesn't have 4x const strings like I do, which is much better. It puts.ToLower() and .ToUpper() in the code.
you might ask why I did .OrderByDescending(x => x.Value.Length) specifically for LatinToCyrillic and the reason is because if you transliterate the name "Yuliya Koleva Hadzhiivanova" (Latin to Cyrillic), it won't think of Yu as a whole, instead it will think of it as Y and u, which would result in "Иулия..." instead of "Юлия...", which is wrong. I found that solution in this code and used it.
I used .Aggregate and this code uses .Replace. Which one is more optimal?
public sealed class Transliteration
{
private const string CyrillicLowercase = "а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ь ю я";
private const string CyrillicUppercase = "А Б В Г Д Е Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ь Ю Я";
private const string LatinLowercase = "a b v g d e zh z i y k l m n o p r s t u f h ts ch sh sht a y yu ya";
private const string LatinUppercase = "A B V G D E Zh Z I Y K L M N O P R S T U F H Ts Ch Sh Sht A Y Yu Ya";
private readonly Dictionary<string,string> _dict;
private Transliteration()
{
_dict = new Dictionary<string, string>();
} | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
private Transliteration()
{
_dict = new Dictionary<string, string>();
}
private Transliteration(Dictionary<string, string> dict)
{
ArgumentNullException.ThrowIfNull(dict);
_dict = dict;
}
public static Transliteration Create()
{
var lowercaseDict = CyrillicLowercase.Split(' ')
.Zip(LatinLowercase.Split(' '), (k, v) => new { k, v })
.ToDictionary(x => x.k, x => x.v);
var uppercaseDict = CyrillicUppercase.Split(' ')
.Zip(LatinUppercase.Split(' '), (k, v) => new { k, v })
.ToDictionary(x => x.k, x => x.v);
var both = lowercaseDict.Concat(uppercaseDict)
.ToLookup(x => x.Key, x => x.Value)
.ToDictionary(x => x.Key, g => g.First());
return new Transliteration(both);
}
/// <summary>
/// Transliterates cyrillic text to latin.
/// </summary>
/// <param name="text">The text to be transliterated.</param>
/// <returns>The transliterated text.</returns>
public string CyrillicToLatin(string text)
{
return _dict.Aggregate(text, (current, pair) => current.Replace(pair.Key, pair.Value));
}
/// <summary>
/// Transliterates latin text to cyrillic.
/// </summary>
/// <param name="text">The text to be transliterated.</param>
/// <returns>The transliterated text.</returns>
public string LatinToCyrillic(string text)
{
return _dict.OrderByDescending(x => x.Value.Length).Aggregate(text, (current, pair) => current.Replace(pair.Value, pair.Key));
}
}
xUnit
public class TransliterationTests
{
private readonly Transliteration _transliteration;
public TransliterationTests()
{
_transliteration = Transliteration.Create();
}
[Fact]
public void CyrillicToLatinTextShouldEqualTheirEqual()
{
// Arrange | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
// Act
var actual = _transliteration.CyrillicToLatin("Юлия Колева Хаджииванова");
// Assert
actual.Should().Be("Yuliya Koleva Hadzhiivanova");
}
[Fact]
public void LatinToCyrillicTextShouldEqualTheirEqual()
{
// Arrange
// Act
var actual = _transliteration.LatinToCyrillic("Yuliya Koleva Hadzhiivanova");
// Assert
actual.Should().Be("Юлия Колева Хаджииванова");
}
}
Answer: Dynamic vs Static lookup table
You are recreating each and every time the same lookup table whenever someone calls the Create method
This is unnecessary since you can do it only once and without using linq
new Dictionary<char, string>
{
{ 'а', "a"}, { 'А', "A"},
{ 'б', "b"}, { 'Б', "B"},
{ 'в', "v"}, { 'В', "V"},
{ 'г', "g"}, { 'Г', "G"},
{ 'д', "d"}, { 'Д', "D"},
{ 'е', "e"}, { 'Е', "E"},
{ 'ж', "zh"}, { 'Ж', "Zh"},
{ 'з', "z"}, { 'З', "Z"},
{ 'и', "i"}, { 'И', "I"},
{ 'й', "y"}, { 'Й', "Y"},
{ 'к', "k"}, { 'К', "K"},
{ 'л', "l"}, { 'Л', "L"},
{ 'м', "m"}, { 'М', "M"},
{ 'н', "n"}, { 'Н', "N"},
{ 'о', "o"}, { 'О', "O"},
{ 'п', "p"}, { 'П', "P"},
{ 'р', "r"}, { 'Р', "R"},
{ 'с', "s"}, { 'С', "S"},
{ 'т', "t"}, { 'Т', "T"},
{ 'у', "u"}, { 'У', "U"},
{ 'ф', "f"}, { 'Ф', "F"},
{ 'х', "h"}, { 'Х', "H"},
{ 'ц', "ts"}, { 'Ц', "Ts"},
{ 'ч', "ch"}, { 'Ч', "Ch"},
{ 'ш', "sh"}, { 'Ш', "Sh"},
{ 'щ', "sht"}, { 'Щ', "Sht"},
{ 'ъ', "a"}, { 'Ъ', "A"},
{ 'ь', "y"}, { 'Ь', "Y"},
{ 'ю', "yu"}, { 'Ю', "Yu"},
{ 'я', "ya"}, { 'Я', "Ya"},
{ ' ', " " }
}
I've also added one extra mapping (space -> space)
Immutability
In your version you have used a const string which is immutable
In my version if I declare a field like this static readonly Dictionary<char, string> then the reference is immutable but the collection itself is mutable | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
In order to make the collection immutable we can use the ToImmutableDictionary builder method
private static readonly ImmutableDictionary<char, string> cyrillicToLatinMapping = new Dictionary<char, string>
{
{ 'а', "a"}, { 'А', "A"},
{ 'б', "b"}, { 'Б', "B"},
{ 'в', "v"}, { 'В', "V"},
{ 'г', "g"}, { 'Г', "G"},
{ 'д', "d"}, { 'Д', "D"},
{ 'е', "e"}, { 'Е', "E"},
{ 'ж', "zh"}, { 'Ж', "Zh"},
{ 'з', "z"}, { 'З', "Z"},
{ 'и', "i"}, { 'И', "I"},
{ 'й', "y"}, { 'Й', "Y"},
{ 'к', "k"}, { 'К', "K"},
{ 'л', "l"}, { 'Л', "L"},
{ 'м', "m"}, { 'М', "M"},
{ 'н', "n"}, { 'Н', "N"},
{ 'о', "o"}, { 'О', "O"},
{ 'п', "p"}, { 'П', "P"},
{ 'р', "r"}, { 'Р', "R"},
{ 'с', "s"}, { 'С', "S"},
{ 'т', "t"}, { 'Т', "T"},
{ 'у', "u"}, { 'У', "U"},
{ 'ф', "f"}, { 'Ф', "F"},
{ 'х', "h"}, { 'Х', "H"},
{ 'ц', "ts"}, { 'Ц', "Ts"},
{ 'ч', "ch"}, { 'Ч', "Ch"},
{ 'ш', "sh"}, { 'Ш', "Sh"},
{ 'щ', "sht"}, { 'Щ', "Sht"},
{ 'ъ', "a"}, { 'Ъ', "A"},
{ 'ь', "y"}, { 'Ь', "Y"},
{ 'ю', "yu"}, { 'Ю', "Yu"},
{ 'я', "ya"}, { 'Я', "Ya"},
{ ' ', " " }
}.ToImmutableDictionary();
Cyrillic 2 Latin
With this dictionary in our hand the translation is quite an easy task
string.Join("", text.ToCharArray().Select(c => cyrillicToLatinMapping[c])
First convert the text to a character array
Then loop through the array and do a lookup in a lookup table
Finally concatenate the looked up strings
Order by latin mappings' length
Yet again rather than doing this (re)ordering every time when someone calls the LatinToCyrillic method you can do it only once
private static readonly ImmutableArray<(string Latin, char Cyrillic)> latinToCyrillicMapping =
cyrillicToLatinMapping
.OrderByDescending(v => v.Value.Length)
.Select(d => (Latin: d.Value, Cyrillic: d.Key))
.ToImmutableArray(); | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
Here we can't simple swap the Key and Value and still use a Dictionary to store the result (.ToImmutableDictionary(d => d.Value, d => d.Key)
Rather we could create an array with named ValueTuples
Latin 2 Cyrillic
With the above array in our hand the translation can be done like this
int startIdx = 0;
StringBuilder accumulator = new();
while (startIdx != text.Length)
{
foreach (var (latin, cyrillic) in latinToCyrillicMapping)
{
if (text[startIdx..].StartsWith(latin))
{
accumulator.Append(cyrillic);
startIdx += latin.Length;
break;
}
}
}
return accumulator.ToString();
Here iterate through the text by moving a pointer
The pointer points to the next character which has not been translated yet
Since we have ordered latinToCyrillicMapping that's why we try to match (StartsWith) first the three letters long strings then the two letters long strings and finally the single letter long strings
Whenever we have found a match then we add the translation to the accumulator and move the pointer accordingly | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
For the sake of completeness here is the fully rewritten version of your Transliteration class
public static class Transliteration
{
private static readonly ImmutableDictionary<char, string> cyrillicToLatinMapping = new Dictionary<char, string>
{
{ 'а', "a"}, { 'А', "A"},
{ 'б', "b"}, { 'Б', "B"},
{ 'в', "v"}, { 'В', "V"},
{ 'г', "g"}, { 'Г', "G"},
{ 'д', "d"}, { 'Д', "D"},
{ 'е', "e"}, { 'Е', "E"},
{ 'ж', "zh"}, { 'Ж', "Zh"},
{ 'з', "z"}, { 'З', "Z"},
{ 'и', "i"}, { 'И', "I"},
{ 'й', "y"}, { 'Й', "Y"},
{ 'к', "k"}, { 'К', "K"},
{ 'л', "l"}, { 'Л', "L"},
{ 'м', "m"}, { 'М', "M"},
{ 'н', "n"}, { 'Н', "N"},
{ 'о', "o"}, { 'О', "O"},
{ 'п', "p"}, { 'П', "P"},
{ 'р', "r"}, { 'Р', "R"},
{ 'с', "s"}, { 'С', "S"},
{ 'т', "t"}, { 'Т', "T"},
{ 'у', "u"}, { 'У', "U"},
{ 'ф', "f"}, { 'Ф', "F"},
{ 'х', "h"}, { 'Х', "H"},
{ 'ц', "ts"}, { 'Ц', "Ts"},
{ 'ч', "ch"}, { 'Ч', "Ch"},
{ 'ш', "sh"}, { 'Ш', "Sh"},
{ 'щ', "sht"}, { 'Щ', "Sht"},
{ 'ъ', "a"}, { 'Ъ', "A"},
{ 'ь', "y"}, { 'Ь', "Y"},
{ 'ю', "yu"}, { 'Ю', "Yu"},
{ 'я', "ya"}, { 'Я', "Ya"},
{ ' ', " " }
}.ToImmutableDictionary();
private static readonly ImmutableArray<(string Latin, char Cyrillic)> latinToCyrillicMapping =
cyrillicToLatinMapping
.OrderByDescending(v => v.Value.Length)
.Select(d => (Latin: d.Value, Cyrillic: d.Key))
.ToImmutableArray();
public static string CyrillicToLatin(string text)
=> string.Join("", text.ToCharArray().Select(c => cyrillicToLatinMapping[c])); | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c#, .net, unit-testing, hash-map, linq
public static string LatinToCyrillic(string text)
{
int startIdx = 0;
StringBuilder accumulator = new();
while (startIdx != text.Length)
{
foreach (var (latin, cyrillic) in latinToCyrillicMapping)
{
if (text[startIdx..].StartsWith(latin))
{
accumulator.Append(cyrillic);
startIdx += latin.Length;
break;
}
}
}
return accumulator.ToString();
}
}
UPDATE #1
In this case J is a char that cannot be found at LatinToCyrillicMapping and it is running in an infinite loop. I want to throw an exception instead of running in an infinite loop
var prevStartIdx = startIdx;
foreach (var (latin, cyrillic) in latinToCyrillicMapping)
{
if (text[startIdx..].StartsWith(latin))
{
accumulator.Append(cyrillic);
startIdx += latin.Length;
break;
}
}
if (prevStartIdx == startIdx)
throw new NotSupportedException("...");
So, here we basically check whether or not the startIdx has advanced if not then throw an exception
UPDATE #2
text[startIdx..] allocates substring for each letter.
Use text.AsSpan() and then Slice() it
The modified code:
var textSpan = text.AsSpan();
...
var prevStartIdx = startIdx;
foreach (var (latin, cyrillic) in latinToCyrillicMapping)
{
if (textSpan.Slice(startIdx).StartsWith(latin))
{
accumulator.Append(cyrillic);
startIdx += latin.Length;
break;
}
}
if (prevStartIdx == startIdx)
throw new NotSupportedException("..."); | {
"domain": "codereview.stackexchange",
"id": 43924,
"lm_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, unit-testing, hash-map, linq",
"url": null
} |
c++, multithreading, multiprocessing
Title: Timeit multithreading/multiprocessing C++
Question: Given a Timeit method which runs for n times the provided function, which approach between multithreading and multiprocessing should be better to speed up the execution of all iterations and avoid the loop? Multithreading would be memory safe? What would be a pseudo code of the implementation? Thanks in advance
typedef std::chrono::milliseconds milliseconds;
struct Result {
milliseconds m_min;
milliseconds m_max;
milliseconds m_avg;
milliseconds m_sum;
Result(milliseconds min, milliseconds max, milliseconds avg,
milliseconds sum)
: m_min(min), m_max(max), m_avg(avg), m_sum(sum) {};
};
template<typename Function, typename ... Args>
Result Timeit(uint16_t iters, bool verbose, Function& f, Args&& ... args) noexcept(false) {
if (iters < 1) throw std::runtime_error("Iters must be >= 1.");
typedef std::chrono::time_point<std::chrono::high_resolution_clock> time_point;
typedef std::vector<std::chrono::milliseconds> Clocks;
Clocks clocks;
clocks.reserve(iters);
for (int it = 0; it < iters; it++) {
time_point t0 = std::chrono::high_resolution_clock::now();
f(std::forward<Args>(args)...);
time_point t1 = std::chrono::high_resolution_clock::now();
clocks.emplace_back(
std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count());
}
milliseconds max = *std::max_element(clocks.begin(), clocks.end());
milliseconds min = *std::min_element(clocks.begin(), clocks.end());
milliseconds sum = std::accumulate(clocks.begin(), clocks.end(), milliseconds(0));
milliseconds avg = sum / clocks.size(); | {
"domain": "codereview.stackexchange",
"id": 43925,
"lm_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++, multithreading, multiprocessing",
"url": null
} |
c++, multithreading, multiprocessing
if (verbose) {
std::cout << "=======================================================================\n";
std::cout << "=========================== SHOW TIMEIT RESULTS =======================\n";
std::cout << "=======================================================================\n\n";
std::cout << "\tIterations completed\t: " << iters << "\n";
std::cout << "\tTotal milliseconds\t: " << sum << "\n";
std::cout << "\tAverage milliseconds\t: " << avg << "\n";
std::cout << "\tMaxima milliseconds\t: " << max << "\n";
std::cout << "\tMinima milliseconds\t: " << min << "\n\n\n";
}
return Result(min, max, avg, sum);
}
Answer: Prefer using over typedef
using declarations are a bit easier to read than typedefs, especially when it comes to making aliases for function pointers or arrays.
Don't create type aliases unnecessarily; Clocks is used only once, so nothing was gained by making that an alias. Also, often you can avoid having to write a type explicitly by using auto.
Naming things
clocks sounds like it is storing clocks... but it is actually storing durations, so durations would be a better name.
Result is a very generic name, which could cause conflicts: consider that some other function might want to return a result in a struct. To solve this, either make sure the name is unique, like TimeitResult, or put everything in a namespace, which itself should have a unique enough name.
Store durations in the clock's own resolution
By using std::chrono::milliseconds to store durations, you are losing precision unnecessarily. Consider the case where one invocation of f() completes in less than one millisecond. It's better to not specify a fixed time resolution at all, but store time in the clock's native resolution:
using clock = std::chrono::high_resolution_clock;
using duration = clock::duration; | {
"domain": "codereview.stackexchange",
"id": 43925,
"lm_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++, multithreading, multiprocessing",
"url": null
} |
c++, multithreading, multiprocessing
struct Result {
duration min;
duration max;
duration avg;
duration sum;
};
Only convert to milliseconds when you actually need to print the values:
std::vector<duration> durations;
...
auto t0 = clock::now();
f(std::forward<Args(args)...);
auto t1 = clock::now();
durations.emplace_back(t1 - t0);
...
std::cout << "\tTotal milliseconds\t: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(sum).count() << "\n";
Note that it might be better to use std::chrono::steady_clock than std::chrono::high_resolution_clock; it's not guaranteed that the latter is monotonic.
Don't pass functions by (const) reference
You are passing f by reference, however this will prevent you from writing:
Timeit(1, true, []{});
Passing by const reference would solve this case, but would be problematic if the function passed in requires it to be mutable. So pass functions either by value or by rvalue reference.
Use std::minmax_element()
If you need both the minimum and maximum of a range, use std::minmax_element(). Since your code requires C++20, you can use std::ranges::minmax_element() and structured bindings to simply write:
auto [min, max] = std::ranges::minmax_element(clocks);
Don't let Timeit() print the results
Your Timeit() both performs timing measurements and handles printing the results to std::cout. This complicates the function, and it's inflexible: what if you want to print the results to a file instead? What if you want to print it to both std::cout and a file?
The solution is to not let Timeit() handle printing of the results at all. Instead, consider creating a friend ostream& operator<<() that will format a Result. If you want the "verbose" behaviour, the caller can then simply do:
std::cout << Timeit(...); | {
"domain": "codereview.stackexchange",
"id": 43925,
"lm_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++, multithreading, multiprocessing",
"url": null
} |
c++, multithreading, multiprocessing
Other things to think about
Why is iters a 16-bit integer? What if you have a very fast function that you want to run a million times? I suggest you use a std::size_t instead for the number of iterations. Also make sure that the iteration variable it has the same type as iters.
If you don't know how fast a function is going to be, it's hard to come up with a value of iters that is large enough to get good statistics but not too large that it takes forever to run. However, you could let Timeit() figure out how many times to run the functions, for example by running it once and checking the time it took, and then calculating how many times it needs to run it so it runs for a small number of seconds.
The first time you run a function it might run quite slow because the caches are cold, the branch predictors have not seen anything to predict yet, and there are many other things that can take longer the first time. In fact, you might need to run the function many times before everything is warmed up. So ideally Timeit() should first do a dummy loop before doing the actual loop of iters iterations.
Multithreading
Given a Timeit method which runs for n times the provided function, which approach between multithreading and multiprocessing should be better to speed up the execution of all iterations and avoid the loop?
It's hard to say what the best approach would be. It would heavily depend on whether the provided function is meant to run in parallel in the same process or in separate processes.
Multithreading would be memory safe?
That again depends on the provided function. If it's not thread-safe, you obviously cannot run it in several threads at once.
What would be a pseudo code of the implementation? | {
"domain": "codereview.stackexchange",
"id": 43925,
"lm_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++, multithreading, multiprocessing",
"url": null
} |
c++, multithreading, multiprocessing
What would be a pseudo code of the implementation?
That's not how it works here on Code Review; you provide a fully working implementation and we review it. And again, it depends on the provided function what the best way to run it is so you get realistic results.
However, if the function is thread-safe, then probably your best option would be to implement a thread pool, and then schedule iters executions of the provided function on the thread pool. | {
"domain": "codereview.stackexchange",
"id": 43925,
"lm_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++, multithreading, multiprocessing",
"url": null
} |
javascript, node.js
Title: Function that querys database and then renders a view
Question: Im new at backend development and I'm noticing that my code is very messy and difficult to read. I know this doesn't have a single correct answer but id like to know how I can make my code tidier when I have so many queries and const definitions. Thank you!
I have this piece of code from a function that retrieves data from db and then renders a view. Im trying not to use ORMs so I can learn SQL better.
show_consorcio_controllers.render_show_consorcio = async (req, res) => {
const id_consorcio = req.params.id_consorcio;
const user_id = req.session.passport.user;
const consorcios = await connection.query("SELECT id FROM consorcios WHERE id_consorcio = ?", id_consorcio);
const id_admin_del_consorcio = consorcios[FIRST_POSITION].id;
if(id_admin_del_consorcio === user_id) {
const consorcio_info = await connection.query("SELECT * FROM consorcios WHERE id_consorcio = ? and id = ?", [id_consorcio, user_id]);
const consorcio = consorcio_info[FIRST_POSITION];
const orden_ingresos_egresos = consorcio.order_egresos_ingresos_by;
let fecha_de_muestra_final = moment(consorcio.fecha_de_muestra_final).format("YYYY/MM/DD");
let fecha_de_muestra_inicial = moment(consorcio.fecha_de_muestra_inicial).format("YYYY/MM/DD");
const user = await connection.query("SELECT nombre FROM usuarios WHERE id = ?", user_id);
const {nombre} = user[FIRST_POSITION]; | {
"domain": "codereview.stackexchange",
"id": 43926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
javascript, node.js
const expensas = await connection.query("SELECT unidad_funcional, mes_periodo, anio_periodo, id_expensa, id_consorcio, titulo, monto_total, fecha FROM expensas WHERE id_consorcio = ? AND id_admin = ?", [id_consorcio, user_id]);
const { ingresos, egresos } = await show_consorcio_controllers.get_ingresos_egresos(orden_ingresos_egresos, id_consorcio, fecha_de_muestra_inicial, fecha_de_muestra_final, user_id);
const proveedores = await connection.query("SELECT id, nombre, apellido FROM proveedores WHERE id_admin = ?", user_id);
show_consorcio_controllers.normalize_dates(ingresos);
show_consorcio_controllers.normalize_dates(egresos);
const unidades_funcionales = await connection.query("SELECT * FROM unidades_funcionales WHERE id_consorcio = ? AND id_admin = ?", [id_consorcio, user_id]);
fecha_de_muestra_final = moment(consorcio.fecha_de_muestra_final).format("DD/MM/YYYY");
fecha_de_muestra_inicial = moment(consorcio.fecha_de_muestra_inicial).format("DD/MM/YYYY");
res.render("consorcio/show_consorcio", {expensas, unidades_funcionales, proveedores, id: user_id, nombre, id_consorcio, ingresos, egresos, orden_ingresos_egresos, fecha_de_muestra_inicial, fecha_de_muestra_final, consorcio});
} else {
res.send("No esta permitido el acceso a esta pagina");
}
};
Answer: Test for invalid state up front
Eliminating branching simplifies. The high level reads in a more consistant general
abstraction level.
if (! id_admin_del_consorcio === user_id) {
res.send("No esta permitido el acceso a esta pagina");
return;
}
// all that code ...
res.render("consorcio/show_consorcio", {expensas, unidades_funcionales, proveedores, id: user_id, nombre, id_consorcio, ingresos, egresos, orden_ingresos_egresos, fecha_de_muestra_inicial, fecha_de_muestra_final, consorcio}); | {
"domain": "codereview.stackexchange",
"id": 43926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
javascript, node.js
Create Consorcios object
Very confusing: Currently there are two variables named "consorcios" but in different scopes. Then everything
seems to have "consorcios" in the name. Make an object to manage that. Consorcios object properties should not have "consorcios" in their names.
Pass res, req as parameters
Make the queries into Object methods. Probably still need to pre-populate these.
Pre populate in the constructor. Necessary call order is guaranteed and all in one place. And the rest of the code will be cleaner.
pass method parameters so we do not need to read all that SQL.
Make object methods for the variables.
fecha_de_muestra_final
fecha_de_muestra_inicial
{nombre} ... possibly does not need to be a formal Object
{ ingresos, egresos } ... possibly does not need to be a formal Object
that inner scope const consorcio
... and so on.
Call the methods when they are used. Don't pre-assign a separate variable. | {
"domain": "codereview.stackexchange",
"id": 43926,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, node.js",
"url": null
} |
c, integer, bitwise, serialization, portability
Title: Portable integer to/from little endian conversion in C
Question: Integers need to be converted to a byte array of defined endianness to be reliably and consistently saved and transmitted, and converted back to be accurately received and read. The goal is to be as portable as possible, while maintaining concise and fast code.
#ifndef LE_h
#define LE_h
#include <stdint.h>
inline static uint16_t le16(const uint8_t b[const static 2]) {
return b[0]|(uint16_t)b[1]<<8;
}
inline static uint32_t le32(const uint8_t b[const static 4]) {
return le16(b)|(uint32_t)le16(b+2)<<16;
}
inline static uint64_t le64(const uint8_t b[const static 8]) {
return le32(b)|(uint64_t)le32(b+4)<<32;
}
inline static void le16b(uint8_t b[const static 2], const uint16_t n) {
b[0] = n;
b[1] = n>>8;
}
inline static void le32b(uint8_t b[const static 4], const uint32_t n) {
le16b(b, n);
le16b(b+2, n>>16);
}
inline static void le64b(uint8_t b[const static 8], const uint64_t n) {
le32b(b, n);
le32b(b+4, n>>32);
}
#endif /* LE_h */
Answer:
The goal is to be as portable as possible, while maintaining concise and fast code. | {
"domain": "codereview.stackexchange",
"id": 43927,
"lm_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, integer, bitwise, serialization, portability",
"url": null
} |
c, integer, bitwise, serialization, portability
Answer:
The goal is to be as portable as possible, while maintaining concise and fast code.
Why little?
"to a byte array of defined endianness", is a good goal. I think little is more correct, yet big endian tends to be, though not universally, the preferred endian. I'd offer users both LE and BE routines.
Signed types?
Endian issues apply to signed types too. I'd expect le16signed() and friends.
Note: Floating point has endian issues and a whole lot more encoding ones too.
Standard integer types?
For intercommunication, fixed width types are preferred, yet such a LE package would be nice if extended to include LE routine for short, int, ..., intmax_t.
(u)intN_t types are optional
A compliant compiler only needs to implement them if the corresponding type is available without padding. Consider the case of CHAR_BIT == 9, or CHAR_BIT == 16.
To port to such rare machines, the interface needs re-design. Perhaps use (u)int_leastN_t types.
Or simply add a #if CHAR_BIT != 8 #error ....
Older compilers
b[const static 2] is not valid on older compilers (of course then maybe not inline). On such, could use *b instead and/or no inline.
At least consider gracefully detecting the required version and #error when not met.
No UB seen
Good.
Pedantic warnings
Some compilers may warn about type narrowing:
b[0] = n;
// alternative
b[0] = (uint8_t) n;
Unneeded const
Style issue: the 2nd const is not needed (and IMO distracting). Unsure about the usefulness of the first const.
// vvvvv
inline static void le16b(uint8_t b[const static 2], const uint16_t n) { | {
"domain": "codereview.stackexchange",
"id": 43927,
"lm_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, integer, bitwise, serialization, portability",
"url": null
} |
java, parsing
Title: Parse a text file, and map to an out-of-scope POJO
Question: I need to parse a file, with a standard formatting:
200 lines of uninteresting data
=====================================================================
Column(s)
=====================================================================
Column Description : HP-PONA
Inventory# : autoID-1
Diameter : 200.0 µm
Length : 50.0 m
The data must be outputted to a POJO outside of the project scope (i.e. I cannot change the POJO definition - ColumnInnerDiameter and ChromatographyColumnLength could/should be the same class or inherit for the same base class, but I cannot change this.):
public class ChromatographyColumnDocument {
private ChromatographyColumnLength chromatographyColumnLength;
private ColumnInnerDiameter columnInnerDiameter;
public ChromatographyColumnLength getChromatographyColumnLength() {
return chromatographyColumnLength;
}
public void setChromatographyColumnLength(ChromatographyColumnLength
chromatographyColumnLength) {
this.chromatographyColumnLength = chromatographyColumnLength;
}
public ColumnInnerDiameter getColumnInnerDiameter() {
return columnInnerDiameter;
}
public void setColumnInnerDiameter(ColumnInnerDiameter columnInnerDiameter) {
this.columnInnerDiameter = columnInnerDiameter;
}
}
public class ColumnInnerDiameter {
private Double value;
private String unit;
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
public class ChromatographyColumnLength{
private Double value;
private String unit;
public Double getValue() {
return value;
} | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
Finally, the code under review:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ColumnInformationMapper {
private ColumnInformationMapper() {
throw new IllegalStateException("Utility class");
}
private static final String valueAndUnitPattern = "([\\d|\\.]*) (\\S*)";
public static ChromatographyColumnDocument readColumnDocumentFromFile(String folderPath) throws Exception {
String line;
ChromatographyColumnDocument columnDocument = new ChromatographyColumnDocument();
File file = new File(folderPath,"acq.txt");
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), StandardCharsets.UTF_16))){
/* Looking for pattern
=====================================================================
Column(s)
=====================================================================
Column Description : HP-PONA
*/
while ((line = br.readLine()) != null) {
if (line.contains("======")) {
line = br.readLine();
if (line.contains("Column(s)")) {
br.readLine();// === line
br.readLine();// empty line
break;
}
}
}
br.readLine(); //Column Description - Not in model
br.readLine(); //Inventory # - Not in model | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
columnDocument.setColumnInnerDiameter(parseColumnInnerDiameter(
StringUtils.substringAfterLast(br.readLine(), ":").trim())); //Column diameter
columnDocument.setChromatographyColumnLength(parseColumnLength(
StringUtils.substringAfterLast(br.readLine(), ":").trim())); //Column length
return columnDocument;
}
}
private static ColumnInnerDiameter parseColumnInnerDiameter(String inputString) {
Pattern p = Pattern.compile(valueAndUnitPattern);
Matcher m = p.matcher(inputString);
if (m.find()) {
ColumnInnerDiameter columnInnerDiameter = new ColumnInnerDiameter();
columnInnerDiameter.setValue(Double.parseDouble(m.group(1)));
columnInnerDiameter.setUnit(m.group(2));
return columnInnerDiameter;
}
throw new NumberFormatException();
}
private static ChromatographyColumnLength parseColumnLength(String inputString) {
Pattern p = Pattern.compile(valueAndUnitPattern);
Matcher m = p.matcher(inputString);
if (m.find()) {
ChromatographyColumnLength columnLength = new ChromatographyColumnLength();
columnLength.setValue(Double.parseDouble(m.group(1)));
columnLength.setUnit(m.group(2));
return columnLength;
}
throw new NumberFormatException();
}
}
My questions:
To skip a line I am not interested in, I use readLine() and just don't use the results. SonarQube is very mad at this, and calls it a Major Bug: "When a method is called that returns data read from some data source, that data should be stored rather than thrown away. Any other course of action is surely a bug.". Is there a more correct way of skipping lines? | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
The methods to parse ColumnInnerDiameter and ChromatographyColumnLength are identical. I have tried to fiddle with generics to get rid of code repetition, but could not get it to work. Is there any way to improve on this side, without modifying the POJO classes?
Any advice on how to improve the code overall is most welcome!
Answer: Your questions:
SonarQube is wrong and you are right. That is the correct way to skip a line. You can use @SuppressWarnings to get rid of the warnings, or you can assign the skipped line to some local variable, such as String skip = br.nextLine().
Since the two Column classes do not share an interface which defines those methods, I do not see a good way to remove the duplication.
See below: | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
Avoid * imports. It makes it harder to determine where dependencies are coming from, and harder to determine what dependencies a class actually has.
Consider importing UTF_16 statically.
There's no need to throw an exception from a private constructor. Having the private constructor is enough.
Constants (and all variables) belong before the constructor, not after. Constants should use UPPER_SNAKE_CASE variable names rather than camelCase.
Throw the most specific exceptions possible. A client cannot handle exception types differently if all it knows it might get is an Exception.
Avoid acronyms and abbreviations when naming code. bufferedReader would be preferable to br. Code should strive to be readable. "bee arr dot readline" vs. "buffered reader dot readline".
The pattern currently used to determine if something is a number is not correct. It will clearly match invalid numbers.
Prefer passing in a File instead of String for the file path. A String can be anything. Consider changing the file path to a File object as soon as possible so the code gains type safety.
Rather than constructing nested readers, consider creating separate named instances. This aligns the code more neatly. Since the use is literally on the next line, it's reasonable to use abbreviated names here. The tradeoff is that the stream and the reader are now in scope for the try block, where they weren't before. Given the size of the method, I think the readability tradeoff is worth it.
Consider breaking out the skip portion of readColumnDocumentFromFile into its own method.
readColumnDocumentFromFile will throw a NullPointerException if the columns block is not in the text file. It would be better to catch the NoSuchElementException and rethrow something that gives more context into what went wrong.
The two parse methods are throwing NumberFormatException, which doesn't make sense when the real problem is that the column data is invalid. | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
Pattern is intended to be compiled once, and then used as a factory for Matcher instances. The Pattern instance should be the constant, not the String.
The code would probably read more cleanly if a Scanner was used. The methods would probably also then be unnecessary, as Scanner can cleanly locate the next double or String value.
If you made all these changes, your code might look more like:
import static java.nio.charset.StandardCharsets.UTF_16; | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Pattern;
public final class ColumnInformationMapper {
private static final Pattern COLUMN_NAME_PATTERN = Pattern.compile(".*:");
private ColumnInformationMapper() {
}
/**
* @throws FileNotFoundException if there is no `acq.txt` file in the given folderPath.
* @throws IOException if the file cannot be read.
*/
public static ChromatographyColumnDocument readColumnDocumentFromFile(File folderPath)
throws FileNotFoundException, IOException {
ChromatographyColumnDocument columnDocument = new ChromatographyColumnDocument();
File file = new File(folderPath, "acq.txt");
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, UTF_16);
Scanner acqScanner = new Scanner(isr)) {
skipToColumnInnerDiameterLine(acqScanner);
ColumnInnerDiameter columnInnerDiameter = new ColumnInnerDiameter();
acqScanner.next(COLUMN_NAME_PATTERN); // skip column name
columnInnerDiameter.setValue(acqScanner.nextDouble());
columnInnerDiameter.setUnit(acqScanner.next());
columnDocument.setColumnInnerDiameter(columnInnerDiameter);
ChromatographyColumnLength columnLength = new ChromatographyColumnLength();
acqScanner.next(COLUMN_NAME_PATTERN); // skip column name
columnLength.setValue(acqScanner.nextDouble());
columnLength.setUnit(acqScanner.next());
columnDocument.setChromatographyColumnLength(columnLength);
return columnDocument;
}
} | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
java, parsing
return columnDocument;
}
}
private static void skipToColumnInnerDiameterLine(Scanner acqScanner) {
/* Looking for pattern
=====================================================================
Column(s)
=====================================================================
Column Description : HP-PONA
*/
String line;
while ((line = acqScanner.nextLine()) != null) {
if (line.contains("======")) {
line = acqScanner.nextLine();
if (line.contains("Column(s)")) {
acqScanner.nextLine();// === line
acqScanner.nextLine();// empty line
break;
}
}
}
acqScanner.nextLine(); //Column Description - Not in model
acqScanner.nextLine(); //Inventory # - Not in model
}
} | {
"domain": "codereview.stackexchange",
"id": 43928,
"lm_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, parsing",
"url": null
} |
python, beginner, python-3.x
Title: Asking multiple choice questions in Python using an API
Question: I’m pretty new to Python. I’m trying to build a multiple choice quiz using Edamam API. It’s currently not flagging any errors but there has to be a neater way to ask the questions, I’m just stuck as some of them require pulling through data from Edamam.
import requests
def recipe_search(meal_type, ingredient, Health):
app_id = "..."
app_key = "..."
result = requests.get(
"https://api.edamam.com/search?q={}&app_id={}&app_key={}".format(ingredient, app_id,
app_key)
)
data = result.json()
return data["hits"]
def run():
meal_type = input("Are you looking for a particular type of meal?: ")
if meal_type == "yes":
input("Select an option from the following list:\n - breakfast\n - brunch\n - lunch\n - snack\n - teatime\n > ")
else: pass
Health = input("Do you have a dietary requirement?: ")
if Health == "yes":
input("Select an option from the following list:\n - vegan\n - vegetarian\n - paleo\n - dairy-free\n - gluten-free\n"
" - wheat-free\n - fat-free\n - low-sugar\n - egg-free\n - peanut-free\n - tree-nut-free\n - soy-free\n"
" - fish-free\n - shellfish-free\n >")
else: pass
ingredient = input("What ingredient would you like to use?:\n > ")
results = recipe_search(meal_type, ingredient, Health)
for result in results:
recipe = result["recipe"]
print(recipe["ingredientLines"])
print(recipe["label"])
print(recipe["calories"])
print(recipe["dishType"])
print(recipe["cuisineType"])
print()
run()
new_item = input("Add recipe to meal planner?:\n > ")
with open("recipe.txt", "r") as recipe_file:
recipes = recipe_file.read()
recipes = recipes + new_item + "\n"
with open("recipe.txt", "w+") as recipe_file:
recipe_file.write(recipes) | {
"domain": "codereview.stackexchange",
"id": 43929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
with open("recipe.txt", "w+") as recipe_file:
recipe_file.write(recipes)
Answer: This is a good beginner project and a good API to practice writing a client.
Add type hints to your function signatures. Python has a weak type system, and the more you can do to strengthen it, the more you'll be able to perform meaningful static analysis and write self-documenting code.
Your program doesn't actually do what you intended. meal_type and Health aren't sent to the API, and even if they were, they would both be the string yes. You need to separate the "yes/no" variable from the "what" variable; the latter you are not assigning at all.
Consider using Edamam's V2 recipe API.
Pay attention to error values that the API may return, the easiest way being raise_for_status.
Delete your else: pass. Or, more likely, once you fix your health and meal assignments, the else will assign the default value for these variables, probably None.
From new_item onward, this is fairly puzzling: it might as well be an entirely separate program, as it doesn't use any of the results from your search to store in the file. It would probably a good feature to add: have the user enter the title of their chosen recipe, and store the entire rendered text of the recipe to the file.
Don't read the entire file; just open the file in append mode.
Suggested
from typing import Any
import requests
def recipe_search(meal_type: str, ingredient: str, health_restriction: str) -> list[dict[str, Any]]:
with requests.get(
'https://api.edamam.com/api/recipes/v2',
headers={'Accept': 'application/json'},
params={
'app_id': '...',
'app_key': '...',
'type': 'any',
'mealType': meal_type,
'health': health_restriction,
'q': ingredient,
},
) as result:
result.raise_for_status()
data = result.json()
return data['hits'] | {
"domain": "codereview.stackexchange",
"id": 43929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
python, beginner, python-3.x
def run_recipe_search() -> None:
has_meal_type = input('Are you looking for a particular type of meal? ')
if has_meal_type == 'yes':
meal_type = input(
'Select an option from the following list:'
'\n - breakfast'
'\n - brunch'
'\n - lunch'
'\n - snack'
'\n - teatime'
'\n > '
)
else:
meal_type = None
has_restriction = input('Do you have a dietary requirement? ')
if has_restriction == 'yes':
health_restriction = input(
'Select an option from the following list:'
'\n - vegan'
'\n - vegetarian'
'\n - paleo'
'\n - dairy-free'
'\n - gluten-free'
'\n - wheat-free'
'\n - fat-free'
'\n - low-sugar'
'\n - egg-free'
'\n - peanut-free'
'\n - tree-nut-free'
'\n - soy-free'
'\n - fish-free'
'\n - shellfish-free'
'\n >'
)
else:
health_restriction = None
ingredient = input('What ingredient would you like to use? ')
results = recipe_search(meal_type, ingredient, health_restriction)
for result in results:
recipe = result['recipe']
print(recipe['ingredientLines'])
print(recipe['label'])
print(recipe['calories'])
print(recipe['dishType'])
print(recipe['cuisineType'])
print()
def add_recipe() -> None:
new_item = input('What recipe would you like to add to your meal planner? ')
with open('recipe.txt', 'a') as recipe_file:
print(new_item, file=recipe_file)
if __name__ == '__main__':
run_recipe_search()
add_recipe() | {
"domain": "codereview.stackexchange",
"id": 43929,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x",
"url": null
} |
c#, beginner, console, image, web-scraping
Title: Grabbing youtube thumbnails from urls
Question: I made some C# code to grab youtube thumbnails from urls, I originally made this in python took some time converting it to C#. I am VERY new to C# and did this with minimal help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
var HD = "maxresdefault.jpg";
var SD = "hqdefualt.jpg";
Console.WriteLine("Welcome to the C# version of YT thumbnail grabber!\nTo get started, go to any video and click 'copy url', then paste it into the program and we'll do the rest!\nTwo websites will open, one with a HD version of the thumbnail, and one with a SD version\nWARNING: A THUMBNAIL MAY ONLY LOAD IN SD OR HD. WHICHEVER IT WAS MADE IN\nInput URL now - ");
var link = Console.ReadLine();
var image = link.Split('/')[3];
var website = "https://img.youtube.com/vi/" + image + "/";
void openBrowser(string a, string b)
{
System.Diagnostics.Process.Start(website + a);
System.Diagnostics.Process.Start(website + b);
}
openBrowser(HD, SD);
Console.Read();
}
}
}
Answer: Prefer constants
Rather than defining HD and SD as mutable variable, please prefer constants
I think there is a typo in your version "hqdefualt.jpg"
const string HD = "maxresdefault.jpg", SD = "hqdefault.jpg";
You should do the same with url prefix
const string HD = "...", SD = "...", UrlPrefix = "https://img.youtube.com/vi";
Prefer verbatim identifier (@)
Rather than using \n inside a long string please prefer @ and multi-line string | {
"domain": "codereview.stackexchange",
"id": 43930,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, image, web-scraping",
"url": null
} |
c#, beginner, console, image, web-scraping
Rather than using \n inside a long string please prefer @ and multi-line string
Console.WriteLine(@"Welcome to the C# version of YT thumbnail grabber!
To get started, go to any video and click 'copy url', then paste it into the program and we'll do the rest!
Two websites will open, one with a HD version of the thumbnail, and one with a SD version
WARNING: A THUMBNAIL MAY ONLY LOAD IN SD OR HD. WHICHEVER IT WAS MADE IN
Input URL now - ");
Do not trust user input
Rather than blindly trusting the user that (s)he provided a valid url please perform some preliminary check(s)
var link = Console.ReadLine();
if (!Uri.TryCreate(link, UriKind.Absolute, out Uri ytLink))
{
Console.WriteLine("Please provide a valid url!");
Environment.Exit(-1);
}
Prefer parsed data
Rather than using magic like this Split("/")[3] please prefer structured data access
Since we have parsed the user input as an Uri we can access the same data via the PathAndQuery property
var image = ytLink.PathAndQuery;
Prefer string interpolation
Rather than concatenating the final url in several steps use a single string interpolation command
$"{UrlPrefix}{image}/{SD}"
$"{UrlPrefix}{image}/{HD}"
Prefer inlining
Rather than creating a local method openBrowser which is called only once please inline the functionality
Process.Start($"{UrlPrefix}{image}/{SD}");
Process.Start($"{UrlPrefix}{image}/{HD}");
Please also prefer namespace usings: using System.Diagnostics;
The full source code
const string HD = "maxresdefault.jpg", SD = "hqdefault.jpg", UrlPrefix = "https://img.youtube.com/vi";
static void Main()
{
Console.WriteLine(@"Welcome to the C# version of YT thumbnail grabber!
To get started, go to any video and click 'copy url', then paste it into the program and we'll do the rest!
Two websites will open, one with a HD version of the thumbnail, and one with a SD version
WARNING: A THUMBNAIL MAY ONLY LOAD IN SD OR HD. WHICHEVER IT WAS MADE IN
Input URL now - "); | {
"domain": "codereview.stackexchange",
"id": 43930,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, image, web-scraping",
"url": null
} |
c#, beginner, console, image, web-scraping
var link = Console.ReadLine();
if (!Uri.TryCreate(link, UriKind.Absolute, out Uri ytLink))
{
Console.WriteLine("Please provide a valid url!");
Environment.Exit(-1);
}
Process.Start($"{UrlPrefix}{ytLink.PathAndQuery}/{SD}");
Process.Start($"{UrlPrefix}{ytLink.PathAndQuery}/{HD}");
Console.Readline();
}
Other observations
Launching browser
Process.Start with an URL will not work on non-Windows machines
I have a Macbook where that command failed with an exception
It might make sense to use HttpClient to download the images
Url generation
I've tried your generated urls and did not provide any valid thumbnail
I have found this SO topic where the described url generation worked like a charm | {
"domain": "codereview.stackexchange",
"id": 43930,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, image, web-scraping",
"url": null
} |
python, performance, python-3.x, dice
Title: Dice roll game with arbitrary face count
Question: I have this code written and I wanted to get a better performance out of it. Could somebody help me please? If possible I would like my code to get a better performance when rolling high numbers and when it getting to the percentage operation.
#implementation of multiple dice rolls at the same time and showing what each dice rolled individually
import random
from collections import Counter
#Welcoming the user to the game
print("Hello and welcome to the dice roller!")
name = input("What is your name?: ")
print ("Hi", name)
while True:
#Asking the user if he wants to play to make it break the loop and say bye whenever he stops playing
wants_to_play = input("Do you want to play? (y/n): ").lower()
#if statement to determine the number of dice faces, and to "roll the dice" hypothetically.
if wants_to_play == "y":
dice_face = int(input("Select the number of faces you want your dice to have. WARNING: if you don't select a whole number, the dice roller won't work. "))
dice_amount = int(input("Select how many dices of the given faces you want to roll: "))
#generating dice roll number with the given input
dice_rolls = []
for i in range(0, dice_amount):
dice_rolls.append(random.randint(1,dice_face))
dice_rolls = []
for i in range(0, dice_amount):
dice_rolls.append(random.randint(1,dice_face))
#Counting how many of each number are they and defining percentages
num = Counter(dice_rolls)
percentages = sum(num.values())
total = round(percentages, 1)
#printing final message output to the user
print("Your dice percentages where: ")
for face, count in num.most_common():
print(f"{face}: {count} ({count/total:.2%})")
#When the user stops wanting to play, saying them goodbye
else:
print("Well, it was great while it lasted! Until next time!")
break | {
"domain": "codereview.stackexchange",
"id": 43931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, dice",
"url": null
} |
python, performance, python-3.x, dice
print("Developed by SMB Studios")
Answer: First off, I would say your code doesn't do what it's stated to do:
#implementation of multiple dice rolls at the same time and showing what each dice rolled individually
It doesn't show the individual rolls, only the cumulative stats. If this is intentional, then fine, but I suggest you change the docstring (and make it one) to show that.
PEP-8
PEP-8 is a set of recommendations regarding the format of Python code. They mean that there is a standard way of writing Python code which makes it easier to read and use others' code.
This includes recommendations on indent levels (4 spaces), spaces after commas, comments, etc. I suggest you look into getting a linter such as flake8 or pylint and run your code through them to standardise it against others' codes.
Comments
As it is, many of your comments don't really help me understand the code any more than the code does and in some cases are somewhat misleading:
# if statement to determine the number of dice faces, and to "roll the dice" hypothetically.
The if statement doesn't determine the number of faces. It's whether the code will run or not. I'm not sure what you mean by
"roll the dice" hypothetically | {
"domain": "codereview.stackexchange",
"id": 43931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, dice",
"url": null
} |
python, performance, python-3.x, dice
"roll the dice" hypothetically
Do you mean you're not really rolling dice because it's a computer?
Comments are very much personal choice, but I would usually just outline what a block of code is to do in simple terms, and in complex parts how it does so (algorithm name, references, etc).
Handling user input
Currently, your code crashes if you enter a non-int value into your input.
We can do better than this using a function to get an integer from a user:
def get_int(prompt: str) -> int: # Type hints tell a user what to provide and expect
""" Get a valid integer from the user """
while True:
val = input(prompt)
try:
val = int(val)
except ValueError: # If it can't be turned into an int,
# it will raise this error, and this code will run
print(f"Invalid integer value ({val}), please try again.")
else: # If there isn't an error, this code will run
return val # Set the name of the function where it is call
# to this value and leave the function
Which means we now use:
dice_face = get_int("Select the number of faces you want your dice to have: ")
dice_amount = get_int("Select how many dice of the given faces you want to roll: ")
Duplicated effort
In your code, you roll the dice, discard them, then roll them again:
dice_rolls = []
for i in range(0, dice_amount):
dice_rolls.append(random.randint(1,dice_face))
dice_rolls = []
for i in range(0, dice_amount):
dice_rolls.append(random.randint(1,dice_face))
This means you spend a lot of effort doing nothing.
The other thing to bear in mind is that you are using append. List comprehensions (which you may not have met yet) are faster in general.
dice_rolls = [random.randint(1, dice_face) for _ in range(dice_amount)] # 0 is implied in the range | {
"domain": "codereview.stackexchange",
"id": 43931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, dice",
"url": null
} |
python, performance, python-3.x, dice
The other thing is that you are building this list of values, and then only using the Counter to do consume the list. You might want to instead, just directly increment the counter.
num = Counter()
for i in range(dice_amount):
roll = random.randint(1, dice_face)
num[roll] += 1
or (advanced) you could use a generator expression as the iterable of the counter:
num = collections.Counter(random.randint(1, dice_face) for _ in range(dice_amount))
Here:
percentages = sum(num.values())
total = round(percentages, 1)
percentages doesn't compute the percentages, just the counts and is not really used again, and total being the rounding of this is irrelevant because the counts will always be integral. There is already a method on Counter (total) which does this.
print(f"{face}: {count} ({count / num.total():.2%})")
Summary
Putting all this together, along with Tamoghna Chowdhury's comments, we end up with something like:
"""
Code to roll multiple dice and show individual rolls as well as aggregated statistics
"""
import random
from collections import Counter
def get_int(prompt: str) -> int:
""" Get a valid integer from the user """
while True:
val = input(prompt)
try:
val = int(val)
except ValueError:
print(f"Invalid integer value ({val}), please try again.")
else:
return val
# Welcome user to the game
print("Hello and welcome to the dice roller!")
name = input("What is your name? ")
print("Hi", name)
while True:
# Ask if user wants to play
wants_to_play = input("Do you want to play? (y/n) ").lower()
if wants_to_play == "y":
# Get the number of faces, and number to roll.
dice_face = get_int("Select the number of faces you want your dice to have: ")
dice_amount = get_int("Select how many dices of the given faces you want to roll: ") | {
"domain": "codereview.stackexchange",
"id": 43931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, dice",
"url": null
} |
python, performance, python-3.x, dice
# generate rolls
num = Counter()
for i in range(dice_amount):
roll = random.randint(1, dice_face)
print(f"Die {i}: {roll}") # N.B. May want to add capability to disable this for large numbers of rolls (e.g > 10)
num[roll] += 1
# print stats
print("\nYour dice percentages were: ")
for face, count in num.most_common():
print(f"{face}: {count} ({count / num.total():.2%})")
elif wants_to_play == "n":
# say goodbye and quit
print("Well, it was great while it lasted! Until next time!")
break
else:
print(f"Unknown option ({wants_to_play}), please try again.")
print("Developed by SMB Studios") | {
"domain": "codereview.stackexchange",
"id": 43931,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, dice",
"url": null
} |
python, tkinter, video
Title: Tool to concatenate video files
Question: The function below is written by me in an app that lets you merge 2 or more video clips together, so I used a text box in the GUI, it asks you how many clips you want to merge, and will do it for you accordingly, however, it looks really messy and it is so repetitive.
def merge_vid():
number_of_videos = box.get()
if number_of_videos <= "1":
messagebox.showwarning(title="Warning", message="Please specify how many videos you want to merge.")
elif number_of_videos == "2":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2])
final_clip.write_videofile('Final.mp4', codec="libx264")
elif number_of_videos == "3":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
clip3 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2, clip3])
final_clip.write_videofile('Final.mp4', codec="libx264")
elif number_of_videos == "4":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
clip3 = VideoFileClip(f"{open_location()}.mp4")
clip4 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2, clip3, clip4])
final_clip.write_videofile('Final.mp4', codec="libx264")
Here's the entire code:
import tkinter
from moviepy.editor import *
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
import threading
import requests
import os
from tkinter.filedialog import askopenfilename
def space():
space = Label(text="", bg="black")
space.pack()
def open_location(): | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
def space():
space = Label(text="", bg="black")
space.pack()
def open_location():
global filename_splitted
filename = askopenfilename()
filename_ext = os.path.splitext(filename)
filename_splitted = str(filename_ext).split('/')[4].split(".")[0].split(',')[0].split("'")[0]
filename_ext_split = filename_ext[1][1:]
if len(filename) > 1 and filename_ext_split == "mp4":
path_url.config(text=filename_splitted, fg="green")
else:
messagebox.showwarning(title="oops", message="No video given!")
path_url.config(text="Please specify a file (mp4)!", fg="red")
return filename_splitted
def merge_vid():
number_of_videos = box.get()
video_title = title_box.get()
if number_of_videos <= "1":
messagebox.showwarning(title="Warning", message="Please specify how many videos you want to merge.")
elif video_title == "":
messagebox.showwarning(title="Warning", message="Please give your clip a title..")
elif number_of_videos == "2":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2])
final_clip.write_videofile(f'{video_title}.mp4', codec="libx264")
elif number_of_videos == "3":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
clip3 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2, clip3])
final_clip.write_videofile('Final.mp4', codec="libx264") | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
elif number_of_videos == "4":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4")
clip3 = VideoFileClip(f"{open_location()}.mp4")
clip4 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2, clip3, clip4])
final_clip.write_videofile('Final.mp4', codec="libx264")
def put_music():
# audio = AudioFileClip("Music.mp3")
# video1 = VideoFileClip("Final.mp4")
# final = video1.set_audio(audio)
# final.write_videofile("output.mp4")
pass
root = Tk()
space()
space()
# root.iconbitmap("yt.ico")
root.title("Video Editor")
root.geometry("350x350")
root.columnconfigure(0, weight=1)
root.config(bg="black")
# space()
# path_btn = Button(root, width=11, height=2, bg="#CC1B25", fg="white", text="Select Video", command=open_location)
# path_btn.pack()
space()
space()
space()
label = Label(root, text="How many videos do you want to merge:", bg="black", fg="white", font=("jost", 9, "bold"))
label.pack()
EntryVar = StringVar()
box = Entry(root, width=7, textvariable=EntryVar)
box.pack()
space()
title = Label(root, text="Name your merged video clip:", bg="black", fg="white", font=("jost", 9, "bold"))
title.pack()
EntryVar = StringVar()
title_box = Entry(root, width=17, textvariable=EntryVar)
title_box.pack()
space()
merge_btn = Button(root, width=27, height=3, bg="green", fg="white", text="Choose and Merge Videos", command=merge_vid)
merge_btn.pack()
space()
space()
# start_merge_btn = Button(root, width=27, height=3, bg="green", fg="white", text="Start Merge", command=start_merge)
# start_merge_btn.pack()
path_url = Label(root, text="", fg="red", bg="black", font=("jost", 9, "bold"))
path_url.pack()
root.mainloop()
Answer: TL;DR: To shorten the repetitive code-blocks and reduce duplication, go to 2nd section "Extract method".
Make code readable
To do so we can: | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
improve naming of variables, functions and classes
write statements that are self-explaining
express intend by telling what we want to achieve and why
be clear about expectations and (pre-/post-) conditions
Improve naming
merge_vid() has deserved a better name.
A rule-of-thumb for naming:
don't use abbreviations or acronyms that are not common
better spell-out words in correct language to leverage auto-completion and satisfy spellchecking | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
Write self-explaining lines
Assume the number_of_videos (well describing and honest name!) is entered by the user and given as first input. It's not that clear from box.get() which UI element is used, nor what can be expected to get. Intent of this line is to get a number. So we could name the element textbox_video_number (or somehow incorporate the related label near the box).
Also we should convert to an integer, like int(textbox_video_number.get()). Maybe we can also give the user a hint for expected numerical input before. Even better if UI-elements allow only to enter numbers in a specific range, have hints or validation.
Tell your intend like a story
Further it looks like open_location() starts a UI-dialogue which waits for user-response. In the name neither the user-interaction nor the expected return is expressed. The name could tell a story: it asks the user to choose a file and returns the path and base-name. Here we can improve naming to express that intent.
Express your conditions clearly
The guard-statement if number_of_videos <= "1" can also check for a valid range, not only min, but also max. For example, if number_of_videos not in range(2, 5) verifies that a valid number is between min 2 and max 4 (or at least 2 but not more than 4).
Extract method (refactoring)
This can be used to de-duplicate and shorten the code. A code-block that is extracted to a method can be named for his intend, and re-used repetitively.
How to identify blocks to extract?
You already recognized a repetitive pattern in your code and suspect some blocks to be somewhat unnecessarily repeated.
Can you express what the following blocks do for the valid given number?
First try to add a comment like a summarizing title on top.
# ask for given number of video files and concatenate them
elif number_of_videos == "2":
clip1 = VideoFileClip(f"{open_location()}.mp4")
clip2 = VideoFileClip(f"{open_location()}.mp4") | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
clip2 = VideoFileClip(f"{open_location()}.mp4")
final_clip = concatenate_videoclips([clip1, clip2])
final_clip.write_videofile('Final.mp4', codec="libx264") | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
How to extract?
Now since you gave this block a title and figured out its dependencies, you can define a function as future replacement for this block. Use the title comment as name, e.g.:
def ask_for_videos_and_concatenate(number_of_videos):
# ask the user for a list of video files (all must have extension mp4)
video_files = []
# read the files to clip objects
clips = []
# concatenate the list of clips to a single MP4 using specific code
final_clip = None
return final_clip
Then fill this dummy or method-stub with code to live. The code comes from your repetitive blocks (which contain duplicated parts depending on the number).
The extracted method and its usage
Finally you might end in:
def ask_for_videos_and_concatenate(number_of_videos):
# ask the user for a list of video files (all must have extension mp4)
video_files = []
for i in range(0, number_of_videos): # loop exactly n times (0..n-1)
choosen_file = open_location() # rename the method to show the UI-aspect: ask the user for a file (path/location)
video_files.append(f"{choosen_file}.mp4")
# read the files to clip objects
clips = [VideoFileClip(f) for f in video_files] # list-comprehension to shorten
# concatenate the list of clips to a single MP4 using specific code
final_clip = concatenate_videoclips( clips ) # now argument clips is a list ;-)
final_clip.write_videofile('Final.mp4', codec="libx264")
return final_clip
# and your repetitive blocks have all reduced to a ..
def merge_videos():
number_of_videos = int(box.get()) # read the user-input as number from text-box
if number_of_videos not in range(2,5):
messagebox.showwarning(title="Warning", message="Please specify how many videos you want to merge. Must be at least 2 and maximum 4.")
return # fast-fail exit: if invalid number then nothing to merge | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, tkinter, video
# .. single line: the happy path
return ask_for_videos_and_concatenate(number_of_videos)
Now merge_vids() became a UI-function (reading user-input, validating and fulfilling the action), might be used as callback for a click-event. | {
"domain": "codereview.stackexchange",
"id": 43932,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, video",
"url": null
} |
python, python-3.x
Title: 2D array diagonals sum
Question: I am trying to sum primary diagonal and secondary diagonal of 2D array of python like this:
records = [[12, 5, 2 , 1], [15, 6,10 , 1], [10, 8, 12,1], [10, 8, 12,1]]
primary_diagonal_sum = 0
array_size = len(records)
secondry_diagonal_sum = 0
for index , record in enumerate(records):
primary_diagonal_sum += records[index][index]
array_size = array_size - 1
secondry_diagonal_sum += records[index][array_size]
and it's working fine. Just want to know if this is this written well ? is this efficient or maybe it can improve working wise ?
Answer: PEP-8
The Style Guide for Python Code has several recommendations which you have deviated from in your code:
White space
Commas should be followed by 1 space, and should not be preceded by any spaces:
Change:
records = [[12, 5, 2 , 1], [15, 6,10 , 1], [10, 8, 12,1], [10, 8, 12,1]]
for index , record in enumerate(records):
to:
records = [[12, 5, 2, 1], [15, 6, 10, 1], [10, 8, 12, 1], [10, 8, 12, 1]]
for index, record in enumerate(records):
Unused variables
If a variable is not used, but is needed for syntactic reasons, the _ throwaway variable should be used:
Change:
for index , record in enumerate(records):
to:
for index, _ in enumerate(records):
Group similar statements
If several statements are similar, if possible, keep them together:
Change:
primary_diagonal_sum = 0
array_size = len(records)
secondry_diagonal_sum = 0
for index , record in enumerate(records):
primary_diagonal_sum += records[index][index]
array_size = array_size - 1
secondry_diagonal_sum += records[index][array_size]
to:
array_size = len(records)
primary_diagonal_sum = 0
secondry_diagonal_sum = 0
for index, _ in enumerate(records):
array_size = array_size - 1
primary_diagonal_sum += records[index][index]
secondry_diagonal_sum += records[index][array_size]
Assignment operators
You’re using += operator; why not -= also?
Change:
array_size = array_size - 1 | {
"domain": "codereview.stackexchange",
"id": 43933,
"lm_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
to:
array_size -= 1
Confusing code
array_size should be the size of the array. The reader would expect this to always hold. But in this code, it appears the size of the array is decreasing???:
array_size = len(records)
for index, _ in enumerate(records):
array_size = array_size - 1
secondry_diagonal_sum += records[index][array_size]
Pick a better variable name for array_size, or calculate the index:
array_size = len(records)
for index, _ in enumerate(records):
secondry_diagonal_sum += records[index][array_size - 1 - index]
or simply use negative indexing:
for index, _ in enumerate(records):
secondry_diagonal_sum += records[index][-1 - index]
Enumerate
The elephant in the room:
for index , record in enumerate(records):
# code not using `record`
Why are you using enumerate(…) if you are not using the record portion?
for index in range(len(records)):
…
Or, actually use the record field:
for index, record in enumerate(records):
primary_diagonal_sum += record[index]
secondry_diagonal_sum += record[-1 - index]
sum
Python has a builtin function for summing sum(), often used with a generator expression. You can even use reversed(…) to traverse records from the bottom up, eliminating the need for negative indexing:
primary_diagonal_sum = sum(row[idx] for idx, row in enumerate(records))
secondry_diagonal_sum = sum(row[idx] for idx, row in enumerate(reversed(records))) | {
"domain": "codereview.stackexchange",
"id": 43933,
"lm_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
} |
javascript, object-oriented, modules
Title: Adding and Retrieving Players in a simple Pre-Flop Poker Hud with Local Storage
Question: I am building a browser based Pre-Flop HUD that for now just tracks VPIP, PFR and number of hands played for an opponent (https://pokercopilot.com/poker-statistics/vpip-pfr). I am currently using local storage to store my data. In the future I will use a better persistence strategy, add more features, and find a way to de-couple the user interface without just putting it in the functions I have now.
I used an object literal approach without classes right now to try out some basic decomposition with simple functions for practice. Right now the only functionality I have is adding a player to Local Storage and getting all players from Local Storage.
Any suggestions for improvement are welcome.
But I do have a couple questions:
Is there a benefit to using Classes? Right now I don't see the benefit of having a handle, like, player1 = new Player(arg,arg,etc...), player2 = new Player(arg,arg, etc...)...
Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.
In my function addPlayer() should I be calling savePlayersToStorage in my localStorageUtils.js?
Main.js file = entry point for my program
/**********************************
* This is the program driver, that
* will call other functions
* *******************************/
import { addPlayer } from "./player.js";
import {
savePlayersToStorage,
getPlayersFromStorage,
} from "./LocalStorageUtilsObjectLiteral.js";
function main() {
let newPlayer = "Doug Polk";
const localStorageKey = "stored_players";
let players = getPlayersFromStorage(localStorageKey); //array of player objects in localStorage
players.push(addPlayer(newPlayer));
savePlayersToStorage(localStorageKey, JSON.stringify(players));
}
main(); | {
"domain": "codereview.stackexchange",
"id": 43934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, object-oriented, modules",
"url": null
} |
javascript, object-oriented, modules
main();
Player.js addPlayer creates and returns an object literal
function addPlayer(name) {
let player = {
uuid: Date.now(),
name: name,
vpipActionCount: 0, //The number of times a player voluntarily put money into the pot Pre-Flop, whether calling or raising.
pfrActionCount: 0, //The number of times a player raised pre-flop, this includes 3-bets.
vpipPercentage: 0, //The percentage of hands a player has played, can be between 0 and 100%
pfrPercentage: 0, //The percentage of hands a player has raised pre-flop, can be between 0 and 100%, but can never be higher than vpipPercentage
totalHandsTracked: 0, //The number of hands tracked for a player
callAction: function () {
this.totalHands++;
this.vpipActionCount++;
},
raiseAction: function () {
this.totalHands++;
this.pfrActionCount++;
},
foldAction: function () {
this.totalHands++;
},
calculateVpipPercentage: function () {
this.vpip = (this.vpipActionCount * 100) / this.totalHands;
},
calculatePfrPercentage: function () {
this.pfrPercentage = (this.pfrActionCount * 100) / this.totalHands;
},
getVpipPercentage: function () {
return this.vpipPercentage;
},
getPfrPercentage: function () {
return this.pfrPercentage;
},
};
return player;
}
export { addPlayer };
LocalStorageUtils.js Functions to get and save players to Local Storage
function savePlayersToStorage(localStorageKey, playersArray) {
if (localStorage.getItem(localStorageKey === null)) {
localStorage.setItem(localStorageKey);
}
localStorage.setItem(localStorageKey, playersArray);
}
function getPlayersFromStorage(localStorageKey) {
if (localStorage.getItem(localStorageKey === null)) {
localStorage.setItem(localStorageKey);
}
let players = JSON.parse(localStorage.getItem(localStorageKey));
return players;
}
export { savePlayersToStorage, getPlayersFromStorage };
Answer: To Your Questions | {
"domain": "codereview.stackexchange",
"id": 43934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, object-oriented, modules",
"url": null
} |
javascript, object-oriented, modules
export { savePlayersToStorage, getPlayersFromStorage };
Answer: To Your Questions
Is there a benefit to using Classes? Right now I don't see the benefit of having a handle, like, player1 = new Player(arg,arg,etc...), player2 = new Player(arg,arg, etc...)...
Maybe there are benefits, but I can't think of any serious ones now.
The current version is similar to the factory pattern, where the creation of an object is abstracted by a factory - in this case addPlayer:
const player = addPlayer('Harry Potter');
Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.
I think storing all players under one key is sufficient and the easiest to manage. But you can get the best of both worlds:
Currently you are saving an array of players. Instead you could save a map where the key is a unique attribute of the player (maybe the name or an id) and the player itself. The benefit would be that you do not need to loop through an array to find a player:
function getPlayersFromStorage(key) {
/* ... read from storage ... */;
/* return has the form:
{
playername: player
}
*/
}
const players = getPlayersFromStorage(localStorageKey);
const harryPotter = players["Harry Potter"];
This is only necessary if you need to find players directly.
In my function addPlayer() should I be calling savePlayersToStorage in my localStorageUtils.js?
It depends. Currently the method name addPlayer does not represent what the method does. When I first read the name I thought: "Ah ok, this methods put a player in some collection or maybe the local storage". But then I read the following line and get confused:
players.push(addPlayer(newPlayer));
A better name for addPlayer would be createPlayer and I would not call savePlayersToStorage in it, to have smaller and side effect free functions.
Change Persistenz | {
"domain": "codereview.stackexchange",
"id": 43934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, object-oriented, modules",
"url": null
} |
javascript, object-oriented, modules
I am currently using local storage to store my data. In the future I will use a better persistence strategy
Currently, only the main.js depends on localStorage, and knows the implementation details, which would make it easier to change it in the future. However, to make it easier to change, especially as the code grows and more files depend on the persistence implementation, it should be abstracted as much as possible:
class LocalStorage {
getAll() { /* ... */ }
getByName() { /* ... */ }
save() { /* ... */ }
}
class OtherStorage {
getAll() { /* ... */ }
getByName() { /* ... */ }
save() { /* ... */ }
}
When your different storage strategies share the same interface they are easy interchange able:
// Main.js
const storage = new LocalStorage('my-storage-key');
# const storage = new OtherStorage(/* dependencies */);
function main() {
const players = storage.getAllPlayers();
const harryPotter = storage.getPlayerByName('Harry Potter');
const newPlayer = createPlayer('Ron Weasley');
const storage.save(newPlayer);
}
Read from Store
function getPlayersFromStorage(localStorageKey) {
if (localStorage.getItem(localStorageKey === null)) {
localStorage.setItem(localStorageKey);
}
let players = JSON.parse(localStorage.getItem(localStorageKey));
return players;
}
When reading from the store we set an item if the key does not exists with localStorage.setItem(localStorageKey). To set an item is not the responsibility for reading data. Instead we could add some logic which is related for reading. For example if there is stored data under the given key:
function getPlayersFromStorage(localStorageKey) {
const fromStore = localStorage.getItem(localStorageKey);
if (fromSore) {
return [];
}
return JSON.parse(fromStore);
} | {
"domain": "codereview.stackexchange",
"id": 43934,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, object-oriented, modules",
"url": null
} |
beginner, rust, minesweeper
Title: rustymines - a mine sweeping game with a shenanigan
Question: I am learning Rust for about a week now. I just finished my first little working project, a mine sweeping game. The game comes with a little extra feature, namely old, broken (rusty) mines, that will not explode if you step on them. I'd like to have feedback on the general code style, since I'm still new to Rust and would also like suggestions, how I could improve the Board.visit_neighbors() which I somehow find pretty ugly.
src/coordinate.rs:
use std::str::FromStr;
#[derive(Debug)]
pub enum CoordinateParseError {
NotTwoNumbers,
InvalidXValue,
InvalidYValue,
}
#[derive(Debug)]
pub struct Coordinate {
x: usize,
y: usize,
}
impl Coordinate {
pub fn new(x: usize, y: usize) -> Self {
Self { x: x, y: y }
}
pub fn x(&self) -> usize {
self.x
}
pub fn y(&self) -> usize {
self.y
}
fn from_str_pair((x, y): (&str, &str)) -> Result<Self, CoordinateParseError> {
match x.parse::<usize>() {
Ok(x) => match y.parse::<usize>() {
Ok(y) => Ok(Coordinate::new(x, y)),
Err(_) => Err(CoordinateParseError::InvalidYValue),
},
Err(_) => Err(CoordinateParseError::InvalidXValue),
}
}
}
impl FromStr for Coordinate {
type Err = CoordinateParseError;
fn from_str(string: &str) -> Result<Self, Self::Err> {
match string.split_once(' ') {
Some(value) => Self::from_str_pair(value),
None => Err(CoordinateParseError::NotTwoNumbers),
}
}
}
src/game.rs:
use std::fmt;
mod args;
use args::parse;
use args::GameArgs;
mod board;
use board::Board;
use board::MoveResult;
#[derive(Debug)]
pub struct Game {
board: Board,
over: bool,
} | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
#[derive(Debug)]
pub struct Game {
board: Board,
over: bool,
}
impl Game {
pub fn new(width: usize, height: usize, mines: u8, duds: u8) -> Result<Self, &'static str> {
Ok(Self {
board: Board::new(width, height, mines, duds)?,
over: false,
})
}
pub fn from_args(args: &impl GameArgs) -> Result<Self, &'static str> {
Self::new(args.width(), args.height(), args.mines(), args.duds())
}
pub fn parse() -> Result<Self, &'static str> {
Self::from_args(&parse())
}
pub fn visit(&mut self, x: usize, y: usize) {
match self.board.visit(x, y) {
MoveResult::AlreadyVisited => println!("You already visited the field at {}x{}.", x, y),
MoveResult::Continue => println!("{}", self),
MoveResult::InvalidPosition => {
println!("The field at {}x{} is not on the board.", x, y)
}
MoveResult::Lost => {
self.over = true;
println!("You lost the game.")
}
MoveResult::Won => {
self.over = true;
println!("You won the game.")
}
}
}
pub fn over(&self) -> bool {
self.over
}
pub fn to_string(&self) -> String {
self.board.to_string(self.over())
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_string())
}
}
src/game/args.rs:
use clap::Parser;
pub trait GameArgs {
fn width(&self) -> usize;
fn height(&self) -> usize;
fn mines(&self) -> u8;
fn duds(&self) -> u8;
}
#[derive(Parser)]
#[clap(name = "rustymines")]
#[clap(author = "Richard Neumann <mail@richard-neumann.de>")]
#[clap(version = "1.0.0")]
#[clap(about = "A mine sweeping game written in Rust.", long_about = None)]
struct GameArgsParser {
#[clap(short, long, value_parser, default_value_t = 5)]
width: usize, | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
#[clap(short, long, value_parser, default_value_t = 5)]
height: usize,
#[clap(short, long, value_parser, default_value_t = 8)]
mines: u8,
#[clap(short, long, value_parser, default_value_t = 0)]
duds: u8,
}
pub fn parse() -> impl GameArgs {
GameArgsParser::parse()
}
impl GameArgs for GameArgsParser {
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usize {
self.height
}
fn mines(&self) -> u8 {
self.mines
}
fn duds(&self) -> u8 {
self.duds
}
}
src/game/board.rs:
use itertools::Itertools;
use std::collections::HashMap;
use grid::Grid;
use rand::{seq::IteratorRandom, thread_rng};
mod field;
use field::Field;
#[derive(Debug, PartialEq, Eq)]
pub enum MoveResult {
AlreadyVisited,
Continue,
InvalidPosition,
Lost,
Won,
}
#[derive(Debug)]
pub struct Board {
fields: Grid<Field>,
mines: u8,
duds: u8,
initialized: bool,
}
impl Board {
pub fn new(width: usize, height: usize, mines: u8, duds: u8) -> Result<Self, &'static str> {
if width < 1 {
Err("field too narrow")
} else if height < 1 {
Err("field too flat")
} else if width * height <= mines as usize {
Err("too many mines for field size")
} else if duds > mines {
Err("more duds than mines")
} else {
Ok(Self {
fields: Grid::new(width, height, Field::new),
mines: mines,
duds: duds,
initialized: false,
})
}
} | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
pub fn visit(&mut self, x: usize, y: usize) -> MoveResult {
match self.make_move(x, y) {
MoveResult::Lost => MoveResult::Lost,
MoveResult::InvalidPosition => MoveResult::InvalidPosition,
_ => {
if self.all_mines_cleared() {
MoveResult::Won
} else {
MoveResult::Continue
}
}
}
}
pub fn to_string(&self, game_over: bool) -> String {
self.header()
+ &self
.fields
.rows()
.enumerate()
.map(|(y, row)| {
format!("{:x}|", y)
+ &row
.iter()
.enumerate()
.map(|(x, field)| {
field.to_string(self.neighboring_mines(x, y), game_over)
})
.join(" ")
})
.join("\n")
}
fn header(&self) -> String {
" |".to_string()
+ &(0..self.fields.width())
.map(|x| format!("{:x}", x))
.join("|")
+ "\n--"
+ &(0..self.fields.width()).map(|_| '-').join("-")
+ "\n"
}
fn neighboring_mines(&self, x: usize, y: usize) -> usize {
self.fields
.neighbors(x, y)
.filter(|(_, _, field)| field.has_mine())
.count()
}
fn make_move(&mut self, x: usize, y: usize) -> MoveResult {
if !self.initialized {
self.first_move(x, y)
} else {
self.visit_coordinate(x, y)
}
} | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
fn first_move(&mut self, x: usize, y: usize) -> MoveResult {
match self.fields.get_mut(x, y) {
Ok(field) => {
field.visit();
self.populate_mines();
self.populate_duds();
self.visit_coordinate(x, y);
self.initialized = true;
MoveResult::Continue
}
Err(_) => MoveResult::InvalidPosition,
}
}
fn populate_mines(&mut self) {
self.fields
.iter_mut()
.filter(|field| !field.visited())
.choose_multiple(&mut thread_rng(), self.mines as usize)
.into_iter()
.for_each(|field| field.set_mine());
}
fn populate_duds(&mut self) {
self.fields
.iter_mut()
.filter(|field| field.has_mine())
.choose_multiple(&mut thread_rng(), self.duds as usize)
.into_iter()
.for_each(|field| field.set_dud());
}
fn visit_coordinate(&mut self, x: usize, y: usize) -> MoveResult {
match self.fields.get_mut(x, y) {
Ok(field) => {
if self.initialized && field.visited() {
MoveResult::AlreadyVisited
} else {
field.visit();
if field.has_mine() && !field.is_dud() {
MoveResult::Lost
} else {
if self.neighboring_mines(x, y) == 0 {
self.visit_neighbors(x, y);
}
MoveResult::Continue
}
}
}
Err(_) => MoveResult::InvalidPosition,
}
}
fn visit_neighbors(&mut self, x: usize, y: usize) {
let mut neighbors = HashMap::new();
neighbors.insert((x, y), ()); | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
loop {
let new_neighbors = neighbors
.iter()
.filter(|(&(x, y), _)| self.neighboring_mines(x, y) == 0)
.flat_map(|(&(x, y), _)| {
self.fields.neighbors(x, y).filter(|(nx, ny, neighbor)| {
!neighbor.has_mine() && !neighbors.contains_key(&(*nx, *ny))
})
})
.collect_vec();
if new_neighbors.len() == 0 {
break;
}
for (x, y, _) in new_neighbors {
neighbors.insert((x, y), ());
}
}
for &(x, y) in neighbors.keys() {
match self.fields.get_mut(x, y) {
Ok(field) => field.visit(),
Err(_) => continue,
}
}
}
fn all_mines_cleared(&self) -> bool {
self.fields
.iter()
.filter(|field| !field.has_mine())
.all(|field| field.visited())
}
}
src/game/board/field.rs:
#[derive(Debug)]
pub struct Field {
mine: bool,
dud: bool,
visited: bool,
}
impl Field {
pub fn new() -> Self {
Self {
mine: false,
dud: false,
visited: false,
}
}
pub fn has_mine(&self) -> bool {
self.mine
}
pub fn set_mine(&mut self) {
self.mine = true;
}
pub fn is_dud(&self) -> bool {
self.dud
}
pub fn set_dud(&mut self) {
self.dud = true;
}
pub fn visited(&self) -> bool {
self.visited
}
pub fn visit(&mut self) {
self.visited = true;
} | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
pub fn visit(&mut self) {
self.visited = true;
}
pub fn to_string(&self, adjacent_mintes: usize, game_over: bool) -> String {
match (game_over, self.visited, self.mine, self.dud) {
(_, true, true, true) => "~".to_string(),
(_, true, true, false) => "*".to_string(),
(false, true, false, _) | (true, _, false, _) => {
if adjacent_mintes > 0 {
adjacent_mintes.to_string()
} else {
" ".to_string()
}
}
(true, false, true, _) => "o".to_string(),
_ => "■".to_string(),
}
}
}
src/io.rs:
use std::fmt::Debug;
use std::io::Write;
use std::str::FromStr;
pub fn read<T>(prompt: &str) -> Result<T, &'static str>
where
T: FromStr,
<T as FromStr>::Err: Debug,
{
print_prompt(prompt);
let mut input = String::new();
match std::io::stdin().read_line(&mut input) {
Ok(_) => match input.trim().parse::<T>() {
Ok(value) => Ok(value),
Err(_) => Err("invalid value"),
},
Err(_) => Err("no value read"),
}
}
pub fn read_repeat<T>(prompt: &str) -> T
where
T: FromStr,
<T as FromStr>::Err: Debug,
{
loop {
match read::<T>(prompt) {
Err(msg) => eprintln!("Error: {}", msg),
Ok(value) => return value,
}
}
}
fn print_prompt(prompt: &str) {
print!("{}", prompt);
match std::io::stdout().flush() {
Ok(_) => (),
Err(_) => (),
}
}
src/main.rs:
mod coordinate;
use coordinate::Coordinate;
mod game;
use game::Game;
mod io;
use io::read_repeat;
fn main() {
match Game::parse() {
Ok(mut game) => run_game(&mut game),
Err(msg) => eprintln!("Error: {}", msg),
}
}
fn run_game(game: &mut Game) {
println!("{}", game); | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
fn run_game(game: &mut Game) {
println!("{}", game);
while !game.over() {
let coordinate = read_repeat::<Coordinate>("Enter coordinate: ");
game.visit(coordinate.x(), coordinate.y());
}
println!("{}", game);
}
Cargo.toml:
[package]
name = "rustymines"
version = "1.0.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
itertools = "*"
rand = "*"
grid = { git = "https://github.com/conqp/grid.git", branch = "main" }
clap = { version = "3.2.22", features = ["derive"] }
Answer: I don't have time for a complete review right now, so I will just make some observations.
First of all: That's a solid improvement over the already good code you submitted last time!
Your main begins with
fn main() {
match Game::parse() {
which is odd to look at. What is parsed here? Where does the stuff to parse come from? Generally, I would try to show the flow of information rather than hiding it. Also, internally the method calls Self::from_args(&parse()), so nothing is actually parsed, but you use the parsed args.
I would rewrite that as something like:
fn main() {
let args = Args::parse_args();
match Game::from(args) {
That would also be a good opportunity to use the standard trait: impl From<Args> for Game.
Then you have this one.
while !game.over() {
let coordinate = read_repeat::<Coordinate>("Enter coordinate: ");
game.visit(coordinate.x(), coordinate.y());
}
So you read a coordinate, copy its x and y, and then pass the individual values to visit(). But you don't want to visit two different usizes, you want to visit an actual coordinate. So write it like this.
pub fn visit(&mut self, coord: Coordinate) {
That way you also don't need to specify the type of read_repeat in main.
This change would need to be propagated all the way down to first_move and visit_coordinate and Board::get_mut. | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, rust, minesweeper
read_repeat is strangely worded IMO. Is it necessary for the coder to see that this method will repeat on this level of abstraction? If not, just call it read, which is already taken in your case, so maybe read_user_input will do.
match self.board.visit(x, y) {
MoveResult::AlreadyVisited => println!("You already visited the field at {}x{}.", x, y),
You must have a bug somewhere, because that message is not shown when I visit 0 0 in a new game repeatedly.
I like your neighbor_coordinates() method a lot! Nice showcase of functional programming.
Usability: The user does not see how the input format looks like and must figure it out themselves. Also it's initially unclear which axis corresponds to which coordinate. You could label the axes. | {
"domain": "codereview.stackexchange",
"id": 43935,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, minesweeper",
"url": null
} |
beginner, c, calculator
Title: Trigonometric functions calculator
Question: This is a basic 6 trigonometric functions calculator that I will incorporate into my main calculator project. It works as intended, but the BUILD MESSAGES issue a warning, the warning being:
Warning: 'op' is used uninitialized in this program.
The program works as intended, the only problem being that it gives one warning. Understanding how functions work - am I missing something?
Does op = getOperation(op), not assign the value to op?
And if it doesn't, why does the program work properly?
Any other tips on how to make this program better would be much appreciated. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#ifdef M_PI
#define PI M_PI
#else
#define PI 3.14159265358979323846264338327950288420
#endif // M_PI
float degreesToRadians(float angle);
unsigned int getOperation(unsigned int op);
float sine(float degrees);
float cosine(float degrees);
float tangent(float degrees);
float sineInverse(float degrees);
float cosineInverse(float degrees);
float tangentInverse(float degrees);
int main()
{
float degrees;
unsigned int op;
op = getOperation(op);
printf("\nEnter the angle in degrees: ");
scanf("%f", °rees);
degrees = degreesToRadians(degrees);
switch(op)
{
case '1' :
sine(degrees);
break;
case '2':
cosine(degrees);
break;
case '3':
tangent(degrees);
break;
case '4':
sineInverse(degrees);
break;
case '5':
cosineInverse(degrees);
break;
case '6':
tangentInverse(degrees);
break;
default:
printf("You entered an invalid option!");
break;
}
return 0;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Degrees to Radians Function | {
"domain": "codereview.stackexchange",
"id": 43936,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, calculator",
"url": null
} |
beginner, c, calculator
float degreesToRadians( float degrees)
{
return degrees * (PI / 180);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
unsigned int getOperation(unsigned int op)
{
printf("Trigonometric Functions: \n");
printf("------------------------ \n");
printf("1. Sine Function\n");
printf("2. Cosine Function\n");
printf("3. Tangent Function\n");
printf("4. Sine Inverse Function\n");
printf("5. Cosine Inverse Function\n");
printf("6. Tangent Inverse Function\n");
op = getch();
return op;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Sine function
float sine(float degrees)
{
float result = sin(degrees);
printf("Answer: %.2f",result);
return result;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Cosine function
float cosine(float degrees)
{
float result = cos(degrees);
printf("Result: %.2f", result);
return result;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Tangent function
float tangent(float degrees)
{
float result = tan(degrees);
printf("Result: %.2f", result);
return result;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//Sine Inverse function | {
"domain": "codereview.stackexchange",
"id": 43936,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, calculator",
"url": null
} |
beginner, c, calculator
float sineInverse(float degrees)
{
float result = asin(degrees);
printf("Result: %.2f", result);
return result;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//Cosine Inverse function
float cosineInverse(float degrees)
{
float result = acos(degrees);
printf("Result: %.2f", result);
return result;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//Tangent Inverse function
float tangentInverse (float degrees)
{
float result = atan(degrees);
printf("Result: %.2f", result);
return result;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
Answer: Don't use arguments just to declare the variable
You have
unsigned int getOperation(unsigned int op)
then inside the function, you print some strings that don't have anything to do with op. The next lines that use op are
op = getch();
return op;
So you never use the argument op at all except as a declaration. You could instead say
unsigned int getOperation()
and
return getch();
And you would get the exact same result.
Note that getch is non-standard. getchar is more common (but operates slightly differently). I don't immediately find an example where getch returns an unsigned value, but as it's non-standard, its return type is implementation dependent.
Using a variable before initialization
Now, in your calling function, you have
unsigned int op;
op = getOperation(op);
and ask
Does op = getOperation(op), not assign the value to op?
Yes, it does. And that's why the program works. But that's not what the warning is telling you. Let's rewrite the code slightly:
unsigned int op;
getOperation(op); | {
"domain": "codereview.stackexchange",
"id": 43936,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, calculator",
"url": null
} |
beginner, c, calculator
getOperation(op);
This will give the same warning. Because, at this point, you have not initialized op.
Note that assignment is right associative and lower priority than a function call. This means that getOperation(op) will run before the assignment. Since the assignment is also the initialization of op, the warning is correct. You are attempting to pass op as an argument before initializing it. Then, after that, you initialize it. The compiler is not smart enough to realize that you never use the uninitialized value of op other than to pass it to the function.
Now, if you remove the argument, as suggested in the first section, you'll have
unsigned int op;
op = getOperation();
which will work without giving the warning. In most versions of C, you could write
unsigned int op = getOperation();
which is shorter.
Arc functions don't take angles
You call arcsine, arccosine, and arctangent functions with values in radians (that you call degrees). But these functions don't take angular measures as arguments. They take ratios between two sides as argument and return the angular measure (or arc) that corresponds with that ratio.
This is more than just a naming issue. Converting from degrees to radians on the values entered here can never return a meaningful result. It would make more sense to take two sides for those functions. Then you could calculate the ratio before passing that to the appropriate arc function. | {
"domain": "codereview.stackexchange",
"id": 43936,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, calculator",
"url": null
} |
database, postgresql
Title: Postgres DB design
Question: I need to develop a database to handle muting people in an online community. The DB needs to keep track of the currently muted people. When somebody gets unmuted, that entry gets moved to an archive table. People can only be muted by specific staff members. This is the code I came up with:
CREATE table sh_members
(
id bigint primary key,
name varchar(32) not null,
discriminator smallint not null,
display_name varchar(32) not null,
joined_at timestamp not null
);
create table sh_staff_members
(
id bigint,
constraint link foreign key (id) references sh_members (id),
primary key (id),
first_promotion timestamp not null,
last_promotion timestamp check (sh_staff_members.last_promotion > first_promotion)
);
create type mute_type as enum ('command', 'reaction');
create table current_mutes
(
member_id bigint not null,
constraint member foreign key (member_id) references sh_members (id) on delete set null,
muter_id bigint not null,
constraint muter foreign key (muter_id) references sh_staff_members (id) on delete set null,
primary key (member_id, muter_id),
mute_type mute_type not null,
mute_reason text not null,
message_link text,
duration interval,
muted_at timestamp not null
); | {
"domain": "codereview.stackexchange",
"id": 43937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "database, postgresql",
"url": null
} |
database, postgresql
create table mutes_archive
(
id serial primary key,
member_id bigint not null,
constraint member foreign key (member_id) references sh_members (id) on delete set null,
muter_id bigint not null,
constraint muter foreign key (muter_id) references sh_staff_members (id) on delete set null,
unmuter_id bigint not null,
constraint unmuter foreign key (unmuter_id) references sh_staff_members (id) on delete set null,
mute_type mute_type not null,
mute_reason text not null,
message_link text,
muted_at timestamp not null,
unmuted_at timestamp not null,
duration interval generated always as (unmuted_at - muted_at) stored,
unmute_reason text not null
);
What probably stands out most is the foreign key in sh_staff_members which also functions as a PK. While inheritance seems like a better tool to represent the is-a relationship between sh_staff_member and sh_member, using it is out of my skill level. Hence I decided to go for a 1:0..1 relationship between those tables.
When it comes to current_mutes, there can only be one entry per member_id. When that member gets unmuted, the entry gets moved into muted_archive. Note, it's intentionally possible for a staff member to mute themselves.
This is the schema I'm trying to go for:
So, I have a few questions:
Is this database properly normalized?
How do I write Postgres checks to ensure that sh_staff_members.id ∈ sh_members.id?
Other suggestions and improvements are certainly welcome!
Answer:
What probably stands out most is the foreign key in sh_staff_members which also functions as a PK. While inheritance seems like a better tool to represent the is-a relationship between sh_staff_member and sh_member, using it is out of my skill level. Hence I decided to go for a 1:0..1 relationship between those tables. | {
"domain": "codereview.stackexchange",
"id": 43937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "database, postgresql",
"url": null
} |
database, postgresql
IMHO, this is the most natural way to express is-a in an RDBMS and I see no issue with it.
Otherwise:
In some places you (properly, I think) include the primary key constraint as an unnamed, inline column constraint. In others, you have it as a table constraint, i.e. primary key (id). I prefer the first style, but you should be consistent.
Sometimes you name your constraints and sometimes you don't. I typically don't, but whatever you do you should be consistent.
joined_at and muted_at could receive a convenience default current_timestamp.
serial is a non-standard extension and you should instead prefer the generated always syntax, which is standard and you're already using elsewhere. | {
"domain": "codereview.stackexchange",
"id": 43937,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "database, postgresql",
"url": null
} |
rust, markdown
Title: Markdown code formatter
Question: With my rustymines 1 2 project, I realized, that it was cumbersome, to copy and paste all the code files into Markdown for review here. So I wrote a small program that formats source code files as Markdown for me:
src/main.rs:
use std::collections::HashMap;
use std::env::args;
use std::fs::File;
use std::io::{BufReader, Error, Read};
use std::path::Path;
use lazy_static::lazy_static;
lazy_static! {
static ref LANGUAGES: HashMap<&'static str, &'static str> = HashMap::from([
("c", "c"),
("cpp", "cpp"),
("h", "cpp"),
("py", "python"),
("rs", "rust"),
("toml", "toml"),
]);
}
fn read_file(file: &Path) -> Result<String, Error> {
let fh = File::open(file)?;
let mut buf_reader = BufReader::new(fh);
let mut content = String::new();
match buf_reader.read_to_string(&mut content) {
Ok(_) => Ok(content),
Err(code) => Err(code),
}
}
fn format_file(file: &Path) {
match read_file(file) {
Ok(text) => {
let extension = match file.extension() {
Some(suffix) => suffix.to_str().unwrap_or(""),
None => "",
};
let language = LANGUAGES.get(extension).unwrap_or(&"");
match file.to_str() {
Some(filename) => {
println!("`{}`:", filename);
println!("```{}\n{}```", language, text);
}
None => eprintln!("Could not extract file name."),
}
}
Err(code) => eprintln!("Error reading file: {}", code),
}
}
fn main() {
let args: Vec<String> = args().collect();
args.iter()
.enumerate()
.filter(|&(index, _)| 0 < index)
.map(|(_, filename)| Path::new(filename))
.for_each(format_file)
}
Cargo.toml:
[package]
name = "mdcode"
version = "0.1.0"
edition = "2021" | {
"domain": "codereview.stackexchange",
"id": 43938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, markdown",
"url": null
} |
rust, markdown
Cargo.toml:
[package]
name = "mdcode"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
lazy_static = "*"
The markdown for file names and code blocks above has been generated by the script itself (which technically makes it a quine, no?) like so:
$ target/release/mdcode src/main.rs Cargo.toml
I'd like to have feedback on what I could improve here.
Answer: Bug
Take a look at what happens if I combine block doc comments and doc test. This perfectly reasonable code:
/**
Adds two numbers
```
# use mdcode::add::add;
# fn main(){
assert_eq!(add(2, 2), 4);
assert_eq!(add(-2, 2), 0);
# }
```
*/
pub fn add(a:i32, b:i32) -> i32{
a + b
}
renders to this:
src/add.rs:
/**
Adds two numbers
use mdcode::add::add;
fn main(){
assert_eq!(add(2, 2), 4);
assert_eq!(add(-2, 2), 0);
}
*/
pub fn add(a:i32, b:i32) -> i32{
a + b
}```
Obviously not good. Either somehow escape the backticks or use indentation-based code blocks instead. Additionally, add a newline before the last set of backticks- I had to add an extra set of backticks to keep the code block from eating my post.
Take in an AsRef<Path> instead of &Path
It's more generic, and since most people using file-based APIs just have a string representing the path anyway, it makes their life easier.
Remember Iterator::skip exists
Fairly self-explanatory, and in conjunction with the previous tip, turns main into
fn main() {
args().skip(1).for_each(format_file);
} | {
"domain": "codereview.stackexchange",
"id": 43938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, markdown",
"url": null
} |
rust, markdown
which is much cleaner.
read_file already exists
There is a convenience function, std::fs::read_to_string to read a file from a string already. Your implementation wasn't bad or anything, but there's no need to reinvent the wheel.
Take advantage of Option's combinators
Option and Result have lots of convenient ways to combine and chain fallible functions. In particular, the match statement for getting the file extension should be
let extension = file
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or_default();
Consider using the log crate for logging
For a project of this size, the ad-hoc eprintln! based logging implementation you have is probably fine, but if your project gets bigger that approach very quickly becomes unmaintainable. Using log plus your favorite backend enables easily configurable logging suitable for whatever your project's needs may be.
Prefer once_cell to lazy_static
There's nothing wrong with lazy_static, but once_cell has more features and also mirrors the API of the equivalent unstable types in the standard library. Additionally, avoid setting the version to "*" as that is a very good way to cause weird version-related compilation errors, which really suck to deal with.
Set a few more fields in your Cargo.toml
Cargo.toml files have lots of supported keys, and you should set a few more of them. At minimum, you should probably set the authors and license keys. A few other keys, like repository and readme, would be ideal as well.
Final thoughts
Your code is pretty good overall. It seems like you've learned the language pretty well, but still have some work to do learning the standard library and ecosystem. Improved, but not quite complete code:
src/main.rs:
use std::collections::HashMap;
use std::env::args;
use std::path::Path;
use once_cell::sync::Lazy; | {
"domain": "codereview.stackexchange",
"id": 43938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, markdown",
"url": null
} |
rust, markdown
use once_cell::sync::Lazy;
static LANGUAGES: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
HashMap::from([
("c", "c"),
("cpp", "cpp"),
("h", "cpp"),
("py", "python"),
("rs", "rust"),
("toml", "toml"),
])
});
fn format_file<A: AsRef<Path>>(file: A) {
let file = file.as_ref();
match std::fs::read_to_string(file) {
Ok(text) => {
let extension = file
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or_default();
let language = LANGUAGES.get(extension).unwrap_or(&"");
//FIXME: escape the text properly, or use indentation
match file.to_str() {
Some(filename) => {
println!("`{}`:", filename);
println!(
"```{}\n{}{}```",
language,
text,
if !text.ends_with('\n') { "\n" } else { "" }
);
}
None => eprintln!("Could not extract file name."),
}
}
Err(code) => eprintln!("Error reading file: {}", code),
}
}
fn main() {
args().skip(1).for_each(format_file);
}
Cargo.toml:
[package]
name = "mdcode"
authors = ["your name here"]
version = "0.1.0"
edition = "2021"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
once_cell = "1.15" | {
"domain": "codereview.stackexchange",
"id": 43938,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, markdown",
"url": null
} |
c#, json, validation, api, .net-core
Title: Apply a schema validation against an HTTP request with JSON body | {
"domain": "codereview.stackexchange",
"id": 43939,
"lm_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#, json, validation, api, .net-core",
"url": null
} |
c#, json, validation, api, .net-core
Question: [HttpPost]
[Authorize("PublicCreateOrder")]
public async Task<ActionResult> CreateOrder(CancellationToken cancellationToken)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
//--------------> Performance measure Start <------------ FROM THIS POINT
StreamReader requestReader = new StreamReader(Request.Body);
JObject jsonRequest;
try
{
jsonRequest = JObject.Parse(await requestReader.ReadToEndAsync());
}
catch (Exception ex)
{
return BadRequest("Please send a metadata has the type of JSON.");
}
var filePath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\OrderSchema.json";
using (StreamReader fileReader = new StreamReader(filePath))
{
JSchema jsonSchema = JSchema.Parse(await fileReader.ReadToEndAsync());
IList<ValidationError> errors;
if (!jsonRequest.IsValid(jsonSchema, out errors))
{
List<ValidationError> newErrors = new List<ValidationError>();
new List<ValidationError>(errors).ForEach(error =>
{
if (error.ChildErrors.Count > 0)
newErrors.AddRange(error.ChildErrors);
else
newErrors.Add(error);
});
var errorsItems = errors.Select(error => new GetSchemaValidationResponse
{
Message = error.Message,
ErrorType = error.ErrorType.ToString(),
LineNumber = error.LineNumber,
LinePosition = error.LinePosition,
Path = error.Path
}).ToList();
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
//--------------> Performance measure Finish<------------ TO THIS POINT | {
"domain": "codereview.stackexchange",
"id": 43939,
"lm_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#, json, validation, api, .net-core",
"url": null
} |
c#, json, validation, api, .net-core
//--------------> Performance measure Finish<------------ TO THIS POINT
return BadRequest(errorsItems);
}
}
CreateOrderRequest request = JsonConvert.DeserializeObject<CreateOrderRequest>(jsonRequest.ToString()); | {
"domain": "codereview.stackexchange",
"id": 43939,
"lm_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#, json, validation, api, .net-core",
"url": null
} |
c#, json, validation, api, .net-core
In this code block i apply a json schema validation against an http request with json body. But because of this validation will perform against every request maybe it will cause a performance issues. For now, this code block took under 2ms but i want to improve the performance. Do you have any idea?
And also if you have an advice about code quality, i would be glad to know it.
Answer: Useless Copying
You're creating a lot of lists for no reasons. No need to copy one list to another just to iterate over it.
Separation of Concerns
The schema validation code pollutes the controller method. It's much better placed in a custom model binder or Filter | {
"domain": "codereview.stackexchange",
"id": 43939,
"lm_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#, json, validation, api, .net-core",
"url": null
} |
performance, c, hash-map, c99
Title: Implementation of Hashtable in C99
Question: I tried implementing a general purpose hashtable in C99.
The basic structure is I have a huge array of hashtable entries and each entry is the entry point to a doubly linked list so that in case there are hash collisions due to a poor hash function the data is automatically appended to the linked list and then while retrieving I compare the actual keys.
Implementation:
from cgl.h:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
// ...
#define CGL_utils_clamp(x, minl, maxl) \
(x < minl ? minl : (x > maxl ? maxl : x))
// ...
#define CGL_malloc(size) malloc(size)
#define CGL_free(ptr) free(ptr)
// ...
#ifndef CGL_HASHTABLE_MAX_KEY_SIZE
#define CGL_HASHTABLE_MAX_KEY_SIZE 256
#endif
struct CGL_hashtable_entry;
typedef struct CGL_hashtable_entry CGL_hashtable_entry;
struct CGL_hashtable;
typedef struct CGL_hashtable CGL_hashtable;
struct CGL_hashtable_iterator;
typedef struct CGL_hashtable_iterator CGL_hashtable_iterator;
typedef uint32_t(*CGL_hash_function)(const void*, size_t);
// ...
// From : http://www.azillionmonkeys.com/qed/hash.html
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define CGL_get16bits(d) (*((const uint16_t *) (d)))
#endif
#if !defined (CGL_get16bits)
#define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
// ...
uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
{
const uint8_t* data = (const uint8_t*)dat;
uint32_t hash = (uint32_t)len;
uint32_t tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2; | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += CGL_get16bits (data);
tmp = (CGL_get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += CGL_get16bits (data);
hash ^= hash << 16;
hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
hash += hash >> 11;
break;
case 2: hash += CGL_get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += (signed char)*data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
struct CGL_hashtable_entry
{
bool set;
uint8_t key[CGL_HASHTABLE_MAX_KEY_SIZE];
void* value;
size_t value_size;
CGL_hashtable_entry* prev_entry; // prev entry in the linked list with same hash
CGL_hashtable_entry* next_entry; // next entry in the linked list with same hash
};
struct CGL_hashtable
{
CGL_hashtable_entry* entries;
size_t table_size;
size_t key_size;
CGL_hash_function hash_function;
size_t count;
};
struct CGL_hashtable_iterator
{
CGL_hashtable* hashtable;
CGL_hashtable_entry* current_entry;
uint32_t current_index;
};
static void __CGL_hashtable_entry_destroy(CGL_hashtable_entry* entry, bool destory_current)
{
if(entry == NULL) return;
if(entry->next_entry != NULL) __CGL_hashtable_entry_destroy(entry->next_entry, true);
if(entry->value) CGL_free(entry->value);
if(destory_current) CGL_free(entry);
} | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
{
*key_size = table->key_size;
if(*key_size == 0) *key_size = strlen((const char*)key);
*key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
uint32_t hash = table->hash_function(key, *key_size);
*hash_table_index = hash % table->table_size;
}
static CGL_hashtable_entry* __CGL_hashtable_get_entry_ptr(CGL_hashtable* table, const void* key)
{
size_t key_size, hash_table_index;
__CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
CGL_hashtable_entry* current_entry = &table->entries[hash_table_index];
while(current_entry != NULL)
{
if(memcmp(current_entry->key, key, key_size) == 0) return current_entry;
current_entry = current_entry->next_entry;
}
return NULL;
}
CGL_hashtable* CGL_hashtable_create(size_t table_size, size_t key_size)
{
CGL_hashtable* table = (CGL_hashtable*)CGL_malloc(sizeof(CGL_hashtable));
table->count = 0;
table->entries = (CGL_hashtable_entry*)CGL_malloc(sizeof(CGL_hashtable_entry) * table_size);
memset(table->entries, 0, (sizeof(CGL_hashtable_entry) * table_size));
table->key_size = key_size;
table->table_size = table_size;
table->hash_function = CGL_utils_super_fast_hash;
return table;
}
void CGL_hashtable_destroy(CGL_hashtable* table)
{
// destroy entries linked lists (if any) and data values
CGL_hashtable_entry* entries = table->entries;
for(size_t i = 0 ; i < table->table_size ; i++)
__CGL_hashtable_entry_destroy(&entries[i], false);
CGL_free(table->entries);
CGL_free(table);
} | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
void CGL_hashtable_set(CGL_hashtable* table, const void* key, const void* value, size_t value_size)
{
size_t key_size, hash_table_index;
__CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
if(entry_ptr)
{
entry_ptr->value_size = value_size;
entry_ptr->value = NULL;
if(value_size > 0)
{
entry_ptr->value = CGL_malloc(value_size);
memcpy(entry_ptr->value, value, value_size);
}
}
else
{
CGL_hashtable_entry entry;
entry.set = true;
entry.next_entry = NULL;
entry.prev_entry = NULL;
memcpy(entry.key, key, key_size);
entry.value_size = value_size;
entry.value = NULL;
if(value_size > 0)
{
entry.value = CGL_malloc(value_size);
memcpy(entry.value, value, value_size);
}
if(table->entries[hash_table_index].set)
{
CGL_hashtable_entry* entry_to_place = &table->entries[hash_table_index];
while(entry_to_place->next_entry != NULL) entry_to_place = entry_to_place->next_entry;
entry.prev_entry = entry_to_place;
entry_to_place->next_entry = (CGL_hashtable_entry*)CGL_malloc(sizeof(CGL_hashtable_entry));
memcpy(entry_to_place->next_entry, &entry, sizeof(CGL_hashtable_entry));
}
else
{
CGL_hashtable_entry* next_entry = table->entries[hash_table_index].next_entry;
memcpy(&table->entries[hash_table_index], &entry, sizeof(CGL_hashtable_entry));
table->entries[hash_table_index].next_entry = next_entry;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
size_t CGL_hashtable_get(CGL_hashtable* table, const void* key, void* value)
{
CGL_hashtable_entry* entry = __CGL_hashtable_get_entry_ptr(table, key);
if(entry && value) memcpy(value, entry->value, entry->value_size);
if(entry) return entry->value_size;
return 0;
}
bool CGL_hashtable_exists(CGL_hashtable* table, const void* key)
{
return __CGL_hashtable_get_entry_ptr(table, key) != NULL;
// OR
//return CGL_hashtable_get(table, key, NULL) != 0;
}
bool CGL_hashtable_remove(CGL_hashtable* table, const void* key)
{
CGL_hashtable_entry* entry = __CGL_hashtable_get_entry_ptr(table, key);
if(entry)
{
if(entry->value) CGL_free(entry->value);
memset(entry->key, 0, CGL_HASHTABLE_MAX_KEY_SIZE);
entry->set = false;
if(entry->prev_entry)
{
entry->prev_entry->next_entry = entry->next_entry;
CGL_free(entry);
}
}
return entry != NULL;
}
Usage:
int main (void) {
char buffer[1024];
CGL_hashtable* table = CGL_hashtable_create(10000, 0);
int idata = 0;
float fdata = 0.0f;
CGL_hashtable_set(table, "Name", "Jaysmito", 9);
idata = 18;
CGL_hashtable_set(table, "Age", &idata, sizeof(idata));
fdata = 454.4854f;
CGL_hashtable_set(table, "Float Data", &fdata, sizeof(fdata));
// print
CGL_hashtable_get(table, "Age", buffer);
printf("Age : %d\n", *(int*)buffer);
CGL_hashtable_get(table, "Float Data", buffer);
printf("Float Data : %f\n", *(float*)buffer);
CGL_hashtable_get(table, "Name", buffer);
printf("Name : %s\n", buffer);
CGL_hashtable_set(table, "Name", "Jack", 5);
CGL_hashtable_get(table, "Name", buffer);
printf("Name 2 : %s\n", buffer);
CGL_hashtable_destroy(table);
} | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
Answer: Enable more warnings
Before you ask for a review, get your compiler to review your code for you. This can help identify any oversights. I got a quite detailed analysis from GCC:
gcc-12 -std=c17 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer -Wconversion 280098.c -o 280098
280098.c: In function ‘CGL_utils_super_fast_hash’:
280098.c:67:26: warning: conversion to ‘uint32_t’ {aka ‘unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
67 | hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
| ^~
280098.c:74:26: warning: conversion to ‘uint32_t’ {aka ‘unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
74 | case 1: hash += (signed char)*data;
| ^~
280098.c: In function ‘CGL_hashtable_create’:
280098.c:151:18: warning: dereference of possibly-NULL ‘table’ [CWE-690] [-Wanalyzer-possible-null-dereference]
151 | table->count = 0;
| ~~~~~~~~~~~~~^~~
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | |
| | (1) entry to ‘main’
| 251 | char buffer[1024];
| 252 | CGL_hashtable* table = CGL_hashtable_create(10000, 0);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling ‘CGL_hashtable_create’ from ‘main’
|
+--> ‘CGL_hashtable_create’: event 3
|
| 148 | CGL_hashtable* CGL_hashtable_create(size_t table_size, size_t key_size)
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (3) entry to ‘CGL_hashtable_create’
|
‘CGL_hashtable_create’: event 4
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
‘CGL_hashtable_create’: event 4
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (4) this call could return NULL
280098.c:150:44: note: in expansion of macro ‘CGL_malloc’
| 150 | CGL_hashtable* table = (CGL_hashtable*)CGL_malloc(sizeof(CGL_hashtable));
| | ^~~~~~~~~~
|
‘CGL_hashtable_create’: event 5
|
| 151 | table->count = 0;
| | ~~~~~~~~~~~~~^~~
| | |
| | (5) ‘table’ could be NULL: unchecked value from (4)
|
280098.c:153:5: warning: use of possibly-NULL ‘*table.entries’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]
153 | memset(table->entries, 0, (sizeof(CGL_hashtable_entry) * table_size));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | |
| | (1) entry to ‘main’
| 251 | char buffer[1024];
| 252 | CGL_hashtable* table = CGL_hashtable_create(10000, 0);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling ‘CGL_hashtable_create’ from ‘main’
|
+--> ‘CGL_hashtable_create’: event 3
|
| 148 | CGL_hashtable* CGL_hashtable_create(size_t table_size, size_t key_size)
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (3) entry to ‘CGL_hashtable_create’
|
‘CGL_hashtable_create’: event 4
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
‘CGL_hashtable_create’: event 4
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (4) this call could return NULL
280098.c:152:44: note: in expansion of macro ‘CGL_malloc’
| 152 | table->entries = (CGL_hashtable_entry*)CGL_malloc(sizeof(CGL_hashtable_entry) * table_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_create’: event 5
|
| 153 | memset(table->entries, 0, (sizeof(CGL_hashtable_entry) * table_size));
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (5) argument 1 (‘*table.entries’) from (4) could be NULL where non-null expected
|
In file included from 280098.c:5:
/usr/include/string.h:61:14: note: argument 1 of ‘memset’ must be non-null
61 | extern void *memset (void *__s, int __c, size_t __n) __THROW __nonnull ((1));
| ^~~~~~
280098.c: In function ‘CGL_hashtable_set’:
280098.c:182:13: warning: leak of ‘<unknown>’ [CWE-401] [-Wanalyzer-malloc-leak]
182 | memcpy(entry_ptr->value, value, value_size);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | |
| | (1) entry to ‘main’
|......
| 255 | CGL_hashtable_set(table, "Name", "Jaysmito", 9);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling ‘CGL_hashtable_set’ from ‘main’
|
+--> ‘CGL_hashtable_set’: events 3-4
|
| 170 | void CGL_hashtable_set(CGL_hashtable* table, const void* key, const void* value, size_t value_size) | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ^~~~~~~~~~~~~~~~~
| | |
| | (3) entry to ‘CGL_hashtable_set’
|......
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 5-7
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (5) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (7) ...to here
| | (6) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 8
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (8) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 9
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (9) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 10
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (10) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 11-14
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (11) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | | | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~
| | |
| | (12) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (13) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (14) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 15
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (15) ...to here
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 16-17
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (16) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3; | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (17) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 18
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (18) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘CGL_hashtable_set’: events 19-20
|
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (19) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_key_size_and_table_index’
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (20) calling ‘__CGL_hashtable_get_entry_ptr’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_entry_ptr’: events 21-22
|
| 134 | static CGL_hashtable_entry* __CGL_hashtable_get_entry_ptr(CGL_hashtable* table, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (21) entry to ‘__CGL_hashtable_get_entry_ptr’
|......
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (22) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘__CGL_hashtable_get_entry_ptr’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 23-25
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (23) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (25) ...to here
| | (24) following ‘true’ branch...
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 26
|
| 10 | (x < minl ? minl : (x > maxl ? maxl : x)) | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (26) following ‘true’ branch...
280098.c:129:17: note: in expansion of macro ‘CGL_utils_clamp’
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~~~~~~~
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 27
|
| 129 | *key_size = CGL_utils_clamp(*key_size, 1, CGL_HASHTABLE_MAX_KEY_SIZE);
| | ^~~~~~~~~
| | |
| | (27) ...to here
280098.c:10:48: note: in definition of macro ‘CGL_utils_clamp’
| 10 | (x < minl ? minl : (x > maxl ? maxl : x))
| | ^
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 28
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (28) calling ‘CGL_utils_super_fast_hash’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
+--> ‘CGL_utils_super_fast_hash’: events 29-32
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
|
| 42 | uint32_t CGL_utils_super_fast_hash(const void* dat, size_t len)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (29) entry to ‘CGL_utils_super_fast_hash’
|......
| 49 | if (len <= 0 || data == NULL) return 0;
| | ~
| | |
| | (30) following ‘false’ branch...
| 50 |
| 51 | rem = len & 3;
| | ~~~~~~~
| | |
| | (31) ...to here
|......
| 55 | for (;len > 0; len--) {
| | ~~~~~~~
| | |
| | (32) following ‘true’ branch (when ‘len != 0’)...
|
‘CGL_utils_super_fast_hash’: event 33
|
| 38 | #define CGL_get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
| | ^
| | |
| | (33) ...to here | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
280098.c:56:22: note: in expansion of macro ‘CGL_get16bits’
| 56 | hash += CGL_get16bits (data);
| | ^~~~~~~~~~~~~
|
‘CGL_utils_super_fast_hash’: events 34-35
|
| 64 | switch (rem) {
| | ^~~~~~
| | |
| | (34) following ‘default:’ branch...
|......
| 80 | hash ^= hash << 3;
| | ~~~~~~~~~
| | |
| | (35) ...to here
|
<------+
|
‘__CGL_hashtable_get_key_size_and_table_index’: event 36
|
| 130 | uint32_t hash = table->hash_function(key, *key_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (36) returning to ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_utils_super_fast_hash’
|
<------+
|
‘__CGL_hashtable_get_entry_ptr’: event 37
|
| 137 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | | | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| | |
| | (37) returning to ‘__CGL_hashtable_get_entry_ptr’ from ‘__CGL_hashtable_get_key_size_and_table_index’
|
‘__CGL_hashtable_get_entry_ptr’: events 38-39
|
| 139 | while(current_entry != NULL)
| | ^
| | |
| | (38) following ‘true’ branch (when ‘current_entry’ is non-NULL)...
| 140 | {
| 141 | if(memcmp(current_entry->key, key, key_size) == 0) return current_entry;
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (39) ...to here
|
<------+
|
‘CGL_hashtable_set’: events 40-43
|
| 174 | CGL_hashtable_entry* entry_ptr = __CGL_hashtable_get_entry_ptr(table, key);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (40) returning to ‘CGL_hashtable_set’ from ‘__CGL_hashtable_get_entry_ptr’
| 175 | if(entry_ptr)
| | ~
| | |
| | (41) following ‘true’ branch (when ‘entry_ptr’ is non-NULL)...
| 176 | {
| 177 | entry_ptr->value_size = value_size;
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (42) ...to here
| 178 | entry_ptr->value = NULL;
| 179 | if(value_size > 0) | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
| 178 | entry_ptr->value = NULL;
| 179 | if(value_size > 0)
| | ~
| | |
| | (43) following ‘true’ branch (when ‘value_size != 0’)...
|
‘CGL_hashtable_set’: event 44
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (44) ...to here
280098.c:181:32: note: in expansion of macro ‘CGL_malloc’
| 181 | entry_ptr->value = CGL_malloc(value_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: event 45
|
| 12 | #define CGL_malloc(size) malloc(size)
| | ^~~~~~~~~~~~
| | |
| | (45) allocated here
280098.c:181:32: note: in expansion of macro ‘CGL_malloc’
| 181 | entry_ptr->value = CGL_malloc(value_size);
| | ^~~~~~~~~~
|
‘CGL_hashtable_set’: event 46
|
| 182 | memcpy(entry_ptr->value, value, value_size);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (46) ‘<unknown>’ leaks here; was allocated at (45)
|
280098.c:197:13: warning: use of possibly-NULL ‘entry.value’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]
197 | memcpy(entry.value, value, value_size);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | | | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
performance, c, hash-map, c99
‘main’: events 1-2
|
| 250 | int main (void) {
| | ^~~~
| | |
| | (1) entry to ‘main’
|......
| 255 | CGL_hashtable_set(table, "Name", "Jaysmito", 9);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling ‘CGL_hashtable_set’ from ‘main’
|
+--> ‘CGL_hashtable_set’: events 3-4
|
| 170 | void CGL_hashtable_set(CGL_hashtable* table, const void* key, const void* value, size_t value_size)
| | ^~~~~~~~~~~~~~~~~
| | |
| | (3) entry to ‘CGL_hashtable_set’
|......
| 173 | __CGL_hashtable_get_key_size_and_table_index(table, &key_size, &hash_table_index, key);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling ‘__CGL_hashtable_get_key_size_and_table_index’ from ‘CGL_hashtable_set’
|
+--> ‘__CGL_hashtable_get_key_size_and_table_index’: events 5-7
|
| 125 | static void __CGL_hashtable_get_key_size_and_table_index(CGL_hashtable* table, size_t* key_size, size_t* hash_table_index, const void* key)
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (5) entry to ‘__CGL_hashtable_get_key_size_and_table_index’
|......
| 128 | if(*key_size == 0) *key_size = strlen((const char*)key);
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (7) ...to here
| | (6) following ‘true’ branch...
| | {
"domain": "codereview.stackexchange",
"id": 43940,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, hash-map, c99",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.