text stringlengths 1 2.12k | source dict |
|---|---|
php, object-oriented, classes, php7
/**
* used to hold tag name while building HTML
* to reduce the number of times tag name should be passed as parameter
* @var string
*/
private $tag = "";
/** used to build tag
* @var string
*/
private $tag_build = "";
/**
* flag for when a <select> is intended
* @var boolean
*/
private $select_options_required = false;
/**
* flag to check if <option>'s are set
* @var boolean
*/
private $select_options_set = false;
// as I'm using PHP 7.0.33 visibility is not allowed for constants
// all this constants should be private | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
const FORM_TAGS = ['form', 'input', 'label', 'select', 'textarea', 'button', 'fieldset', 'legend',
'datalist', 'output', 'option', 'optgroup'];
const FORM_TAGS_TYPES = array(
'input' => ['button', 'checkbox', 'color', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month',
'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week'],
'button' => ['submit', 'reset', 'button'],
);
const FORM_TAGS_COMMON_ATTR = ['id', 'class', 'accesskey', 'style', 'tabindex'];
const FORM_TAGS_REQUIRED_ATTR = array(
'form' => ['name', 'action', 'method'],
'select' => ['name'],
'textarea' => ['name', 'cols', 'rows'],
'button' => ['name', 'value'],
'option' => ['value', 'text'],
'input' => ['type', 'name', 'value'],
'optgroup' => ['label'],
);
const FORM_TAGS_SPECIFIC_ATTR = array(
'form' => ['target', 'enctype', 'autocomplete', 'rel', 'novalidate'],
'label' => ['for'],
'select' => ['autocomplete', 'autofocus', 'disabled', 'form', 'multiple', 'required', 'size'],
'textarea' => ['autocomplete', 'autofocus', 'disabled', 'form', 'maxlength', 'minlength', 'placeholder', 'readonly', 'required'],
'button' => ['autofocus', 'disabled', 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 'formnovalidate'],
'fieldset' => ['disabled', 'form'],
'legend' => [],
'datalist' => [],
'output' => ['for', 'form'],
'option' => ['disabled', 'label', 'selected'],
'optgroup' => ['disabled'],
'input' => ['disabled', 'required'],
'checkbox' => ['checked'],
'color' => [],
'date' => ['max', 'min', 'step'],
'datetime-local' => ['max', 'min', 'step'],
'email' => ['list', 'maxlength', 'minlength', 'multiple', 'pattern', 'placeholder', 'readonly', 'size'], | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
'file' => ['accept', 'capture', 'multiple'],
'hidden' => [],
'image' => ['alt', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'src', 'width'],
'month' => ['list', 'max', 'min', 'readonly', 'step'],
'number' => ['list', 'max', 'min', 'placeholder', 'readonly', 'step'],
'password' => ['maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size'],
'radio' => ['checked', 'required'],
'range' => ['list', 'max', 'min', 'step'],
'reset' => [],
'search' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'],
'submit' => ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'],
'tel' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size'],
'text' => ['autofocus', 'list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'],
'time' => ['list', 'max', 'min', 'readonly', 'step'],
'url' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'],
'week' => ['max', 'min', 'readonly', 'step']
);
const FORM_TAGS_FORBIDDEN_ATTR = []; // to be implemented in the future
// fieldsets closing is treated in render() method
const FORM_TAGS_CLOSING = ['label', 'select', 'textarea', 'legend', 'option', 'optgroup'];
const FORM_BOOLEAN_ATTR = ['required', 'autofocus', 'multiple', 'checked']; | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
/**
*
* @param array $form Asociative array where the keys are the form tag
* attributes and the values the attribute's value
* @throws Exception
*
* Attributes name, action and method are mandatory and cannot be empty.
* The rest of the attributes, if set must have a valid value.
*
* Usage:
*
* $form = new Form(['name'=>'myform', 'action'=>'action.php', 'method'=>'post']);
*
* Result:
*
* <form name='myform' action='action.php' method='post'>
*
*/
public function __construct(array $form_attributes)
{
$output = "";
$this->check_attributes("form", $form_attributes);
$output = '<form';
foreach ($form_attributes as $attribute => $value) {
$output .= " $attribute";
if (!in_array($attribute, self::FORM_BOOLEAN_ATTR)) {
$output .= "=\"$value\"";
}
}
$output .= '>';
$this->output[] = $output;
}
public function add_tag(string $element): bool
{
$this->check_unset_select();
// as fieldsets are treated differently and when they have no
// attributes set needs the trailing '>'
if (
($this->tag == "fieldset") and
(strpos($this->tag_build, -1) != ">")
) {
$this->output[] = $this->tag_build . ">";
}
$this->tag = "";
$this->tag_build = "";
$this->select_options_required = false;
$this->select_options_set = false;
$this->check_element($element);
$this->tag = $element;
$this->tag_build = "<" . $element;
if ($element == "select") {
$this->select_options_required = true;
}
return true;
}
public function add_tag_attributes(array $attributes): bool
{
$this->check_attributes($this->tag, $attributes); | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
if (array_key_exists($this->tag, self::FORM_TAGS_TYPES)) {
$this->check_element_type($attributes["type"]);
}
foreach ($attributes as $attribute => $value) {
if ($attribute != "text") {
$this->tag_build .= " $attribute";
if (!in_array($attribute, self::FORM_BOOLEAN_ATTR)) {
$this->tag_build .= "=\"$value\"";
}
}
}
$this->tag_build .= ">";
if (in_array($this->tag, ["label", "textarea", "legend"])) {
if (array_key_exists("text", $attributes)) {
$this->tag_build .= $attributes["text"] ?? "";
}
$this->tag_build .= "</" . $this->tag . ">";
}
if ($this->tag != "select") {
$this->output[] = $this->tag_build;
}
return true;
}
public function add_tag_options(array $options, array $selected = []): bool
{
$optgroup = false;
if ($this->tag != "select") {
throw new Exception("Options are only valid for select tag");
}
if (count($options) < 1) {
throw new Exception("select tag must have at least one option");
}
// check if optgroup
if (count($options) != count($options, COUNT_RECURSIVE)) {
$optgroup = true;
}
foreach ($options as $value => $text) {
if ($optgroup) {
$this->tag_build .= "\n<optgroup label=\"$value\">";
foreach ($text as $opt_value => $opt_text) {
$this->tag_build .= "\n<option value=\"$opt_value\"";
if (in_array($opt_value, $selected)) {
$this->tag_build .= " selected";
} | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
$this->tag_build .= ">$opt_text</option>";
}
$this->tag_build .= "\n</optgroup>"; // this is not mandatory
} else {
$this->tag_build .= "\n<option value=\"$value\"";
if (in_array($value, $selected)) {
$this->tag_build .= " selected";
}
$this->tag_build .= ">$text</option>";
}
}
$this->tag_build .= "\n</select>";
$this->select_options_set = true;
$this->output[] = $this->tag_build;
unset($this->tag_build);
return true;
}
public function render(): string
{
$open_fieldsets = 0;
$output = "";
$this->check_unset_select();
foreach ($this->output as $element) {
if (strpos($element, "fieldset") !== false) {
if ($open_fieldsets > 0) {
$output .= "\n</fieldset>";
$open_fieldsets--;
}
$open_fieldsets++;
}
$output .= "\n$element";
}
while ($open_fieldsets != 0) {
$output .= "\n</fieldset>";
$open_fieldsets--;
}
$output .= "\n</form>";
unset($this->output); // prevents double rendering
return $output;
}
/**
* Checks if an HTML form tag is valid
* @param string $declared_element
* @throws Exception
* @return boolean
*
* As said, PHP 7.0.33 does not allow void return type
*
*/
private function check_element (string $declared_element): bool
{
if (strlen($declared_element) < 1) {
throw new Exception("Form tag/element must be a non empty string");
}
if (in_array($declared_element, self::FORM_TAGS)) {
return true;
}
throw new Exception("'$declared_element': illegal form (or type of) element");
} | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
throw new Exception("'$declared_element': illegal form (or type of) element");
}
/**
* Checks if input or button has an allowed type
* @param string $type
* @throws Exception
* @return bool
*
* As said, PHP 7.0.33 does not allow void return type
*/
private function check_element_type(string $type): bool
{
if (strlen($type) == 0) {
throw new Exception($this->tag . " type cannot be an empty string");
}
foreach (self::FORM_TAGS_TYPES as $element => $types) {
if (
($this->tag == $element) and
in_array($type, $types)
) {
return true;
}
}
throw new Exception("'$type' type for '" . $this->tag . "' is not valid");
}
/**
* Checks attributes
*
* @param string $element
* @param array $attributes
* @throws Exception
* @return bool
*
* This method checks for mandatory attributes to be present. Also checks
* for non mandatory and common attributes and ignores the rest.
*
* As said, PHP 7.0.33 does not allow void return type
*/
private function check_attributes (string $element, array $attributes): bool
{
foreach (self::FORM_TAGS_REQUIRED_ATTR[$element] ?? [] as $attribute) {
if (!array_key_exists($attribute, $attributes)) {
throw new Exception("Attribute '$attribute' for tag '$element' is mandatory");
} | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
// if attribute is not value or text, and it's not a boolean
// attribute and its length is 0... not valid
if (
($attribute != "value") and
($attribute != "text") and
(!in_array($attribute, self::FORM_BOOLEAN_ATTR)) and
(strlen($attributes[$attribute]) == 0)
) {
throw new Exception("Attribute '$attribute' value cannot be an empty string");
}
}
return true;
}
/**
* Check's if select tag options where set
* @throws Exception
* @return bool
*
* This function is used in add_tag() and render() methods.
*
* As said, PHP 7.0.33 does not allow void return type
*/
private function check_unset_select(): bool
{
// check if previous tag was "select" and if options were set
if (
($this->tag == "select") and
!$this->select_options_set
) {
throw new Exception("Options for select are mandatory");
}
return true;
}
}
Answer: Review
Related to the code itself, the approach on array parameters, efficiency and ease of use, are there any suggestions?
The code has come a long way since the first version posted.
At first glance it doesn't seem overly inefficient. The calls to check* methods typically come early in methods before the main processing (e.g. looping over attributes).
If there is a goal of optimizing for speed then one could considering using simple for loops instead of foreach loops. I don't expect the speed gains to be much but when making a library it is something to consider.
Suggestions
Consider Supported PHP Versions
I am using PHP 7.0.33 | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
I am using PHP 7.0.33
If you have control over the PHP version then it would be wise to update it, or if not then it would be wise to request it be updated. At the time of writing there is Active support for version 8.1 and 8.2, Security fixes only for 8.0 and End of life support for 7.2 and earlier. Hence versions like 7.0.33 "may be exposed to unpatched security vulnerabilities." Additionally, PHP 8 has improved performance and numerous other features.
Utilize different string delineators
In the Form constructor there is a loop over the attributes. Within the loop is this conditional block:
if (!in_array($attribute, self::FORM_BOOLEAN_ATTR)) {
$output .= "=\"$value\"";
}
The HTML specification allows for multiple ways to specify attribute values, including Single-quoted attribute value syntax or Double-quoted attribute value syntax so single quotes could be used instead, which requires no escape characters:
if (!in_array($attribute, self::FORM_BOOLEAN_ATTR)) {
$output .= "='$value'";
}
Use strict type comparisons where possible
It is a good habit to use strict equality operators whenever possible. It may be faster since no type casting would be required. There are some strict type comparisons already - for example, in the render method:
foreach ($this->output as $element) {
if (strpos($element, "fieldset") !== false) {
In the add_tag() method there are a couple loose equality checks:
if (
($this->tag == "fieldset") and
(strpos($this->tag_build, -1) != ">")
) {
$this->output[] = $this->tag_build . ">";
}
and towards the end:
if ($element == "select") {
The property $this->tag is a string and parameter $element has a type declared: string, so strict equality can be used in both places.
Re-consider operators given precedence
In mickmackusa's review of the previous code the following was mentioned:
I personally never use and or or in PHP code. This helps to avoid precedence issues and assures code consistency. | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
php, object-oriented, classes, php7
PHP has two variations for logical AND i.e. and and && (as well as for logical OR: or and ||). Note that and has lower precedence than many other operators including assignment - =. The code above still uses and with conditions enclosed in parentheses. It would be a good habit to use && instead for cases where parentheses may not be present. As this StackOverflow answer illustrates it can lead to unintended consequences in some scenarios. | {
"domain": "codereview.stackexchange",
"id": 44692,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, classes, php7",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
Title: Comparison of lists of intervals
Question: From the following script, the "similarity" function should be callable to compare two sets of lists and return a certain similarity score. The elements of the lists represent intervals, so [12,16] represents 12, 13, 14, 15 and 16. From the sets, the lists are compared one by one. So the first lists from both sets are compared to each other only, the second lists to each other only, and so on. The sets are to be given in text files, so the input to the "similarity" function would be similar to the following image: | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
I am wondering how my code could be improved, with regard to runtime, memory usage and readability. I will explain the used functions in greater detail so you know what their general purpose is, though I hope the comments in the code itself are clear enough also.
The "ls" function takes two lists as input and computes a metric based on how many intervals from the first list overlap with at least one interval of the second list. It also checks whether the input is correct.
As this function is sensitive to the order in which the lists are given, it is done for both possible orders. Then the "sym_ls" function is used to take the average of the two outputs.
Then the "ss" function applies the above functions to all the lists of the sets, so the total similarity score between the sets is calculated (an average of the scores of similarity between the individual lists).
Finally, the "similarity" function opens the text files containing the data, cleans out the data so it can be used as input to the "ss" function and then applies this "ss" function, after which the final similarity score is saved to a new text file.
Please let me know what parts of the code could be written more concisely, efficiently and whether the comments are clear or not, and of course how to improve. Eventually the code should be executed by importing the "similarity" function from the .py file, and calling it with correct input arguments.
# import necessary modules
import ast | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
# define functions needed for similarity computation
def ls(list1, list2):
'''
This function determines the similarity between the two given lists,
list1 and list2, using overlapping intervals.
The input (list1 and list2), should be lists containing lists of 2 integers,
of which the second integer is greater than the first.
'''
# overlap variable is set to 0 for every new computation
overlap = 0
# loop through the intervals to identify the number of intervals in list1
# that have an overlap with at least one interval in list2
for inter1 in list1:
for inter2 in list2:
# check whether intervals are correclty syntaxed
if len(inter1) != 2 or len(inter2) != 2:
print("Error ls: intervals are expected to be represented by two integers, not more or less.")
break
elif inter1[0] >= inter1[1] or inter2[0] >= inter2[1]:
print("Error ls: the first integer representing an interval should be lesser than the second.")
break
else:
# determine whether there is overlap
if inter1[0] >= inter2[0] and inter1[0] <= inter2[1]:
overlap += 1
break
elif inter1[1] >= inter2[0] and inter1[1] <= inter2[1]:
overlap += 1
break
elif inter1[0] < inter2[0] and inter1[1] > inter2[1]:
overlap += 1
break
# determine the maximum of the lengths of list1 and list2
maxlen = max(len(list1), len(list2))
# compute the similarity (ls)
ls = overlap / maxlen
return ls | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
return ls
def sym_ls(ls1, ls2):
'''
This function computes the symmetric version of the similarity between two
lists. It does so by taking the average of the two similarities.
The input (ls1 and ls2), should be real numbers in [0,1].
'''
# check whether input is within the expected range ([0,1])
if (ls1 < 0 or ls1 > 1) or (ls2 < 0 or ls2 > 1):
print("Error sym_ls: similarity metrics as input should be a value in [0,1], check the input.")
else:
# calculate the average similarity
symmetric_ls = (ls1 + ls2) / 2
return symmetric_ls
def ss(set1, set2):
'''
This function computes the similarity between two sets of lists of intervals.
It does so by applying the ls functions on the different set elements. Then,
using the sym_ls function, the symmetric similarities are computed. Finally,
the global set similarity is calculated and returned as S.
The input (set1 and set2) should be lists with lists as elements. These list-
elements have intervals as elements. Both sets should have an equal amount of
elements.
'''
# initialize variable to sum up all symmetric similarity values
symmetric_similarity_total = 0
# for every ith element of both sets, apply the ls function to them
# and add the results to the similarity lists
for i in range(len(set1)):
symmetric_similarity_total += sym_ls(ls(set1[i], set2[i]), ls(set2[i], set1[i]))
# compute set similarity metric, S
S = symmetric_similarity_total / len(set1)
return S | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
def similarity(set_1, set_2, outfile):
# open the textfiles and read in its contents
set1_data = open(set_1, "r")
set2_data = open(set_2, "r")
S1 = set1_data.readlines()
S2 = set2_data.readlines()
set1_data.close()
set2_data.close()
# loop through the set elements to clean up the data
for i in range(len(S1)):
# check for equal sizes of sets
if S1[i][-1] == "\n" and S2[i][-1] != "\n":
print("Error get_sets: Set1 seems to contain more elements than Set2.")
break
elif S1[i][-1] != "\n" and S2[i][-1] == "\n":
print("Error get_sets: Set2 seems to contain more elements than Set1.")
break
else:
# clean the data and convert it to the right type
S1[i] = list(ast.literal_eval(S1[i].replace("\n", "")))
S2[i] = list(ast.literal_eval(S2[i].replace("\n", "")))
S = round(ss(S1, S2), 2)
# write the similarity metric S to a textfile
output_file = open(outfile, "x")
output_file.write("The similarity metric S is: {}".format(S))
output_file.close()
Answer: You asked about performance and complexity. In that regard, the problem is that you naively test each range against each of the other ranges, which gives you O(n²) runtime complexity. Like so:
for inter1 in list1:
for inter2 in list2:
You can easily improve complexity by using a datastructure that allows fast lookup, like a sorted list with binary search, which results in O(n log n) complexity. Apart from performance, there's a few more issues with your code. Let's start with this piece:
# check whether input is within the expected range ([0,1])
if (ls1 < 0 or ls1 > 1) or (ls2 < 0 or ls2 > 1):
print("Error sym_ls: similarity metrics as input should be a value in [0,1], check the input.")
else:
# calculate the average similarity
symmetric_ls = (ls1 + ls2) / 2 | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
First, you don't need the error check here because it's not a user-visible interface. There is no way how you would end up with a value outside the correct range. This line of code has never been executed and will never be executed. Delete it. Secondly, if you want an error check, use assert. Like this:
assert 0 <= ls1 <= 1
assert 0 <= ls2 <= 1
symmetric_ls = (ls1 + ls2) / 2
This raises an exception when the condition is untrue. You can catch the exception in the interface code that uses the library function and talks to the user through a text-based interface. Never use print inside the library function itself. Your comments are also fairly useless here. Don't comment every line of code. Don't tell us what you do (we see that), tell us why you're doing it. Use comments to explain the edge cases and non-obvious things. Move code into separate functions. A good function name is usually better than a comment. For example, the code that determines if two ranges overlap can be moved into a separate function:
def overlaps(x, y):
''' tests if two ranges overlap, bounds inclusive '''
return x[0] <= y[1] and y[0] <= x[1]
Whenever you call overlaps() from a different piece of code, everyone knows what's going on. You don't need comments anymore. The code became self-explanatory. Next, I have a further nitpick on error handling.
elif inter1[0] >= inter1[1] or inter2[0] >= inter2[1]:
print("Error ls: the first integer representing an interval should be lesser than the second.")
break | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
In my opinion, a range with the upper bound less than the lower bound is perfectly valid. You shouldn't throw an error if the user gives you a range like (5, 3). A mathematician would write such a set as
$$ \left\{ x \in \mathbb{Z},\quad 5 \le x \le 3\right\} = \emptyset $$
and conclude it's an empty set. The empty set never overlaps with anything, not even with itself, so we should silently ignore it. You can use a somewhat modified overlaps() function that handles the empty set correctly and always returns false.
def overlaps(x, y):
''' tests if two ranges overlap, bounds inclusive '''
return max(x[0], y[0]) <= min(x[1], y[1])
Finally, the most glaring problem with your code are the function names. Why would you name a function ss or ls? Give them proper names.
Here is an improved version of your business logic. It uses sorted lists and binary search, list comprehensions (which are incredibly concise and readable), useful function names with docstrings and only two (but useful) comments. This code also separates the algorithm from the interface (I didn't rewrite the interface here).
from bisect import bisect
def symmetric_similarity(list1, list2):
''' computes the symmetric similarity between two lists of ranges '''
unique1 = sorted_unique(list1)
unique2 = sorted_unique(list2)
valid1 = [x for x in list1 if overlaps_any(x, unique2)]
valid2 = [x for x in list2 if overlaps_any(x, unique1)]
return (len(valid1) + len(valid2)) / max(len(list1), len(list2)) / 2
def overlaps_any(x, ys):
''' tests if x overlaps with any y, ys must be sorted, non-empty, non-overlapping '''
i = bisect(ys, x)
# bisect returns the index where x would be inserted into ys, so we
# have to compare it against the ys before and after that point.
return i > 0 and overlaps(x, ys[i-1]) or i < len(ys) and overlaps(x, ys[i])
def overlaps(x, y):
''' tests if two ranges overlap, bounds inclusive '''
return max(x[0], y[0]) <= min(x[1], y[1]) | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python, performance, memory-optimization, cyclomatic-complexity
def sorted_unique(ranges):
''' sorts, removes empty ranges, then merges overlapping ranges '''
ranges = [x for x in sorted(ranges) if overlaps(x, x)]
unique = list(ranges[:1])
for x in ranges:
if overlaps(unique[-1], x):
# The lower bound is correct because we sorted, but we have to
# take the maximum of the upper bounds to merge the ranges.
unique[-1] = unique[-1][0], max(unique[-1][1], x[1])
else:
unique.append(x)
return unique
If you don't need the binary search, everything reduces to just a few lines of code. It's beautifully simple and reads almost like plain English, even without comments.
def symmetric_similarity(list1, list2):
''' computes the symmetric similarity between two lists of ranges '''
valid1 = [x for x in list1 if overlaps_any(x, list2)]
valid2 = [x for x in list2 if overlaps_any(x, list1)]
return (len(valid1) + len(valid2)) / max(len(list1), len(list2)) / 2
def overlaps_any(x, ys):
''' tests if x overlaps with any y '''
return any(overlaps(x, y) for y in ys)
def overlaps(x, y):
''' tests if two ranges overlap, bounds inclusive '''
return max(x[0], y[0]) <= min(x[1], y[1])
If you want to win the price for compactness, you can reduce it even further:
def symmetric_similarity(list1, list2):
''' computes the symmetric similarity between two lists of ranges '''
count1 = sum(any(overlaps(x, y) for y in list2) for x in list1)
count2 = sum(any(overlaps(x, y) for y in list1) for x in list2)
return (count1 + count2) / max(len(list1), len(list2)) / 2
def overlaps(x, y):
''' tests if two ranges overlap, bounds inclusive '''
return max(x[0], y[0]) <= min(x[1], y[1]) | {
"domain": "codereview.stackexchange",
"id": 44693,
"lm_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, memory-optimization, cyclomatic-complexity",
"url": null
} |
python-3.x, logging
Title: A Python decorator to trace function calls
Question: A while ago, I came up with a function that is similar to this one: Decorator to log function calls and return values, but with a different implementation.
What this function does: when applied to a function as a decorator, it captures the positional/named arguments and values passed to the function and outputs results to console (print), or to an active logger that you specify. The default behavior is to print.
The original aim was to debug code, especially unattended scripts, loops etc, and review the logs to figure out what values certain functions are actually receiving. This approach is to make it easy and convenient to monitor any function. Also, the logging feature provides a timestamp which is often relevant information when troubleshooting code.
One design goal is to have one single declaration so that the decorator can be used either with or without logger argument.
Possible improvements:
customize the output message by way of format string or similar, for example to facilitate analysis by a log parser (eg JSON)
there may be a better way than this implementation of partial that I am not sure about
The code:
debugtools.py:
from functools import wraps, partial
def show_args(func=None, logger=None):
if func is None:
return partial(show_args, logger=logger)
@wraps(func)
def wrapper(*args, **kwargs):
msg = f"{func.__name__}: (args={args}, kwargs={kwargs})"
if logger is None:
print(msg)
else:
logger(msg)
return func(*args, **kwargs)
return wrapper
main.py:
import logging
import sys
from debugtools import show_args
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
@show_args
def my_function_with_print(*args, **kwargs):
pass
@show_args(logger=logger.debug)
def my_function_with_logging(*args, **kwargs):
pass | {
"domain": "codereview.stackexchange",
"id": 44694,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, logging",
"url": null
} |
python-3.x, logging
@show_args(logger=logger.debug)
def my_function_with_logging(*args, **kwargs):
pass
my_function_with_print(1, 2, 3, 4, 5, f=6, comment="Using print")
my_function_with_logging(123, comment="Using logger")
Sample output:
my_function_with_print(args=(1, 2, 3, 4, 5), kwargs={'f': 6, 'comment': 'Using print'})
2023-05-03 22:08:58,520 - DEBUG - my_function_with_logging(args=(123,), kwargs={'comment': 'Using logger'})
Answer: I will note in passing that a
StringIO
buffer can be a useful logger.
The use case would be to freeze
the behavior of a unit test,
and verify that future invocations do the same thing.
The absence of (changing!) timestamps
is a boon to a unit test that wants
to do self.assertEqual.
If f() calls g() and so on,
I wonder if we could achieve nice composition.
Perhaps they would need some common default.
Maybe a with context handler would establish that?
if func is None:
return partial(show_args, logger=logger)
I found this slightly tricky upon first reading.
It accommodates the with / without parentheses notation,
and is worth a # comment.
This all looks good to me. Ship it!
I would be willing to delegate or accept maintenance tasks
on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44694,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, logging",
"url": null
} |
javascript, random
Title: JavaScript seedable Math.random
Question: I made an implementation of xoshiro256** in JavaScript, using BigInts. It's designed to mimic Math.random. Any feedback on the code quality?
function rol64(x, k) {
return (x << k) | (x >> (64n - k));
}
// state is an array of BigInts that are unsigned 64-bit integers
// you could use a normal array, or a BigUint64Array
function xoshiro256ss(state) {
return function() {
const result = rol64(state[1] * 5n, 7n) * 9n;
const t = state[1] << 17n;
state[2] ^= state[0];
state[3] ^= state[1];
state[1] ^= state[2];
state[0] ^= state[3];
state[2] ^= t;
state[3] = rol64(state[3], 45n);
return Number(BigInt.asUintN(53, result)) / (Number.MAX_SAFE_INTEGER + 1);
}
}
// example usage (browser)
const random = xoshiro256ss(
crypto.getRandomValues(new BigUint64Array(4))
);
alert(random());
Answer: Do not ship this code as-is. | {
"domain": "codereview.stackexchange",
"id": 44695,
"lm_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, random",
"url": null
} |
javascript, random
alert(random());
Answer: Do not ship this code as-is.
The identifier xoshiro256ss is apparently intended to denote
xoshiro256**,
but there is no comment or documentation explaining that.
You should definitely cite a reference,
even if only Wikipedia.
The comment "state is an array of [non-negative] BigInts"
is pretty clear, thank you for that.
The assumption is never verified.
It seems pretty easy for a caller to accidentally
mis-use the Public API and never notice the mistake,
for example by passing in ordinary integers or floats.
This submission contains no unit tests.
As such, it does not instill confidence that it
correctly computes what the spec asks of it.
Comparing the behavior of a C implementation
with this implementation, on diverse inputs,
would be of interest.
There are a few edge case inputs that would be
especially interesting.
The named spec is all about stirring 256 bits of entropy.
Yet we return a number between zero and one like Math.random,
rather than 64 high-entropy bits.
That detail really needs to be called out in the Public API
documentation or comments.
It looks like we cannot return 2^64 distinct values as promised by the spec.
This code does not detect the user error
of supplying an all-zeros state vector.
Repeatedly asking for random numbers
will yield decidedly non-random output
if state ever stores just 256 zeros.
My understanding is we should have the following invariant:
Elements of state[] shall at all times be non-negative integers that are at most 2^64 - 1.
Yet I see this:
const t = state[1] << 17n;
I think that in the spec we should see
seventeen low-order bits cleared to zero,
and we should see an integer less than 2^64.
But the BigInt t apparently retains
high order bits and can exceed 2^64 ?!?
s[2] ^= t; | {
"domain": "codereview.stackexchange",
"id": 44695,
"lm_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, random",
"url": null
} |
javascript, random
Later on the XOR will set high-order bits in this element,
and from there they will propagate to all other elements.
I am hard pressed to see how this JS code
implements the original algorithm.
Why are you even asking a human if this code
computes what it is supposed to?
Ask the machine.
You have other implementations available.
Ask if they mutate state in the same way.
Another invariant is that state shall always
store 256 bits.
But it appears to me that a loop which keeps
asking for new numbers will cause storage
to grow without bound.
Improve the automated testing and documentation before merging down to main. | {
"domain": "codereview.stackexchange",
"id": 44695,
"lm_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, random",
"url": null
} |
javascript, html, css, responsive-design
Title: Legend of Zelda: Breath of the Wild armor upgrade materials tracker
Question: There are plenty of these online already but none of them quite fit what I wanted. I've been meaning to learn some more front-end stuff so I decided to make one myself. I know some JavaScript but would consider myself an intermediate. I am definitely a beginner with HTML and CSS. The code is here on my GitHub and hosted here through GitHub Pages. The code is below, but I've provided the links in case it is easier. In the interest of keeping the code concise I have removed much of the armor data from the code here, but it still behaves the same.
You do not need to understand the game mechanics to understand this webpage. A brief summary is that you check the boxes on the table corresponding to the armor piece and level of that armor piece you are interested in tracking. The webpage presents a list of the totals of all the items you need. If you check level 1 of Champion's Tunic you will see that you need 3 Silent Princess. When you check level 2 (which by itself needs 2 Shard of Farosh's Horn and 3 Silent Princess) you will see that you need a total of 2 Shard of Farosh's Horn and 6 Silent Princess.
I have used "responsive design" so please also be sure to try this in a full screen and adjust the width of the browser if you want to see that functionality. I'm not exclusively looking for feedback on that aspect or anything, but it was a tough part for me being new to CSS.
<!DOCTYPE html>
<head>
<style>
td {
text-align: right;
}
.flex-container {
display: flex;
flex-flow: row wrap;
justify-content: center;
}
.flex-item {
--margin: 5px;
display: flex;
flex-flow: column nowrap;
justify-content: flex-start;
align-items: center;
flex-grow: 1;
max-width: calc(50% - 2 * var(--margin));
flex-basis: 50%;
margin: var(--margin);
}
.title {
text-align: center;
} | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
.title {
text-align: center;
}
@media (max-width: 768px) {
.flex-container {
flex-flow: column nowrap;
}
.flex-item {
max-width: 100%;
}
}
</style>
<script>
"use strict";
function init() {
// Populate the armor table
let tableBody = document.getElementById("armors");
Object.entries(armorData).forEach(([armorPiece, levels]) => {
let newRow = tableBody.insertRow();
let allCell = newRow.insertCell();
allCell.innerHTML = makeCheckAll(armorPiece);
let nameCell = newRow.insertCell();
nameCell.innerHTML = armorPiece;
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
let cell = newRow.insertCell();
cell.innerHTML = makeCheck(armorPiece, levelIndex);
}
})
update();
}
function update() {
// Populate the materials table
let tableBody = document.getElementById("totals");
// First, clear old data
while (tableBody.rows.length > 0) {
tableBody.deleteRow(0);
}
let matsNeeded = new Map(); | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
let matsNeeded = new Map();
// Find which are needed
let wholeTableChecked = true;
let wholeColumnChecked = [true, true, true, true];
Object.entries(armorData).forEach(([armorPiece, levels]) => {
let wholeRowChecked = true;
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
if (isChecked(armorPiece, levelIndex)) {
let level = levels[levelIndex];
Object.entries(level).forEach(([material, quantity]) => {
if (matsNeeded.has(material)) {
let currentNeededQuantity = matsNeeded.get(material);
matsNeeded.set(material, currentNeededQuantity + quantity);
} else {
matsNeeded.set(material, quantity);
}
})
} else {
wholeRowChecked = false;
wholeTableChecked = false;
wholeColumnChecked[levelIndex] = false;
}
}
setChecked(armorPiece, "", wholeRowChecked); // TODO
})
setChecked("all", "", wholeTableChecked); // TODO
for (let columnIndex = 0; columnIndex < wholeColumnChecked.length; columnIndex++) {
setChecked("", columnIndex, wholeColumnChecked[columnIndex]); // TODO
}
// Sort by material
matsNeeded = new Map([...matsNeeded].sort((a, b) => String(a[0]).localeCompare(b[0])))
// Put them in the table
matsNeeded.forEach((quantity, material) => {
let newRow = tableBody.insertRow();
newRow.insertCell().innerHTML = material;
newRow.insertCell().innerHTML = quantity;
})
}
function updateWholeRow(id) {
Object.entries(armorData).forEach(([armorPiece, levels]) => {
if (armorPiece === id) {
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
setChecked(armorPiece, levelIndex, isChecked(armorPiece, "")) // TODO
}
}
})
update();
} | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
function updateWholeColumn(levelIndex) {
Object.entries(armorData).forEach(([armorPiece, levels]) => {
setChecked(armorPiece, levelIndex, isChecked("", levelIndex)) // TODO
})
update();
}
function updateWholeTable() {
Object.entries(armorData).forEach(([armorPiece, levels]) => {
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
setChecked(armorPiece, levelIndex, isChecked("all", "")) // TODO
}
})
update();
}
function makeCheck(name, level) {
// <input type="checkbox" id="Armor NameX" onchange="update()">
return "<input type=\"checkbox\" id=\"" + name + level + "\" onchange=\"update()\">";
}
function makeCheckAll(name) {
// <input type="checkbox" id="Armor NameX" onchange="update()">
return "<input type=\"checkbox\" id=\"" + name + "\" onchange=\"updateWholeRow(this.id)\">";
}
function isChecked(name, level) {
return document.getElementById(name + level).checked;
}
function setChecked(name, level, state) {
document.getElementById(name + level).checked = state;
} | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
const armorData = {
"Champion's Tunic": [
{
"Silent Princess": 3,
},
{
"Silent Princess": 3,
"Shard of Farosh's Horn": 2,
},
{
"Silent Princess": 3,
"Shard of Naydra's Horn": 2,
},
{
"Silent Princess": 10,
"Shard of Dinraal's Horn": 2,
},
],
"Sand Boots": [
{
"Molduga Fin": 5,
"Hightail Lizard": 10,
},
{
"Molduga Fin": 10,
"Swift Carrot": 10,
},
{
"Molduga Guts": 2,
"Rushroom": 15,
},
{
"Molduga Guts": 4,
"Swift Violet": 15,
},
],
"Snow Boots": [
{
"Octorok Tentacle": 5,
"Hightail Lizard": 10,
},
{
"Octo Balloon": 5,
"Swift Carrot": 10,
},
{
"Octorok Eyeball": 5,
"Rushroom": 15,
},
{
"Naydra's Scale": 2,
"Swift Violet": 15,
},
],
"Amber Earrings": [
{
"Amber": 5,
"Flint": 3,
},
{
"Amber": 10,
"Flint": 3,
},
{
"Amber": 20,
"Flint": 3,
},
{
"Amber": 30,
"Flint": 3,
},
],
"Diamond Circlet": [
{
"Diamond": 2,
"Flint": 3,
},
{
"Diamond": 4,
"Flint": 3,
},
{
"Diamond": 6,
"Star Fragment": 1,
},
{
"Diamond": 10,
"Star Fragment": 1,
},
],
}
</script>
</head> | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
<body onload="init()">
<h1 class="title">Armor upgrade materials tracker</h1>
<p>
Each checkbox of the first table represents each upgrade (represented in
game by stars). The base version of the armor is not represented because
this tool is only for tracking upgrade materials needed. That means things
like the 5 Opals you need for the Opal Earrings are not tracked here.
</p>
<div class="flex-container">
<div class="flex-item armor">
<h2>Armors</h2>
<p>
Check the armors you <i>want</i> but do not <i>have</i>. If you already
have an upgrade or just do not care about tracking the materials for it
right now then <i>leave the box unchecked</i>.
</p>
<p>
Checkboxes on the "all" side will check/uncheck the entire row. The one
on the first row will do this for the entire table.
</p>
<table>
<thead>
<tr>
<th>All? <input type="checkbox" id="all" onchange="updateWholeTable()"></th>
<th>Name</th>
<th>1★ <input type="checkbox" id="0" onchange="updateWholeColumn(this.id)"></th>
<th>2★ <input type="checkbox" id="1" onchange="updateWholeColumn(this.id)"></th>
<th>3★ <input type="checkbox" id="2" onchange="updateWholeColumn(this.id)"></th>
<th>4★ <input type="checkbox" id="3" onchange="updateWholeColumn(this.id)"></th>
</tr>
</thead>
<tbody id="armors"></tbody>
</table>
</div>
<div class="flex-item">
<h2>Materials needed</h2>
<p>
These are the materials you need to get for the <i>checked</i> upgrades
above.
</p>
<table>
<thead>
<tr>
<th>Material</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="totals"></tbody>
</table>
</div>
</div>
</body>
<footer>
<hr>
<a href="https://github.com/JacksonBailey/armor">GitHub repository</a>
</footer> | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
Answer: 1 HTML
Your HTML markup is invalid. The W3C Validator returns 3 flags which include 2 red flags.
You miss the <html> opening and closing tag which needs to wrap the head and body element
You miss the lang attribute
You miss the <title> tag within your head element
Your <footer> tag is outside of the body and as such an invalid placement
Semantics and valid placement is important for accessibility. That again is not only important for disabled persons but also for SEO ratings. For the same reasons, the lang attribute and the title tag are needed.
The body element is not the main element of your website but the body of the document. It has to contain every visual placement. The body itself can be divided into <header>, <main>, and <footer>. <body> is not to be mistaken as the <main> element that comes between header and footer.
1.1 Conventions | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
I see no usage of conventions and no comments in your entire document. Overall your code is harder than necessary to read
The naming of your IDs and classes is mostly not self-explaining. They are not given with the entire context in mind. The class title should be an id while I see no reason in your code why it needs to be given in the first place. That element is your only h1 element and at least your first h1 element. As such could have been addressed directly without class or id. The class armor is a class that is used on a section for armor. As such it should be an id which would make the id armors redundant and not necessary. Especially the usage of ids with the name 0, 1, 2, 3, or 4 is not an useful name that would tell other developers what the ids are for. More useful is a name such as all-1-stars or all-2-stars. Names in general do not have to be short but self-explaining
The code is well-indented but misses only gaps or line breaks to separate logical groups of elements. It is one of the main reasons that your code is hard to read
Your CSS and JS and include directly in your document which not makes usage of caching performance as well as making the code harder to read. This also prevents the reuse of your code
You are using an onload attribute to start your script. This makes maintenance harder and is not the modern way to solve the issue. The 2 modern solutions are either to use the defer attribute on the script tag or to use window.addEventListener('DOMContentLoaded', function). While the third "outdated" method is to put the script at the end of your body. Same rule applies to the onchange attribute. Instead of usign the onclick attribute over and over again, you could simply use an event listener and an event delegation
1.2 Accessibility & Semantics
With exception of the footer which has an invalid placement, you're not using the semantic tags. Overall, your code is inaccessible. | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
You are basically dividing the main part of you content in 2 sections. As such a <section> should be used
Your inputs missing a label and as such a screen reader would recognize a checkbox but a blind person would never know what those checkboxes are for
The flex-container should be a <main> element while the title and description would be appropriate as a <header> element
1.3 Head Element
As already mentioned above, you should not write your entire CSS and JS code into your head element but connect the files there. Respectively for CSS using the <link>tag.
You miss the <charset> tag which should always be used to set the correct character set that you are using
You miss a <title> tag which will title your website and also be used when saving the website as favorites
While not necessary, you should consider a favicon
1.4 Body Element
There is nothing more to add which hasn't been coverd yet.
2 CSS
Your CSS is super basic and does not add any real design choices. Your CSS is mainly used to align items. Which it self is a good start but would not thrill any user. While it makes the CSS in general short, you miss heavily on the UX/UI side that you completely ignored. It will probably not make any users sticking with your tool nor to give it any real attention.
2.1 Accessibility
You have not used any colors. While this might seem unappealing in terms of UI it will not influence accessibility as you have not to take care of contrast.
Your tool is has limited accessibility for users with touch or eye-tracking controls. On touchscreens the inputs need to be larger to allow a easy and comfortable (un)checking with your fingers.
Your different section are only split with a margin. Carefully placed board woulds increase a UI and UX as well as readability.
Especially in larger tables you should color the rows so that they visually be differentiated | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
2.2 Responsiveness
While you believe that your website is responsive, you're actually far from it. Responsiveness does not necessarily mean to have different layouts at different screen widths. Responsive Web Design is a concept that its basic idea is an UX concept. It aims to provide the best experience in form of readability, accessibility and controlling or usability of your website / web application. For that, it has to adjust to the screen size. This however means, that it is not limited to changing your layout on different widths.
Your design completely ignores usability on mobile devices
The smallest screen where your layout will be displayed correctly is at 419px while mobile devices can start at 320px
You do not take DPR (Device Pixel Ratio) into account. While testing your web application on a real mobile device, you will properly recognize undesired behavior.
A good responsive design starts with mobile first, then tablets, then desktops
2.3 Structure
I see no structure in your CSS. flex-container and flex-items are grouped correctly but you should order your CSS in some way, Either specificty weight, appearance or alphabetically
While it is acceptable to declare CSS variables within an element in your case, you should in general consider to declare them at the top within the :root selector
You are using flex-flow while in both instances you're declaring a default value which is redundant but not needed.
flex-wrap is not needed in your case as you declare a direction and only have 2 elements. You either could solve the entire design with flex-wrap itself or by just declaring the flex-direction
You setting a margin to the elements and then calculating the width depending on the margin. The easy and correct solution would be the usage of the gap property on the parent. You also could use CSS Grid which saves you the calculation | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
3 JS
While your JS is good for a beginner it lacks readability, formatting and modern approaches. Your techniques is a mixture of modern and outdated approaches. The usage of JS modules would have been helpful here. While I understand why you used an array of objects and not a database, it is something you should have included as a module and split from the main JS.
3.1 Conventions
Conventions make code easier to read and as such also easier to maintain.
List global constants at the very top and use capital names to differentiate them from variables
Make parameters visual by adding underscores to it such as --param. This helps to differentiate them from other variables or constants
Your variable names are self-explaining. No issue here
Don't spare with comments. While code should be self-explaining, carefully placed comments would greatly improve readability. Since you're missing comments, others will have a hard time to understand how your code would work
Don't use innerHTML as they pose a security risk (XSS) and are slow (requires the reparsing of the DOM)
3.2 Logic & Coding Style
There is a lot to improve. While I not want to point out every single "issue" I want to just push you into a direction on what you should focus on.
let wholeColumnChecked = [true, true, true, true]; is hard to understand. Using an array is not needed here at all. It also is not scalable at all. Make use of querySelectorAll('all inputs:checked') === querySelectorAll('all inputs').
Learn to use backticks:
let name = "Armor";
let level = 4;
console.log(`<input type="checkbox" id="${name}${level}">`);
Learn to use querySelector and querySelectorAll
Learn to use an event delegation
Learn to use data attributes
4 Rating
Especially since you are new you should read into the Dunning-Kruger-Effect and Mt. Stupid and Valley of Death.
With your statement: | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
javascript, html, css, responsive-design
I have used "responsive design" so please also be sure to try this in a full screen and adjust the width of the browser if you want to see that functionality. I'm not exclusively looking for feedback on that aspect or anything, but it was a tough part for me being new to CSS
you where actually quite wrong. Responsive Web Design and UX and UI should be your next big topic to learn. You underestimate the influence of the frontend part of those topics.
While you show a really good start, you need still to learn some of the basics especially with correctness and semantics in mind. | {
"domain": "codereview.stackexchange",
"id": 44696,
"lm_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, html, css, responsive-design",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
Title: Code for asynchronous data stream processing with multistage pipelines
Question: I am trying to write some code for processing streams of asynchronous data from multiple sources (Producer Nodes), process them using a multistage pipeline of Processors Nodes and then forward them to multiple Consumers Nodes. So the way I have thought of going about it is the follows: Each Node has a run function which does stuff. A Consumer node has an input queue, Producer node has an output queue and the Processor node has both. I then Construct a Pipeline by 'connecting' input and output queues (by pointing input queue of next node to output queue of previous) of nodes and run all nodes asynchronously. Each shared queue between nodes is synchronized by a mutex and condition_variable variable which are also 'connected'. Here is the code sample for int streams:
enum class PacketState{
START,
VALID,
CORRUPT,
END,
};
typedef struct packet{
int data;
PacketState state;
explicit packet(int x):data{x},state{PacketState::VALID}{};
packet(int d, PacketState s):data{d},state{s}{};
packet():data{0},state{PacketState::VALID}{};
} PacketType;
using OutputType = PacketType;
using InputType = OutputType;
class Node{
protected:
bool stayAlive = true;
public:
virtual void run() = 0;
}; | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
class NodesWithOutput: public Node{
protected:
//declare output pointers
std::shared_ptr<Queue<OutputType>> output;
std::shared_ptr<std::condition_variable> cvout;
std::shared_ptr<std::mutex> m_out;
public:
NodesWithOutput(){
//setup output apparatus.....
output = std::make_shared< Queue<OutputType> >();
cvout = std::make_shared<std::condition_variable>();
m_out = std::make_shared<std::mutex>();
}
auto getOutputQueue(){return output;}
auto getOutputCondition(){return cvout;}
auto getOutputMutex(){return m_out;};
};
class NodesWithInput: public Node{
protected:
//declare input pointers
std::shared_ptr<Queue<InputType>> input;
std::shared_ptr<std::condition_variable> cvin;
std::shared_ptr<std::mutex> m_in;
};
//template<typename OutputType>
class Producer: public NodesWithOutput{
public:
Producer() = default;
void run() override {
int i = 6;
while (stayAlive) {
//generate stream of ints..
OutputType dataPacket{--i};
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// push to output queue
{
std::lock_guard<std::mutex> lock(*m_out);
output->push(dataPacket);
cvout->notify_all();
}
if(i <= 0) stayAlive = false;
}
OutputType dataPacket{-1,PacketState::END};
// push to output queue
{
std::lock_guard<std::mutex> lock(*m_out);
output->push(dataPacket);
}
// This is the right place to notify right?..
// **not** inside the guarded block
cvout->notify_all();
}
}; | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
//template<typename InputType, typename OutputType>
// HOW DO I DO THIS PROPERLY?
class Processor:public NodesWithOutput, public NodesWithInput {
private:
int scale;
protected:
//HOW DO I FIX THIS?
//?? this doesn't seem right!
bool stayAlive = NodesWithOutput::stayAlive;
public:
Processor():scale{1}{}
void setScale(int s){ scale = s;}
void setInput(Producer& other){
input = other.getOutputQueue();
m_in = other.getOutputMutex();
cvin = other.getOutputCondition();
}
void run() override {
while(stayAlive) {
//wait for input
{
std::unique_lock<std::mutex> ulock(*m_in);
//Should I wait for notify from cvout of previous node?
//I mean this cvin will finally point to previous cvout!
cvin->wait(ulock, [this](){return !input->empty();});
}
//process input
{
std::unique_ptr<PacketType> ip;
//read from input queue
{
std::lock_guard<std::mutex> lock(*m_in);
ip = input->pop();
}
//process and
OutputType o;
o.state = ip->state;
if(ip->state != PacketState::END) {
o.data = (*ip).data * scale;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}else{
stayAlive = false;
}
//write to output queue
{
std::lock_guard<std::mutex> lock(*m_out);
output->push(o);
}
cvout->notify_all();
}
}
}
}; | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
//template<typename InputType>
class Consumer: public NodesWithInput {
public:
Consumer() = default;
void setInput(Processor& other){
input = other.getOutputQueue();
m_in = other.getOutputMutex();
cvin = other.getOutputCondition();
}
void run() override {
while(stayAlive) {
//wait for data
{
std::unique_lock<std::mutex> ulock(*m_in);
cvin->wait(ulock, [this](){ return !input->empty();});
}
//Consume data data
std::unique_ptr<InputType> ip;
{
std::lock_guard<std::mutex> lock(*m_in);
ip = input->pop();
}
if(ip->state == PacketState::END) break;
//process data
std::cout << "Consumed: " << ip->data << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
};
class Pipeline {
private:
std::vector< Node* > nodes;
public:
Pipeline(){
nodes = std::vector< Node* >();
}
~Pipeline() = default;
void buildAndRun() {
// Node 1
Producer randInt;
//nodes.push_back(&randInt);
Processor multiplier;
//HOW DO IF FIX THIS?
//'Node' is an ambiguous base of 'Processor'
//nodes.push_back(&multiplier);
multiplier.setInput(randInt);
multiplier.setScale(2);
Consumer printer;
//nodes.push_back(&printer);
printer.setInput(multiplier); | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
//FIX move to separate function which operates on nodes vector....
auto run = [&](){
// Put these in a loop if nodes vector works out...
auto t1 = std::async(std::launch::async, &Producer::run, randInt);
auto t2 = std::async(std::launch::async, &Processor::run, multiplier);
auto t3 = std::async(std::launch::async, &Consumer::run, printer);
t1.get();
t2.get();
t3.get();
};
run();
}
};
Not this is the first time I am writing async code and I have a questions! Some are in code comments but here are some major ones:
Is the general architecture of the code OK or should I change it? Do you see any obvious (or non-obvious) issues I may will run into using this pattern?
The Queue I am using is a thread safe queue Is that an overkill? Should I just use simple std::queue for holding data packets?
This may be more of a stackoverflow question, but how do I properly inherit from two different classes (NodesWithInput and Nodeswithoutput) so that I can have a vector of Nodes in Pipeline? (I shout 'how to fix...' in code comments for stuff that I haven't figure out yet.)
Here is the code for the Queue class along with test main function for runnable sample.
class Queue {
private:
std::queue< std::unique_ptr<T> > _queue;
std::mutex _mutex;
//?? change this to a shared ptr
// add a shared ptr to condition and point
// node sync variables to connecting queue sync variables..
public:
Queue() = default;
Queue(const Queue<T> &) = delete;
Queue& operator=(const Queue<T>& ) =delete;
Queue(Queue<T> && other) noexcept {
std::lock_guard<std::mutex> lock(_mutex);
_queue = std::move(other._queue);
}
virtual ~Queue(){} | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
virtual ~Queue(){}
size_t size() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
bool empty() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.empty();
}
std::unique_ptr<T> pop() {
std::lock_guard<std::mutex> lock(_mutex);
//check empty only when locked
if(_queue.empty()){
return nullptr;
}
auto front = std::move(_queue.front());
_queue.pop();
return front;
}
void push(const T& packet){
std::lock_guard<std::mutex> lock(_mutex);
_queue.push(std::make_unique<T>(packet));
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
Pipeline p;
p.buildAndRun();
std::cout << "Goodbye, World!" << std::endl;
return 0;
}
Is there a way to simplify the Code for Nodes by somehow adding condition_variable to the Queue and using that to synchronize and signal all output nodes to stop wait? (I have some ideas for this in the comments of the Queue class.. but need to be sure about race conditions and blocking stuff...)
Finally, a bit more open ended for the future.. I have to make the ``Queue` bounded at some point. What would be the most optimal way to handle this? The processing times of different nodes could be different and large queues could form at 'some' places but not others. Is it possible to have a global bound on total number of queued items rather than local bound on each queue?
Answer: General | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
Answer: General
typedef is not needed in C++ for structs
In C++, one tends to have public members first and then private members. similarly constructors and functions generally come before member variables.
All classes with virtual functions must have a virtual destructor.
It's considered bad practice to have protected members. It is also considered bad practice to have member variables in base classes that are pure virtual
Avoid having _ as a prefix to before any names. Its against C++ guidelines.
Architecture
Your hierarchies are too deep. There is very little to be gained from having a Node class. Also, it is the cause of the ambigous base error in Processor. Look up diamond dependency issue.
The NodesWithOutput and NodesWithInput is leaking variables. Everytime, the getters are called a new shared_ptr is created. Looking at the usage you could have easily made it into a struct.
Further there is no point having NodesWithOutput and NodesWithInput, why not just create a class called Pipe and let the Nodes have a shared_ptr to it?
Do you intend to write a new Producer, Consumer and Processor class everytime you have to have a new way to produce, process or consume something? This is too much broilerplate code to achieve something mundane.
Since the Queues are shared it which means that if you have multiple consumers then only one of the queue will get the packet.
Final word
There are many other issue. But the main issue is the architecture. It is needlessly complicated. I would start with something like this.
Disclaimer: The code below is not not tested. It only serves as a rough sketch of how I would rearchitect the code
#include <memory>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional> | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
template<typename T>
class Queue
{
public:
T pop()
{
auto lock = std::unique_lock(mMutex);
mConditionVariable.wait(lock, [this]{return !mQueue.empty();});
auto element = mQueue.front();
mQueue.pop();
return element;
}
void push(T&& t)
{
auto lock = std::unique_lock(mMutex);
mQueue.push(t);
}
bool empty()
{
auto lock = std::unique_lock(mMutex);
return true;
}
private:
std::condition_variable mConditionVariable;
std::queue<T> mQueue;
std::mutex mMutex;
};
template<typename T>
class Producer
{
public:
void run()
{
while(1)
{
mOutputQueue->push(mProduce());
}
}
void connect(std::shared_ptr<Queue<T>> q)
{
mOutputQueue = q;
}
private:
std::function<T()> mProduce;
std::shared_ptr<Queue<T>> mOutputQueue;
};
template<typename T>
class Processor
{
public:
void run()
{
while(1)
{
mOutputQueue->push(
mProcess(
mInputQueue.pop()
)
);
}
}
void connectInput(std::shared_ptr<Queue<T>> q)
{
mInputQueue = q;
}
void connectOutput(std::shared_ptr<Queue<T>> q)
{
mOutputQueue = q;
}
private:
std::function<void(T)> mProcess;
std::shared_ptr<Queue<T>> mInputQueue;
std::shared_ptr<Queue<T>> mOutputQueue;
};
template<typename T>
class Consumer
{
public:
void run()
{
while(1)
{
auto value = mInputQueue->pop();
mConsume(std::move(value));
}
}
void connectInput(std::shared_ptr<Queue<T>> q)
{
mInputQueue = q;
}
private:
std::function<void(T&)> mConsume;
std::shared_ptr<Queue<T>> mInputQueue;
}; | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
c++, multithreading, asynchronous, producer-consumer, multiprocessing
private:
std::function<void(T&)> mConsume;
std::shared_ptr<Queue<T>> mInputQueue;
};
If you can refactor the code to look something like this and repost it. I can review it and make it robust. I suspect there are race conditions which we are unaware of but they will start to be apparent only after the code is readable. | {
"domain": "codereview.stackexchange",
"id": 44697,
"lm_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, asynchronous, producer-consumer, multiprocessing",
"url": null
} |
python, beginner, programming-challenge
Title: Determine the chance a streak of 6 HEADs or 6 TAILS appear in 100 flips, repeated 10000 times
Question: Here's the problem from the book Automate the boring stuff:
write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails.
The #comments are a hint by the author. This program I created ran just fine but the chance of streak is surprisingly high to me: ~152% - 153%. So I'm wondering if I got the logic right? Any help will be greatly appreciated.
import random
def flip():
random_num = random.randint(0, 1)
if random_num == 1:
return "H"
else:
return 'T'
numberOfStreaks = 0 #author wrote this line
for experimentNumber in range(10000): #author wrote this line
# Code that creates a list of 100 'heads' or 'tails' values.
head_tail_str = ""
side = flip()
head_tail_str += side
for _ in range(99):
prev_side = side
side = flip()
if side != prev_side:
head_tail_str += f",{side}"
else:
head_tail_str += side
# Code that checks if there is a streak of 6 heads or tails in a row.
head_tail_lst = head_tail_str.split(',')
for item in head_tail_lst:
if len(item) >= 6:
numberOfStreaks += (int(len(item)) // 6)
print('Chance of streak: %s%%' % (numberOfStreaks / 100)) #author wrote this line
P.S. I've been learning Python for 1 month
Answer: Logical
numberOfStreaks += (int(len(item)) // 6)
Does a streak of 12 H mean 2 streaks?
how often a streak of six heads or a streak of six tails comes up
Sounds like just numberOfStreaks to me, not sure why it's being suggested to compare to 100 in order to produce a percentage:
print('Chance of streak: %s%%' % (numberOfStreaks / 100)) #author wrote this line
for experimentNumber in range(10000): #author wrote this line | {
"domain": "codereview.stackexchange",
"id": 44698,
"lm_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, programming-challenge",
"url": null
} |
python, beginner, programming-challenge
for experimentNumber in range(10000): #author wrote this line
The above suggests the code is designed to run multiple trials. For this to happen, it's important that each trial is independent, meaning state (values/data) does not bleed from one trial to another.
You'll see that's not happening if you run the script with this line instead:
for experimentNumber in range(1):
Structural
Would suggest using list instead of str to collect the flips, which more naturally expresses "a bunch of items".
It also helps to organize code by splitting up the two things you're doing: flipping 100 times and grouping together streaks.
# flip 100 times
flips = []
for _ in range(100):
flips.append(flip())
# group together streaks:
first_flip, *rest_flips = flips
streaks = [[first_flip]]
for side in rest_flips:
prev_streak = streaks[-1] # [-1] returns the last item
prev_side = prev_streak[-1]
if side == prev_side:
streak = prev_streak
else:
streak = [] # new streak
streaks.append(streak)
streak.append(side)
For "nicer" code
numberOfStreaks = 0 #author wrote this line
The convention in Python is underscore naming for variables, i.e. number_of_streaks.
In Python, 0 is "fasley", which means flip() can be:
if random.randint(0, 1):
return "H" # when 1, "truthy"
else:
return "T" # when 0, "falsey"
When grouping, can do all the flips together rather than the first_flip and rest_flips separately by handling the first iteration edge case:
streaks = []
for side in flips:
prev_side = streaks and streaks[-1][-1] # `[]` is also falsey
if side == prev_side:
streak = streaks[-1]
else:
streak = []
streaks.append(streak)
streak.append(side)
Leveling up
One of the reasons to split up the flipping from the grouping is that grouping is so generally useful, it's already available in the standard library as itertools.groupby:
import itertools as it | {
"domain": "codereview.stackexchange",
"id": 44698,
"lm_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, programming-challenge",
"url": null
} |
python, beginner, programming-challenge
flips = [flip() for _ in range(100)]
streaks = [list(grp) for _, grp in it.groupby(flips)] | {
"domain": "codereview.stackexchange",
"id": 44698,
"lm_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, programming-challenge",
"url": null
} |
c++, integer, binary
Title: Any amount bits integer
Question: This class is meant to work exactly as an unsigned integer should work, but it limits the value based on a set amount of bits.
/**
* @brief Any amount of bits integer.
* @tparam bits amount of bits
*
* @note stores with size of uint64_t
*/
template <uint8_t bits>
requires((bits >= 1) && (bits <= 64))
class uintx_t {
protected:
uint64_t Val;
constexpr static inline uint64_t formatBits(
uint64_t val,
uint16_t bits2
) {return val & (UINT64_MAX >> (64-bits2));}
public:
uintx_t(int64_t val) {
Val = formatBits(val, bits);
}
template <uint8_t otherBits>
uintx_t(const uintx_t<otherBits>& val) {
Val = formatBits(val.getVal(), bits);
}
constexpr inline uint64_t getVal() const {return Val;} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
constexpr inline uint64_t getVal() const {return Val;}
std::string toBin() const {
std::string bin = std::bitset<bits>(Val).to_string();
return bin;
}
inline void operator= (int64_t val) {
Val = formatBits(val, bits);
}
template <uint8_t otherBits>
inline void operator= (uintx_t<otherBits> val) {
Val = formatBits(val.getVal(), bits);
}
inline bool operator== (int64_t val) {
return (Val == val);
}
template <uint8_t otherBits>
inline bool operator==(const uintx_t<otherBits>& val) {
return (Val == val.getVal());
}
inline bool operator!= (int64_t val) {
return (Val != val);
}
template <uint8_t otherBits>
inline bool operator!=(const uintx_t<otherBits>& val) {
return (Val != val.getVal());
}
inline bool operator> (int64_t val) {
return (Val > val);
}
template <uint8_t otherBits>
inline bool operator> (const uintx_t<otherBits>& val) {
return (Val > val.getVal());
}
inline bool operator< (int64_t val) {
return (Val < val);
}
template <uint8_t otherBits>
inline bool operator< (const uintx_t<otherBits>& val) {
return (Val < val.getVal());
}
inline bool operator>= (int64_t val) {
return (Val >= val);
}
template <uint8_t otherBits>
inline bool operator>= (const uintx_t<otherBits>& val) {
return (Val >= val.getVal());
}
inline bool operator<= (int64_t val) {
return (Val <= val);
}
template <uint8_t otherBits>
inline bool operator<= (const uintx_t<otherBits>& val) {
return (Val <= val.getVal());
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
inline uintx_t operator+ (int64_t val) {
return uintx_t(formatBits(Val + val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator+ (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val + val.getVal(), bits));
}
inline uintx_t operator- (int64_t val) {
return uintx_t(formatBits(Val - val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator- (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val - val.getVal(), bits));
}
inline uintx_t operator* (int64_t val) {
return uintx_t(formatBits(Val * val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator* (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val * val.getVal(), bits));
}
inline uintx_t operator/ (int64_t val) {
return uintx_t(formatBits(Val / val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator/ (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val / val.getVal(), bits));
}
inline uintx_t operator% (int64_t val) {
return uintx_t(formatBits(Val % val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator% (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val % val.getVal(), bits));
}
inline uintx_t operator| (int64_t val) {
return uintx_t(formatBits(Val | val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator| (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val | val.getVal(), bits));
}
inline uintx_t operator& (int64_t val) {
return uintx_t(formatBits(Val & val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator& (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val & val.getVal(), bits));
}
inline uintx_t operator^ (int64_t val) {
return uintx_t(formatBits(Val ^ val, bits));
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
return uintx_t(formatBits(Val ^ val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator^ (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val ^ val.getVal(), bits));
}
inline uintx_t operator<< (int64_t val) {
return uintx_t(formatBits(Val << val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator<< (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val << val.getVal(), bits));
}
inline uintx_t operator>> (int64_t val) {
return uintx_t(formatBits(Val >> val, bits));
}
template <uint8_t otherBits>
inline uintx_t operator>> (const uintx_t<otherBits>& val) {
return uintx_t(formatBits(Val >> val.getVal(), bits));
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
inline uintx_t& operator++ () {
Val = formatBits(++Val, bits);
return *this;
}
inline uintx_t& operator-- () {
Val = formatBits(--Val, bits);
return *this;
}
inline uintx_t operator++ (int) {
Val = formatBits(++Val, bits);
return *this;
}
inline uintx_t operator-- (int) {
Val = formatBits(--Val, bits);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
inline uintx_t operator+= (int64_t val) {
Val = formatBits(Val+val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator+= (const uintx_t<otherBits>& val) {
Val = formatBits(Val+val.getVal(), bits);
return *this;
}
inline uintx_t operator-= (int64_t val) {
Val = formatBits(Val-val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator-= (const uintx_t<otherBits>& val) {
Val = formatBits(Val-val.getVal(), bits);
return *this;
}
inline uintx_t operator*= (int64_t val) {
Val = formatBits(Val*val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator*= (const uintx_t<otherBits>& val) {
Val = formatBits(Val*val.getVal(), bits);
return *this;
}
inline uintx_t operator/= (int64_t val) {
Val = formatBits(Val/val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator/= (const uintx_t<otherBits>& val) {
Val = formatBits(Val/val.getVal(), bits);
return *this;
}
inline uintx_t operator%= (int64_t val) {
Val = formatBits(Val%val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator%= (const uintx_t<otherBits>& val) {
Val = formatBits(Val%val.getVal(), bits);
return *this;
}
inline uintx_t operator|= (int64_t val) {
Val = formatBits(Val|val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator|= (const uintx_t<otherBits>& val) {
Val = formatBits(Val|val.getVal(), bits);
return *this;
}
inline uintx_t operator&= (int64_t val) {
Val = formatBits(Val&val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator&= (const uintx_t<otherBits>& val) { | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
template <uint8_t otherBits>
inline uintx_t operator&= (const uintx_t<otherBits>& val) {
Val = formatBits(Val&val.getVal(), bits);
return *this;
}
inline uintx_t operator^= (int64_t val) {
Val = formatBits(Val^val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator^= (const uintx_t<otherBits>& val) {
Val = formatBits(Val^val.getVal(), bits);
return *this;
}
inline uintx_t operator<<= (int64_t val) {
Val = formatBits(Val<<val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator<<= (const uintx_t<otherBits>& val) {
Val = formatBits(Val<<val.getVal(), bits);
return *this;
}
inline uintx_t operator>>= (int64_t val) {
Val = formatBits(Val>>val, bits);
return *this;
}
template <uint8_t otherBits>
inline uintx_t operator>>= (const uintx_t<otherBits>& val) {
Val = formatBits(Val>>val.getVal(), bits);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
friend std::ostream& operator<< (
std::ostream& os,
uintx_t& UX
) {
os << std::to_string(UX.Val);
return os;
}
template <typename T>
explicit operator T() const {
return (T)Val;
}
};
Example:
uintx_t<4> nibble = 3;
uintx_t<8> other = 20;
std::cout << nibble << '\n';
std::cout << nibble.toBin() << '\n';
std::cout << nibble + 4 << '\n';
std::cout << nibble + other << '\n';
Output:
3
0011
7
7 | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
Answer: You forgot std::
Types like uint8_t from <cstdint> are defined in the std namespace. Often these types are pulled into the global namespace as well because C headers are included behind the scenes, but you cannot rely on that. You should therefore write std::uint8_t in full.
Mixing signed and unsigned integers
I see both std::uint64_t and std::int64_t being used. C++ will silently convert these values into each other (unless you enable compiler warnings like -Wsign-conversion), but the result might not be what you expect. Since C++20, signed integers are guaranteed to be represented using two's complement, and that causes most of the implicit conversions in your code to be safe, it's better not to rely on that, and use std::uint64_t everywhere.
Naming things
It's weird to see both Val and val in your code. While C++ is case-sensitive, virtually all code styles use identifiers starting with lower-case for variables and functions. If you want to distinguish between a member variable and a function argument, I recommend you use m_ as a prefix for member variables, and perhaps s_ for static member variables.
I would also avoid unnecessary abbreviations, and just write value instead of val.
Conversion back to an integer
You wrote a templated conversion function, which at least is made explicit. However, inside it will do a C-style cast. This will allow silent casting of the value into types that might not be big enough to hold the value, or to pointers, and to any other type that can be created from an integer. Are you sure you want this to happen?
Instead of having a conversion operator, I would use getVal() (perhaps renamed to to_uint()), but modified to returns an integer of the smallest type with at least bits bits. Then the result can be implicitly casted to other types (which is safer, especially with the appropriate compiler warnings enabled) or the programmer can do some explicit casts on that if they really wanted to. Something like: | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
auto to_uint() const {
if constexpr (bits <= 8) return std::uint8_t(m_value);
if constexpr (bits <= 16) return std::uint16_t(m_value);
…
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
Create a mask instead of using formatBits()
Instead of having a static member function to mask the bits of a value, you can create a static constant holding the mask:
template <std::uint8_t bits>
requires((bits >= 1) && (bits <= 64))
class uintx_t {
protected:
std::uint64_t m_value;
static constexpr std::uint64_t s_mask = UINT64_MAX >> (64 - bits);
public:
uintx_t(std::uint64_t value): m_value(value & s_mask) {}
…
};
What about adding a uintx_t to a regular integer type?
You have two overloads for all the operators. One for adding a uintx_t to another uintx_t, and one for adding a regular integer to a uintx_t. But what if I wanted to add a uintx_t to a regular integer? The following does not compile:
uintx_t<4> nibble = 3;
auto foo = 4 + nibble; // compile error
Obviously you cannot solve this by using member functions. However, you can write a free function to do this:
template <std::uint8_t bits>
static constexpr std::uint64_t operator+(std::uint64_t lhs, uintx_t<bits> rhs) {
return lhs + rhs.to_uint();
}
Note the return type. It's not the same as your operator+(int64_t), which returns a uintx_t<bits>. What if you wrote:
uintx_t<4> nibble = 3;
std::uint64_t large_result = nibble + 20;
Do you expect large_result to be 23 or 7? I would personally say the latter. This matches how regular integers behave; they are automatically promoted to the larger type. And since addition is commutative, you expect the order of the arguments not to matter.
Reducing code duplication
Already you have two overloads for every operator, and as shown that doesn't cover all the possibilties of mixing regular integers and uintx_ts. You probably don't want to add even more overloads. You could consider find a way to reduce the duplication, for example by writing an even more generic operator overload like so:
auto operator+(Uint auto lhs, Uint auto rhs)
-> std::common_type<decltype(lhs), decltype(rhs)>
{
return value_of(lhs) + value_of(rhs);
} | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
c++, integer, binary
Where Uint is then a concept that matches both std::uint64_t and your uintx_t. Then there is a helper function value_of(), which just returns the input if it's a regular integer, and returns the result of .to_uint() if it's a uintx_t. You want to overload std::common_type so the common type of two uintx_ts is the larger uintx_t, and std::uint64_t if one of the sides is std::uint64_t. | {
"domain": "codereview.stackexchange",
"id": 44699,
"lm_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, binary",
"url": null
} |
beginner, c, networking, proxy
Title: Socks4 Client/Server implementation
Question: I implemented a basic Socks4 client and server which can handle CONNECT requests only right now also without identfication protocol support.
I've tested it with a simple ncat echo server which works but I would like to have a review of my:
project structure
filenaming/code splitting
naming/design of structures
error handling
and of course the code.
handling multiple connections (thread for each session? threadpool?)
I tried to create a flexible socks_config and socks structure but I am not sure if I succeeded. I really want to avoid having socks4_client and socks4_server to achive a simple and small interface for the user, where the functions returns if it is the wrong "object type".
I've read about the usage of poll and select with many connections which is not recommended so I stick to the threaded-way but thread creation is expensive. Would be nice to hear what you think is right.
I also am not sure if my usage of poll is stupid or correct or could be better.
As you will notice the accept function is quite long and not splitted. That is because I am not sure how I should split it. But maybe you have some hints for me.
While writing this I realized that the accept function is blocking until the client send a connect request. So should I add all procedures after the accept() call to the thread function?
Is my accept function unnecessary then?
I have an repo available at: https://github.com/mortytheshorty/socks
This is my project structure:
├── CMakeLists.txt
├── include
│ └── socks.h
├── socks4.rfc
└── src
├── include
│ ├── socket_config.h
│ ├── socks4.h
│ └── socks_internal.h
├── readFromSocket.c
├── sendToSocket.c
├── socket_configuration.c
├── socks_accept.c
├── socks_close.c
├── socks_connect.c
├── socks_init.c
├── socks_listen.c
├── socks_log.c
├── test
│ ├── client.c
│ └── server.c
└── thread.c | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
Here the source code:
socks.h
//
// Created by flo on 4/18/23.
//
#ifndef SOCKS_SOCKS_H
#define SOCKS_SOCKS_H
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdarg.h>
#define SOCKS4_VERSION 0x04
/* Socks types*/
enum SOCKS_TYPE {SOCKS_SERVER, SOCKS_CLIENT};
typedef struct socks_config {
int type; // SOCKS_SERVER or SOCKS_CLIENT
int maxconn; // maximum connections possible if SOCKS_SERVER else irgnored
char *ip; // SOCKS_SERVER == interface the to listen on, SOCKS_CLIENT == server address to connect to
uint16_t port; // SOCKS_SERVER == port to listen on, SOCKS_CLIENT == socks server port to connect to
char *filename; // log file name
uint8_t version; // socks version
} socks_config;
typedef struct socks {
socks_config *config; // pointer to socks config
int sock; // network socket
char *ip; // destination ip address to connect to via socks proxy or unused as server
uint16_t port; // destination port to connect to via socks proxy or unused as server
FILE *log; // log file handle
} socks;
typedef struct socks_connection {
int client_sock;
int target_sock;
} socks_connection;
/**
* @brief Initializes the socks structure for client and server aswell
*
* @param socks socks strucuture
* @param config socks configruation
* @retval 0 on success
* @retval n on failure
*/
int socks_init(socks *socks, socks_config *config);
/**
* @brief Connectes a socks client with a remote peer via the proxy
*
* @param client socks client structure
* @param ip destination ip
* @param port destination port
* @retval 0 on success
* @retval n on failure
*/
int socks_connect(socks *client, char *ip, int port);
/**
* @brief Starts listening on configured server
*
* @param proxy socks server structure
* @retval 0 on success
* @retval n on failure
*/
int socks_listen(socks *proxy); | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
/**
* @brief Sends data of specified size to socks socket
*
* @param socks socks socks structure
* @param data data
* @param len size of data
* @retval n on success
* @retval -1 on failure
*/
ssize_t socks_send(socks *socks, void *data, size_t len);
/**
* @brief Receives data of specified size to socks socket
*
* @param socks socks socks structure
* @param data data
* @param len size of data
* @retval n on success
* @retval -1 on failure
*/
ssize_t socks_recv(socks *socks, void *data, size_t len);
/**
* @brief Destroys socks structure
*
* @param socks socks strucutre
*/
void socks_destroy(socks *socks);
#endif //SOCKS_SOCKS_H
socket_config.h
#ifndef SOCKS_CONFIG_H
#define SOCKS_CONFIG_H
#include <inttypes.h>
/* not sure if I want to use it */
void socket_enable_keepalive(int sock);
/* gets ipv4 address and port form socket file descriptor */
/* NOTE: buffer and bufsz must be at least INET6_ADDRSTRLEN or bigger */
int socket_peer_addrinfo(int sock, char *buffer, size_t bufsz, uint16_t *port);
#endif
socks4.h
//
// Created by flo on 4/18/23.
//
#ifndef SOCKS_SOCKS4_H
#define SOCKS_SOCKS4_H
#include <inttypes.h>
#define PACKED __attribute__((__packed__))
#define SOCKS4_VERSION 0x04
#define SOCKS4_CMD_CONNECT 0x01
#define SOCKS4_CMD_BIND 0x02
struct PACKED socks4_request {
uint8_t version;
uint8_t cmd;
uint16_t port; // network byte order
uint32_t ip; // network byte order
uint8_t userid[1];
};
typedef struct socks4_request socks4_request;
#define SOCKS4_REPLY_GRANTED 0x5A
#define SOCKS4_REPLY_FAILED 0x5B
// #define SOCKS4_REPLY_IDENT_CONNECT_FAILED 0x5C
// #define SOCKS4_REPLY_IDENT_AUTH_FAILED 0x5D
struct PACKED socks4_reply {
uint8_t version;
uint8_t code;
uint16_t port;
uint32_t ip;
};
typedef struct socks4_reply socks4_reply; | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
enum SOCKS4_ERRORS {
SOCKS_OK,
SOCKS_SEND_ERR,
SOCKS_RECV_ERR,
SOCKS_REPLY_INVAL,
SOCKS_REQUEST_DENY,
SOCKS_SOCKCREAT_ERR,
SOCKS_LOGCREAT_ERR,
SOCKS_IP_INVAL,
SOCKS_SOCKREUSE_ERR,
SOCKS_SERVER_BIND_ERR,
SOCKS_CLIENT_CONNECT_ERR,
SOCKS_SERVER_ACCEPT_ERR,
SOCKS_SERVER_CONNECT_ERR, // server can not connect to destination
SOCKS_LISTEN_ERR,
};
#endif //SOCKS_SOCKS4_H
socks_internal.h
#ifndef SOCKS_INTERNAL_H
#define SOCKS_INTERNAL_H
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include "../../include/socks.h"
#include "socket_config.h"
#include "socks4.h"
ssize_t readFromSocket(int sock, void *buf, size_t size);
ssize_t sendToSocket(int sock, void *buf, size_t size);
void *socks_connection_thread(void *pipefdsp);
int socks_accept(socks *proxy, socks_connection *conn);
int socks_log(socks *socks, const char *function, const char *fmt, ...);
#endif
readFromSocket.c
#include "include/socks_internal.h"
ssize_t readFromSocket(int sock, void *buf, size_t size)
{
char *pbuf = (char*) buf;
ssize_t num_bytes, total = 0;
while (total < size) {
num_bytes = recv(sock, &pbuf[total], size-total, 0);
if (num_bytes <= 0) {
if ((num_bytes < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) {
break;
}
return -1;
}
total += num_bytes;
}
return total;
}
sendToSocket.c
#include "include/socks_internal.h"
ssize_t sendToSocket(int sock, void *buf, size_t size)
{
char *pbuf = (char*) buf;
ssize_t num_bytes, total = 0;
while (total < size) {
num_bytes = send(sock, &pbuf[total], size-total, 0);
if (num_bytes < 0) {
if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
break;
}
return -1;
}
total += num_bytes;
} | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
return total;
}
socket_config.c
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <sys/signal.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#define check(expr) if (!(expr)) { perror(#expr); kill(0, SIGTERM); }
void socket_enable_keepalive(int sock) {
int yes = 1;
check(setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(int)) != -1);
int idle = 1;
check(setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(int)) != -1);
int interval = 1;
check(setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(int)) != -1);
int maxpkt = 10;
check(setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &maxpkt, sizeof(int)) != -1);
}
void *get_in_addr(const struct sockaddr_storage *storage) {
if( storage->ss_family == AF_INET) // IPv4 address
return &(((struct sockaddr_in*)storage)->sin_addr);
// else IPv6 address
return &(((struct sockaddr_in6*)storage)->sin6_addr);
}
int socket_peer_addrinfo(int sock, char *buffer, size_t bufsz, uint16_t *port)
{
if(bufsz != INET6_ADDRSTRLEN) {
return -1;
}
struct sockaddr_storage inaddr;
socklen_t inaddr_len = sizeof(inaddr);
getpeername(sock, (struct sockaddr*) &inaddr, &inaddr_len);
if(inet_ntop(inaddr.ss_family, get_in_addr(&inaddr), buffer, inaddr_len) == NULL) {
return -1;
}
if(port) {
*port = ntohs(((struct sockaddr_in*)&inaddr)->sin_port);
}
return 0;
}
int socket_local_addrinfo(int sock, char *buffer, size_t bufsz, uint16_t *port)
{
if(bufsz < INET6_ADDRSTRLEN) {
return -1;
}
struct sockaddr_storage inaddr;
socklen_t inaddr_len = sizeof(inaddr);
getsockname(sock, (struct sockaddr*) &inaddr, &inaddr_len);
if(inet_ntop(inaddr.ss_family, get_in_addr(&inaddr), buffer, inaddr_len) == NULL) {
return -1;
} | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
if(port) {
*port = ntohs(((struct sockaddr_in*)&inaddr)->sin_port);
}
return 0;
}
socks_accept.c
#include "include/socks_internal.h"
int target_connect(socks *proxy, socks4_request *req, int client_sock, int *target_sock)
{
char ip[INET6_ADDRSTRLEN];
uint16_t port;
socks4_reply reply;
struct sockaddr_in inaddr;
memset(&inaddr, 0, sizeof(inaddr));
inaddr.sin_family = AF_INET;
inaddr.sin_addr.s_addr = req->ip;
inaddr.sin_port = req->port;
*target_sock = socket(AF_INET, SOCK_STREAM, 0);
if(target_sock < 0) {
socks_log(proxy, __FUNCTION__, "failed to create remote peer socket.");
return SOCKS_SOCKCREAT_ERR; // SOCKS_SERVER_TARGET_SOCKET_CREATE_ERROR
}
socket_peer_addrinfo(client_sock, ip, sizeof(ip), &port);
// we try to connect to the remote peer for the client
if(connect(*target_sock, (struct sockaddr*) &inaddr, sizeof(inaddr)) != 0) {
reply.version = SOCKS4_VERSION;
reply.code = SOCKS4_REPLY_FAILED;
reply.ip = inaddr.sin_addr.s_addr;
reply.port = inaddr.sin_port;
if(sendToSocket(client_sock, &reply, sizeof(reply)) != sizeof(reply)) {
socks_log(proxy, __FUNCTION__, "failed to send reply about failed connect to %s:%d", ip, port);
return SOCKS_SEND_ERR;
}
socks_log(proxy, __FUNCTION__, "failed to connect to remote peer '%s:%d'", ip, port);
return SOCKS_SERVER_CONNECT_ERR; // SOCKS_SERVER_TARGET_CONNECT_ERROR
}
socks_log(proxy, __FUNCTION__, "CONNECT from %s:%d to %s:%d", ip, port, inet_ntoa(*(struct in_addr*) &req->ip), ntohs(req->port));
return SOCKS_OK;
}
int socks_accept(socks *proxy, socks_connection *conn)
{
if(proxy->config->type != SOCKS_SERVER) {
socks_log(proxy, __FUNCTION__, "can not listen to socks handle. socks handle is a client");
}
socks4_request request;
socks4_reply reply; | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
char ip[INET6_ADDRSTRLEN];
uint16_t port;
int target_sock = -1;
int client_sock = -1;
int rc = 0;
client_sock = accept(proxy->sock, NULL, NULL);
if(client_sock < 0) {
socks_log(proxy, __FUNCTION__, "socks_accept: failed to accept connection from %s", "unknown");
return SOCKS_SERVER_ACCEPT_ERR; // SOCKS_SERVER_ACCEPT_ERROR see: errno
}
socket_peer_addrinfo(client_sock, ip, sizeof(ip), &port);
socks_log(proxy, __FUNCTION__, "connection from %s:%d", ip, port);
if(readFromSocket(client_sock, &request, sizeof(request)) != sizeof(request)) {
socks_log(proxy, __FUNCTION__, "failed to receive request from '%s:%d'", ip, port);
close(client_sock);
return SOCKS_RECV_ERR; // SOCKS_SERVER_RECV_ERROR
}
if(request.userid != 0) {
// identifaction protocol code
}
rc = target_connect(proxy, &request, client_sock, &target_sock);
if( rc ) {
return SOCKS_SERVER_CONNECT_ERR;
}
// build the reply
reply.version = SOCKS4_VERSION;
reply.code = SOCKS4_REPLY_GRANTED;
reply.port = request.port;
reply.ip = request.ip;
// send it back to the client
if(sendToSocket(client_sock, &reply, sizeof(reply)) != sizeof(reply)) {
socks_log(proxy, __FUNCTION__, "failed to send reply about successful connect to '%s:%d'", "unknown", 0);
close(client_sock);
return SOCKS_SEND_ERR; // SOCKS_SERVER_SEND_ERROR
}
conn->client_sock = client_sock;
conn->target_sock = target_sock;
return 0;
}
socks_close.c
#include "include/socks_internal.h"
void socks_destroy(socks *socks_handle)
{
close(socks_handle->sock);
socks_log(socks_handle, __FUNCTION__, "closing connection");
if(socks_handle->log) {
fclose(socks_handle->log);
}
}
socks_connect.c
#include "include/socks_internal.h"
int socks_connect(socks *client, char *ip, int port) {
client->ip = ip;
client->port = port; | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
ssize_t ret = 0;
socks4_request request;
request.version = SOCKS4_VERSION;
request.cmd = SOCKS4_CMD_CONNECT;
request.port = htons((short) port);
request.ip = inet_addr(ip);
request.userid[0] = 0x00;
if((ret = sendToSocket(client->sock, &request, sizeof(request))) != sizeof(request)) {
socks_log(client, __FUNCTION__, "failed to send CONNECT request");
return SOCKS_SEND_ERR;
}
socks4_reply reply;
if((ret = readFromSocket(client->sock, &reply, sizeof(reply))) != sizeof(reply)) {
socks_log(client, __FUNCTION__, "failed to receive reply from socks server '%s:%d'", client->config->ip, client->config->port);
return SOCKS_RECV_ERR;
}
switch(reply.code) {
case SOCKS4_REPLY_GRANTED:
socks_log(client, __FUNCTION__, "connection to '%s:%d' established", client->ip, client->port);
return 0;
case SOCKS4_REPLY_FAILED:
socks_log(client, __FUNCTION__, "connection to '%s:%d' denied", client->ip, client->port);
return SOCKS_REQUEST_DENY;
default:
socks_log(client, __FUNCTION__, "received unsupported reply code '%d' (X'%x')", reply.code, reply.code);
return SOCKS_REPLY_INVAL;
}
}
socks_init.c
//
// Created by flo on 4/17/23.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <sys/ioctl.h>
#include "include/socks_internal.h"
int socks_init(socks *socks_handle, socks_config *config)
{
int rc = 0;
int on = 1;
socks_handle->config = config;
if(config->filename)
{
socks_handle->log = fopen(config->filename, "w");
if( !socks_handle->log ) {
fprintf(stderr, "error: can't open logfile '%s'\n", config->filename);
return SOCKS_LOGCREAT_ERR;
}
}
socks_log(socks_handle, __FUNCTION__, "Socks%d-%s started.", config->version, (config->type == SOCKS_SERVER) ? "Server" : "Client"); | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
// initialize socks main socket
socks_handle->sock = socket(AF_INET, SOCK_STREAM, 0);
if(socks_handle->sock < 0)
{
socks_log(socks_handle, __FUNCTION__, "failed to create socket");
return SOCKS_SOCKCREAT_ERR; // SOCKS_SOCKET_CREATION_ERROR
}
/* this is SOCKS VERSION dependent */
struct sockaddr_in inaddr;
memset(&inaddr, 0, sizeof(inaddr));
inaddr.sin_family = AF_INET;
inaddr.sin_port = htons((uint16_t) config->port);
inaddr.sin_addr.s_addr = inet_addr(config->ip);
if(inaddr.sin_addr.s_addr == INADDR_NONE)
{
socks_log(socks_handle, __FUNCTION__, "failed to parse ip address %s", config->ip);
return SOCKS_IP_INVAL; // SOCKS_WRONG_IP_ADDRESS
}
/* if server, bind address to socket and set it reusable */
if(config->type == SOCKS_SERVER)
{
rc = setsockopt(socks_handle->sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(rc < 0) {
socks_log(socks_handle, __FUNCTION__, "failed to enable reuse of socket address");
return SOCKS_SOCKREUSE_ERR;
}
if( bind(socks_handle->sock, (struct sockaddr*) &inaddr, sizeof(inaddr)) != 0 )
{
socks_log(socks_handle, __FUNCTION__, "failed to bind %s to socket.", config->ip);
return SOCKS_SERVER_BIND_ERR; // SOCKS_BIND_ERROR
}
}
/* if client, try to connect to proxy server */
else if(config->type == SOCKS_CLIENT)
{
if(connect(socks_handle->sock, (struct sockaddr*)&inaddr, sizeof(inaddr)) != 0)
{
socks_log(socks_handle, __FUNCTION__, "failed to connect to socks server %s", config->ip);
return SOCKS_CLIENT_CONNECT_ERR; // SOCKS_CLIENT_CONNECT_ERROR
}
socks_log(socks_handle, __FUNCTION__, "connected to socker server %s:%d", config->ip, config->port);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
return 0;
}
/* sends data via proxy server */
ssize_t socks_send(socks *client, void *data, size_t len)
{
return sendToSocket(client->sock, data, len);
}
/* reads data from proxy server */
ssize_t socks_recv(socks *client, void *data, size_t len)
{
return readFromSocket(client->sock, data, len);
}
socks_listen.c
#include <stdio.h>
#include <pthread.h>
#include "include/socks_internal.h"
int socks_listen(socks *proxy)
{
if(proxy->config->type != SOCKS_SERVER) {
socks_log(proxy, __FUNCTION__, "can not listen to socks handle. socks handle is a client");
return -1;
}
pthread_t thread;
socks_connection conn;
int conidx = 0;
if(listen(proxy->sock, proxy->config->maxconn) != 0) {
socks_log(proxy, __FUNCTION__, "failed to listen on %s", proxy->config->ip);
return SOCKS_LISTEN_ERR; // SOCKS_LISTEN_ERROR see: errno
}
socks_log(proxy, __FUNCTION__, "listening on '%s:%d'", proxy->config->ip, proxy->config->port);
for(;;) {
socks_connection conn;
int ret = socks_accept(proxy, &conn);
if(ret < 0) {
// SOCKS_ACCEPT ERROR
socks_log(proxy, __FUNCTION__, "failed to accept connection from %s", "unkown");
continue;
}
pthread_create(&thread, NULL, socks_connection_thread, &conn);
conidx++;
}
return 0;
}
socks_log.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include "include/socks_internal.h"
int socks_log(socks *socks, const char *function, const char *fmt, ...)
{
if(socks->log) {
va_list args;
va_start(args, fmt);
time_t now = time(NULL); // get current time
char buffer[128];
struct tm tnow;
gmtime_r(&now, &tnow); // create UTC time
strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S-%Z", &tnow); // create UTC time format string | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
fprintf(socks->log, "%s: ", buffer); // log timestamp
vfprintf(socks->log, fmt, args); // log message
if(errno) { // if errno is set, log calling function with error string
fprintf(socks->log, "%s: %s", function, strerror(errno));
}
va_end(args);
fputc('\n', socks->log);
fflush(socks->log);
}
return 0;
}
thread.c
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <stdbool.h>
#define _GNU_SOURCE
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <poll.h>
#include "include/socks_internal.h"
#define MAX_SOCKETS 2
#define DEFAULT_TIMEOUT (3 * 60 * 1000)
#define CLIENT_POLL 0
#define REMOTE_POLL 1
int timeout = DEFAULT_TIMEOUT;
void *socks_connection_thread(void *pipefd) {
pthread_detach(pthread_self());
socks_connection conn = *(socks_connection*) pipefd;
int rc = 0;
int timeout = DEFAULT_TIMEOUT;
/* two pollfd's for listening on remote peer and client connection for events */
struct pollfd pfds[MAX_SOCKETS];
nfds_t nfds = MAX_SOCKETS;
uint8_t client_buf[4096];
size_t client_buf_size = 0;
uint8_t target_buf[4096];
size_t target_buf_size = 0;
ssize_t num_bytes;
memset(&pfds, 0, sizeof(pfds));
/* set sockets to non blocking */
int opt = 1;
ioctl(conn.client_sock, FIONBIO, &opt);
ioctl(conn.target_sock, FIONBIO, &opt);
while(true) {
pfds[CLIENT_POLL].fd = conn.client_sock;
pfds[CLIENT_POLL].events = POLLIN;
pfds[REMOTE_POLL].fd = conn.target_sock;
pfds[REMOTE_POLL].events = POLLIN;
/* waiting for some events */
rc = poll(pfds, MAX_SOCKETS, timeout);
if(rc < 0) {
fprintf(stderr, "poll() failed: %s\n", strerror(errno));
break;
} | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
if(rc == 0) {
fprintf(stderr, "poll() timed out. End Connection\n");
break;
}
/* there is something to read form the client side */
if(pfds[CLIENT_POLL].revents & POLLIN)
{
num_bytes = readFromSocket(conn.client_sock, &client_buf[client_buf_size], sizeof(client_buf)-client_buf_size);
if(num_bytes < 0) break; // client connection lost
if(num_bytes > 0) {
printf("read from client: %s (%ld)\n", client_buf, num_bytes);
client_buf_size += num_bytes;
pfds[REMOTE_POLL].revents = POLLOUT;
}
}
/* there is something to read from the remote side */
else if(pfds[REMOTE_POLL].revents & POLLIN)
{
//printf("Got data from remote.\n");
num_bytes = readFromSocket(conn.target_sock, target_buf, sizeof(target_buf));
if (num_bytes < 0) break; // remote connection lost
if (num_bytes > 0) {
printf("read from peer: %s (%ld)\n", target_buf, num_bytes);
target_buf_size += num_bytes;
pfds[CLIENT_POLL].revents = POLLOUT;
}
}
/* client has data to receive */
if(pfds[CLIENT_POLL].revents & POLLOUT) {
num_bytes = sendToSocket(conn.client_sock, target_buf, target_buf_size);
if (num_bytes < 0) break;
if (num_bytes > 0) {
printf("forward to client: %s (%ld)\n", target_buf, num_bytes);
// remove the sent bytes...
target_buf_size -= num_bytes;
memmove(client_buf, &client_buf[num_bytes], client_buf_size); | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
}
} else if(pfds[REMOTE_POLL].revents & POLLOUT) {
num_bytes = sendToSocket(conn.target_sock, client_buf, num_bytes);
if(num_bytes < 0) break;
if(num_bytes > 0) {
printf("forward to remote peer: %s (%ld)\n", client_buf, num_bytes);
// remove the sent bytes...
client_buf_size -= num_bytes;
memmove(target_buf, &target_buf[num_bytes], target_buf_size);
}
}
else {
// unexpected event result appeared so close the connection
break;
}
}
// all done
close(conn.client_sock);
close(conn.target_sock);
printf("Thread terminating\n");
}
Answer: Key points
[...] I would like to have a review of my:
project structure
It looks sensible to me. You could create a doc/ directory where you put in any documentation like socks4.rfc.
filenaming/code splitting
What you did is fine. However, it would also have been acceptable to just have a socks.c file that contains all the code that's now distributed over several socks_*.c files, and to put utility functions like readFromSocket(), writeToSocket() and socks_connection_thread() in a utils.c file. It's a matter of taste. Nowadays compilers and code editors deal with large files very well.
I would rename include/socks.h to include/socks4.h though, since it really is SOCKS4-specific.
naming/design of structures
That's fine. I would however not bother with PACKED. The variables are already layed out in such a way that they are naturally packed, there is no need to force that in any way. The only issue is the uint8_t userid[1] field. It's not really 1 byte, it's actually a variable length field that you are currently not handling in your code, I think you assume it will always be just a NUL-byte? I would write another function to read variable-length, NUL-terminated strings from a socket.
error handling | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
error handling
You are doing it, but it's not consistent. In some functions you return an error code, in others you do kill(0, SIGTERM). I would make it so everything returns an error code, killing the process is quite rude and prevents the caller from dealing with errors in a better way.
Also consider which errors really need to be dealt with. So what if SO_KEEPALIVE cannot be set? It will not prevent you from making a connection to the SOCKS server. In this case, ignoring the error might be the best approach. You could consider logging a warning though.
If a system call returns EAGAIN, it should be safe to immediately retry it again. So instead of doing a break, it might be better to continue. The same is not true for EWOULDBLOCK.
and of course the code.
Others have already commented on that, and I don't have much to add, but see below.
handling multiple connections (thread for each session? threadpool?) | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
handling multiple connections (thread for each session? threadpool?)
There are various trade-offs here. You could do it without threads, and just poll() all the filedescriptors. You don't get the benefit of using multiple cores if you have lots of traffic to deal with, but on the other hand, you don't have to deal with any thread-related issues.
One thread per session is fine, however if you have lots of connections, you have to consider the per-thread overhead. In particular, each thread will need memory for its stack, and that can be quite a lot (something like 2 MB on Linux). On 32-bit systems, that could cause you to run out of (virtual) memory quite fast. You can use pthread attributes to start threads with a smaller stack to work around this.
A thread pool would be the most complicated solution. Are you going to distribute connections over the threads? What if one threads gets all the active connections and the others get relatively inactive ones? Or is every thread going to poll() all the sockets? This can cause all threads to wake up every time there is some activity. Or do you want one thread that poll()s all sockets and then wakes up one or more threads as required to handle the actual data arriving on a connection? That requires a lot of synchronization.
If you want it to be multi-threaded, then I would go for one thread per connection. It's the simplest, it's quite efficient, and if you keep the stack space in mind you'll probably be fine.
Type safety
I tried to create a flexible socks_config and socks structure but I am not sure if I succeeded. I really want to avoid having socks4_client and socks4_server to achive a simple and small interface for the user, where the functions returns if it is the wrong "object type". | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
beginner, c, networking, proxy
But now you rely on your code to check if the right "object type" is passed in. Whereas if you have separate structs for this, the compiler can check at compile time whether you pass the right type of object to a function.
Note that you can nest structs, so you can reduce code duplication like so:
typedef struct socks_common_config {
char *ip;
uint16_t port;
char *filename;
uint8_t version;
} socks_common_config;
typedef struct socks_server_config {
int maxconn;
socks_common_config common;
} socks_server_config;
typedef struct socks_client_config {
socks_common_config common;
} socks_client_config;
No need for struct sock
Instead of having a socks_init() function and then socks_connect() and socks_listen(), why not pass the configuration directly to the latter two functions?
int socks_connect(socks_client_config *config, char *ip, int port);
int socks_listen(socks_server_config *config);
There is no socks struct necessary anymore. The int returns by socks_connect() is just a filedescriptor of the established proxy connection (or -1 in case of errors). | {
"domain": "codereview.stackexchange",
"id": 44700,
"lm_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, networking, proxy",
"url": null
} |
make
Title: Makefile template
Question: I have created a Makefile template file which I hope to be able to easily drop in to a folder and have useful targets ready. I am, however, not very familiar with make's language and am looking for suggestions about correctness/readability, or ways to make this file simpler. The template is only intended to be used for C code (not C++).
The Makefile expects the project structure to be as follows -
project_root/
|--Makefile
|--build/ <--- Binaries
|--src/ <--- Source files
|--obj/ <--- Objects and pre-compiled headers
|--inc/ <--- Header files
This is the full Makefile -
# r - diables built-in rules
# R - diables built-in variables
MAKEFLAGS += -rR
# Make all targets depend on this Makefile
.EXTRA_PREREQS:= $(abspath $(lastword $(MAKEFILE_LIST)))
# Program name
P=
INCLUDE_DIR=inc
OBJECT_DIR=obj
BUILD_DIR=build
SOURCE_DIR=src
CC=gcc
CFLAGS=-Wall -Wextra -Wpedantic -I$(INCLUDE_DIR) -I$(OBJECT_DIR) # OBJECT_DIR contains the precompiled headers
LDFLAGS=
DBGFLAGS=-fsanitize=address,undefined,integer-divide-by-zero -fno-omit-frame-pointer
LDLIBS=
HEADERS=algos sorts array shared # Header files
UNITS=algos sorts array # Compilation units
# Generate lists of headers, sources, objects, and object-with-debugging-symbols
HDRS=$(patsubst %, $(OBJECT_DIR)/%.h.gch, $(HEADERS))
SRCS=$(patsubst %,$(SOURCE_DIR)/%.c, $(UNITS))
OBJS=$(patsubst %, $(OBJECT_DIR)/%.o, $(UNITS))
OBJS_DEBUG=$(patsubst %,$(OBJECT_DIR)/%.o.debug, $(UNITS))
# build main binary by default
.PHONY: default
default: $(BUILD_DIR)/$(P)
# build main binary, main binary with debug symbols, and main binary built for valgrind
.PHONY: all
all: $(BUILD_DIR)/$(P) $(BUILD_DIR)/$(P)_debug $(BUILD_DIR)/$(P)_grind
# Build pre-compiled header file
.SECONDARY: $(OBJECT_DIR)/%.gch
$(OBJECT_DIR)/%.gch: $(INCLUDE_DIR)/%
@echo Building pre-compiled header: $@
@mkdir -p $(OBJECT_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $< -o $@ | {
"domain": "codereview.stackexchange",
"id": 44701,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "make",
"url": null
} |
make
# Build object file
.SECONDARY: $(OBJECT_DIR)/%.o
$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c $(DEPS)
@echo Building object: $@
@mkdir -p $(OBJECT_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $< -c -o $@
# Build object file with debugging symbols
.SECONDARY: $(OBJECT_DIR)/%.o.debug
$(OBJECT_DIR)/%.o.debug: LDFLAGS+=-g
$(OBJECT_DIR)/%.o.debug: $(SOURCE_DIR)/%.c $(DEPS)
@echo Building object with debug symbols: $@
@mkdir -p $(OBJECT_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $< -c -o $@
# Build main binary
$(BUILD_DIR)/$(P): $(OBJS)
@echo Building $@
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $^ -O3 -o $@
# Build binary with debugging symbols. Uses -g and ASan. To be used for valgrind
$(BUILD_DIR)/$(P)_debug: LDFLAGS+=-g
$(BUILD_DIR)/$(P)_debug: $(OBJS_DEBUG)
@echo Building $@
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $(DBGFLAGS) $^ -o $@
# Build binary with debugging symbols. Uses -g only. Cannot be used for valgrind
$(BUILD_DIR)/$(P)_grind: LDFLAGS+=-g
$(BUILD_DIR)/$(P)_grind: $(OBJS_DEBUG)
@echo Building $@
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
# Run program
.PHONY: run
run: $(BUILD_DIR)/$(P)
$^
# Start gdb on debug build
.PHONY: debug
debug: $(BUILD_DIR)/$(P)_debug
gdb $^
# Run valgrind on grind build
.PHONY: grind
grind: $(BUILD_DIR)/$(P)_grind
valgrind --track-origins=yes --leak-check=full --leak-resolution=high $^
# Run linter
.PHONY: lint
lint: $(SRCS)
clang-tidy\
--quiet\
--checks=*,\
-llvmlibc-restrict-system-libc-headers,\
-altera-id-dependent-backward-branch,\
-modernize-macro-to-enum,\
-altera-unroll-loops,\
-llvm-include-order,\
-bugprone-reserved-identifier,\
-cert-dcl37-c,\
-cert-dcl51-cpp,\
-misc-no-recursion,\
-google-readability-todo\
$^\
-- -I$(INCLUDE_DIR) # Have to include this or clang will complain about not being able to find header files. See https://stackoverflow.com/a/56457021/15446749 | {
"domain": "codereview.stackexchange",
"id": 44701,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "make",
"url": null
} |
make
# Format all sources
.PHONY: format
format: $(SRCS)
clang-format --fallback-style=LLVM -i $(SRCS)
.PHONY: clean
clean:
rm -f $(OBJECT_DIR)/*.o
rm -f $(OBJECT_DIR)/*.o.debug
rm -f $(OBJECT_DIR)/*.h.gch
rm -f $(BUILD_DIR)/$(P){,_debug,_grind}
rmdir obj
rmdir build
Answer: I'm not a C developer, so I don't know what's idiomatic in that community. That said:
The linter flags could probably be in a configuration file, to avoid cluttering up actual code.
Making all flags depend on the Makefile itself is an interesting pattern. Do you have a reference discussing it? I feel like it could possibly cause more problems than it solves.
The clean target references both OBJECT_DIR and obj directly. You probably want to always reference OBJECT_DIR.
Why not delete OBJECT_DIR and BUILD_DIR recursively? Nothing else should be writing to those directories, after all.
Idiomatically, uppercase variables are free to be overridden at runtime. But HDRS etc look like they should not be overridden, so they could be lowercase.
Rather than the "Program name" comment, why not rename the variable to the self-explanatory PROGRAM_NAME? | {
"domain": "codereview.stackexchange",
"id": 44701,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "make",
"url": null
} |
python, beginner, python-3.x, chess
Title: Checking if a chessboard presented as a dictionary, is a valid chessboard
Question: Here's my solution to the Chess Dictionary Validator project in Automate the boring stuff by Al Sweigart. I'd love to know how I can improve this code so that it's more efficient. Thank you
Function accepts a dictionary that represents a chessboard. Eg: {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} . A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'.
def isValidChessboard(chessboard):
# function accept a dict
#create a dictionary with all the pieces of each color as the key
# and the valid starting number of the pieces as value
pieces = {'pawn': 8,'knight': 2,'bishop': 2,'rook': 2,'queen': 1,'king': 1}
colors = ['w','b']
all_pieces = {} #the valid dict to compare pieces and quantities to
for color in colors:
for p, num in pieces.items():
all_pieces[color + p] = num
all_pieces[''] = 0 #no piece is valid if empty quare
current_pieces = list(chessboard.values()) #get a list of all the pieces present on the chessboard | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
def is_valid_p(current_pieces):
#accepts a list, checking if the pieces of the chessboard are valid
if 'bking' not in current_pieces or 'wking' not in current_pieces:
return False
for c_p in current_pieces: #checking if the pieces' names are valid
if c_p not in all_pieces:
return False
for p in all_pieces:
if p in current_pieces and p != '':
#looping through all the valid p in valid dict, if p is present
#on the chessboard, count and compare to the valid number of the piece
if current_pieces.count(p) > all_pieces[p]:
return False
return True
valid = True
for position in chessboard: #checking coordinates of the square
if len(position) != 2:
valid = False
break
elif int(position[0]) not in range(1, 9) or position[1] not in ['a','b','c','d','e','f','g','h']:
valid = False
break
else:
if not is_valid_p(current_pieces): #checking the pieces itself
valid = False
if not valid:
print("Your board is invalid")
else:
print("Your board is valid")
Answer: Organization
It's a bit difficult to follow the logic of your function due to the large inner function is_valid_p() cutting it in half. Plus, most of the lines above this inner function are only used within it. So, I would move the inner function outside to make it more clear where work is being done.
def is_valid_p(current_pieces):
#create a dictionary with all the pieces of each color as the key
# and the valid starting number of the pieces as value
pieces = {'pawn': 8,'knight': 2,'bishop': 2,'rook': 2,'queen': 1,'king': 1}
colors = ['w','b']
all_pieces = {} #the valid dict to compare pieces and quantities to
for color in colors:
for p, num in pieces.items():
all_pieces[color + p] = num | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
all_pieces[''] = 0 #no piece is valid if empty quare
#accepts a list, checking if the pieces of the chessboard are valid
if 'bking' not in current_pieces or 'wking' not in current_pieces:
return False
for c_p in current_pieces: #checking if the pieces' names are valid
if c_p not in all_pieces:
return False
for p in all_pieces:
if p in current_pieces and p != '':
#looping through all the valid p in valid dict, if p is present
#on the chessboard, count and compare to the valid number of the piece
if current_pieces.count(p) > all_pieces[p]:
return False
return True
def isValidChessboard(chessboard):
# function accept a dict
current_pieces = list(chessboard.values()) #get a list of all the pieces present on the chessboard
valid = True
for position in chessboard: #checking coordinates of the square
if len(position) != 2:
valid = False
break
elif int(position[0]) not in range(1, 9) or position[1] not in ['a','b','c','d','e','f','g','h']:
valid = False
break
else:
if not is_valid_p(current_pieces): #checking the pieces itself
valid = False
if not valid:
print("Your board is invalid")
else:
print("Your board is valid")
Next, the logic of the isValidChessboard() can be cleaned up by removing the print() statements and having the function return True or False (most functions and methods that start with is___() return boolean values). Instead of using value to store the result, we can return once we know the answer.
def isValidChessboard(chessboard):
# function accept a dict | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
current_pieces = list(chessboard.values()) #get a list of all the pieces present on the chessboard
for position in chessboard: #checking coordinates of the square
if len(position) != 2:
return False
elif int(position[0]) not in range(1, 9) or position[1] not in ['a','b','c','d','e','f','g','h']:
return False
else:
if not is_valid_p(current_pieces): #checking the pieces itself
return False
return True
if not isValidChessboard(chessboard):
print("Your board is invalid")
else:
print("Your board is valid")
Some last bits:
Since there's no more break within this for loop, the else clause will always happen, so let's save some indentation.
Instead of a list of letters for the valid files, we can use a str to save space.
Let's move current_pieces near to where it's used. (Side note: .values() already returns a list, so there's no need to convert it.)
Finally, since it's the last thing the function checks, we can return the result of is_valid_p()
def isValidChessboard(chessboard):
# function accept a dict
for position in chessboard: #checking coordinates of the square
if len(position) != 2:
return False
elif int(position[0]) not in range(1, 9) or position[1] not in 'abcdefgh':
return False
current_pieces = chessboard.values()
return is_valid_p(current_pieces): #checking the pieces itself
Following the requirements of the task
There are three requirements on the number of pieces on the board:
Exactly one white king and one black king.
No more than 8 pawns of either color.
No more than 16 pieces of either color. | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
There is no restriction on the number of any other piece. Because of pawn promotion, a pawn can be converted into any other non-king piece. It is legal for there to be 2, 3, 4, or even 9 white queens on the board (unlikely, but legal). So, the line where you check the number of each type of piece if current_pieces.count(p) > all_pieces[p]: in is_valid_p() is incorrect.
First, let's change the pieces variable to a list and handle the counts later.
def is_valid_p(current_pieces):
#create a dictionary with all the pieces of each color as the key
# and the valid starting number of the pieces as value
pieces = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']
colors = ['w', 'b']
all_pieces = []
for color in colors:
for p in pieces:
all_pieces.append(color + p)
all_pieces.append('') #no piece is valid if empty quare
#accepts a list, checking if the pieces of the chessboard are valid
if 'bking' not in current_pieces or 'wking' not in current_pieces:
return False
for c_p in current_pieces: #checking if the pieces' names are valid
if c_p not in all_pieces:
return False
# Still needs fixing
for p in all_pieces:
if p in current_pieces and p != '':
#looping through all the valid p in valid dict, if p is present
#on the chessboard, count and compare to the valid number of the piece
if current_pieces.count(p) > all_pieces[p]:
return False
return True | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
At the point where we reach the comment # Still needs fixing, we know that there is one white king and one black king, and that all of the piece names are valid. So, we can use simple counts on the piece list to check pawns and other pieces. The task description doesn't mention blank squares, so I don't see a use for the inclusion of '' in all_pieces.
def isValidPieceSet(current_pieces):
#create a dictionary with all the pieces of each color as the key
# and the valid starting number of the pieces as value
pieces = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']
colors = ['w', 'b']
all_pieces = []
for color in colors:
for p in pieces:
all_pieces.append(color + p)
#accepts a list, checking if the pieces of the chessboard are valid
if 'bking' not in current_pieces or 'wking' not in current_pieces:
return False
for c_p in current_pieces: #checking if the pieces' names are valid
if c_p not in all_pieces:
return False
if current_pieces.count('wpawn') > 8:
return False
if current_pieces.count('bpawn') > 8:
return False
# Count the white pieces
if len([p for p in current_pieces if p.startswith('w')]) > 16:
return False
# Count the black pieces
if len([p for p in current_pieces if p.startswith('b')]) > 16:
return False
return True
Let's put the script back together after giving is_valid_p() a clearer name and formatting to match the other function.
def isValidPieceSet(current_pieces):
#create a dictionary with all the pieces of each color as the key
# and the valid starting number of the pieces as value
pieces = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']
colors = ['w', 'b']
all_pieces = []
for color in colors:
for p in pieces:
all_pieces.append(color + p) | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
#accepts a list, checking if the pieces of the chessboard are valid
if 'bking' not in current_pieces or 'wking' not in current_pieces:
return False
for c_p in current_pieces: #checking if the pieces' names are valid
if c_p not in all_pieces:
return False
if current_pieces.count('wpawn') > 8:
return False
if current_pieces.count('bpawn') > 8:
return False
# Count the white pieces
if len([p for p in current_pieces if p.startswith('w')]) > 16:
return False
# Count the black pieces
if len([p for p in current_pieces if p.startswith('b')]) > 16:
return False
return True
def isValidChessboard(chessboard):
# function accept a dict
for position in chessboard: #checking coordinates of the square
if len(position) != 2:
return False
elif int(position[0]) not in range(1, 9) or position[1] not in 'abcdefgh':
return False
current_pieces = chessboard.values()
return isValidPieceSet(current_pieces): #checking the pieces itself
if not isValidChessboard(chessboard):
print("Your board is invalid")
else:
print("Your board is valid") | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
python, beginner, python-3.x, chess
At this point, we have a script that's easy to read and easy to check for correctness. One further improvement would be to create a function for each requirement so that each function only does one thing, but that can come later.
One more note
The task description and this program both allow illegal board positions to be counted as valid: boards with 10 white queens, boards with pawns on the first and eighth ranks, boards with kings attacking each other, and many more. The reason for this is the problem of determining whether an arbitrary board position is legal is very hard. Such a program would have to implement all the rules of chess and then find a sequence of moves that results in the input board. Such a search could take literal millions of years. So, since this task is meant to be programming practice, the scope of the checks is restricted to what is easily programmable. | {
"domain": "codereview.stackexchange",
"id": 44702,
"lm_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, chess",
"url": null
} |
c++, performance, multithreading, thread-safety, multiprocessing
Title: Multi-threading Class in C++
Question: I wrote a C++ class which can take a vector of functions and their respective arguments and execute them in parallel and return a vector of results from its respective functions.
// @file: mthread.hh
// @author: Tushar Chaurasia (Dark-CodeX)
// @license: This file is licensed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007. You may obtain a copy of this license at https://www.gnu.org/licenses/gpl-3.0.en.html.
#ifndef MTHREAD_HH
#define MTHREAD_HH
#include <vector>
#include <thread>
#include <functional>
namespace openutils
{
template <typename return_type, typename... args>
class mthread
{
private:
std::vector<return_type> ret_val;
std::vector<std::thread> threads;
public:
void execute_processes(const std::vector<std::function<return_type(args...)>> &functions, const std::vector<args> &...a);
const std::vector<return_type> &get() const;
std::vector<return_type> &get();
};
template <typename return_type, typename... args>
void mthread<return_type, args...>::execute_processes(const std::vector<std::function<return_type(args...)>> &functions, const std::vector<args> &...a)
{
std::vector<return_type> temp_val(functions.size()); // pre allocate
this->threads = std::vector<std::thread>(functions.size()); // pre allocate
for (std::size_t i = 0; i < functions.size(); i++)
{
this->threads[i] = std::thread([i, &temp_val, &functions, &a...]()
{ temp_val[i] = (functions[i](a[i]...)); });
}
for (std::size_t i = 0; i < this->threads.size(); i++)
{
this->threads[i].join();
}
this->ret_val.swap(temp_val);
}
template <typename return_type, typename... args>
const std::vector<return_type> &mthread<return_type, args...>::get() const
{
return this->ret_val;
} | {
"domain": "codereview.stackexchange",
"id": 44703,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, thread-safety, multiprocessing",
"url": null
} |
c++, performance, multithreading, thread-safety, multiprocessing
template <typename return_type, typename... args>
std::vector<return_type> &mthread<return_type, args...>::get()
{
return this->ret_val;
}
}
#endif
The above library can be used as:
int main()
{
openutils::mthread<int, std::pair<int, int>> thread;
std::vector<std::pair<int, int>> args({{10, 20}, {5, 5}});
thread.execute_processes({[](std::pair<int, int> x)
{ return x.first + x.second; },
[](std::pair<int, int> x)
{ return x.first - x.second; }},
args);
std::vector<int> get = thread.get();
for (const int &x : get)
printf("%d\n", x);
return 0;
}
Result:
30
0
Any suggestions, improvements are appreciated.
Answer: License
Just as a heads up.
// @license: This file is licensed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007. You may obtain a copy of this license at https://www.gnu.org/licenses/gpl-3.0.en.html. | {
"domain": "codereview.stackexchange",
"id": 44703,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, thread-safety, multiprocessing",
"url": null
} |
c++, performance, multithreading, thread-safety, multiprocessing
You have now all licensed this file under Creative Commons. There is a link at the bottom of the page. See: https://stackoverflow.com/help/licensing
Overview
OK. Nice try, if you are just experimenting.
BUT this is a bad idea.
I have a couple of issues with your implementation.
1: Threads are expensive to create.
2: There is no point in making more threads than you have processors. You are just doing busy work swapping between threads when you can simply spend time on one thread.
Given the above two. What you normally do is create a "Work" queue onto which you add work items. Simple interface run() the object has all the parameters embedded. Then you create a "Thread Pool", a set of thread objects(about the number of processors on your hardware). Each thread in the pool will execute a unique work item on the "Work" queue when finished it will get the next item or wait until another one is added.
Do a search for thread groups: Thread Pool in C++
But even thread pools are obsolete. The standard already provides an abstract mechanism to do this. std::async. Here you create an item of work and get a promise back. When the work item is finished the promise contains the result (or exception). Behind the sense the standard can create a thread pool for you.
CodeReview
The term MTHREAD seems very likely to be used previously. I would add the namespace into the include guard to try and make it more unique.
#ifndef MTHREAD_HH
#define MTHREAD_HH
The design of the class seems a bit odd.
template <typename return_type, typename... args>
class mthread
{
private:
std::vector<return_type> ret_val;
std::vector<std::thread> threads;
public:
void execute_processes(const std::vector<std::function<return_type(args...)>> &functions, const std::vector<args> &...a);
const std::vector<return_type> &get() const;
std::vector<return_type> &get();
}; | {
"domain": "codereview.stackexchange",
"id": 44703,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, thread-safety, multiprocessing",
"url": null
} |
c++, performance, multithreading, thread-safety, multiprocessing
There is no constructor. But you start the execution by calling execute_processes() and passing all the values that are needed. Seems like this could be better designed as static method that simply returns the results.
So rather than:
thread.execute_processes({[](std::pair<int, int> x)
{ return x.first + x.second; },
[](std::pair<int, int> x)
{ return x.first - x.second; }},
args);
std::vector<int> get = thread.get();
I would want to use it like:
std::vector<int> get =
mthread::execute_processes({[](std::pair<int, int> x)
{ return x.first + x.second; },
[](std::pair<int, int> x)
{ return x.first - x.second; }},
args);
Don't use this->
If you have to use this-> it means you have accidently shadowed a member variable with a local variable and you need to disambiguify the two members. The trouble is the compiler can not tell when you get it wrong.
So better solution is to always make your identifiers unique. | {
"domain": "codereview.stackexchange",
"id": 44703,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, thread-safety, multiprocessing",
"url": null
} |
python, algorithm
Title: Checking if a Number is a Wilson Prime in Python
Question: I have written a Python function am_i_wilson(P) that takes an integer P as input and checks if it is a Wilson prime. Here's how it works:
If the input P is equal to 0 or 1, the function returns False.
Otherwise, it calculates (fact(P-1) + 1) / (P * P) using the fact() function, where fact(n) calculates the factorial of n.
Finally, it checks if the result is a whole number using the whole_num() function, which returns True if the input is a whole number and False otherwise.
Here's the code:
def am_i_wilson(P):
if P == 1:
return False
if P == 0:
return False
return whole_num((fact(P-1) + 1) / (P * P))
def fact(n):
f = 1
while n > 0:
f *= n
n -= 1
return f
def whole_num(n):
return (n % 1) == 0
I'd appreciate any feedback or suggestions on how to improve the code. Thanks!
Answer: Just as information, note that the first three Wilson primes are 5, 13, 563, and the fourth Wilson prime is known to be greater than 2*1013.
Whatever the fourth Wilson prime is, am_i_wilson won't be suitable to detect it. That number is just too high.
am_i_wilson does not check whether P is a prime number, and may return True improperly when P is not prime but does pass the other condition.
Here are two things that you should probably know, at least so you can use them in different contexts: | {
"domain": "codereview.stackexchange",
"id": 44704,
"lm_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, algorithm",
"url": null
} |
python, algorithm
Checking whether X is divisible by Y typically should not be done by dividing X by Y and checking whether there is a fractional part, because the division may round a not-quite-integer to an integer. A proper way that works in general is checking X % Y == 0.
As an extension of that, if you're going to compute something and then check whether it's divisible by Y, you can (usually, but there are some restrictions) do the whole computation modulo Y, and check whether the result is zero. This has the advantage that the intermediate results do not become arbitrarily large. A factorial becomes very large very quickly, evaluating it modulo (in this case) P² at least makes it a little bit more tractable, but even then it's too slow to detect the fourth Wilson prime. | {
"domain": "codereview.stackexchange",
"id": 44704,
"lm_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, algorithm",
"url": null
} |
java, beginner, calculator
Title: Interest/Discount rate and loan calculator java
Question: I'm currently learning Java at home with YouTube tutorials.
I took a short break from the course to make a small project for calculating costs of loan.
It's not economically accurate - I followed basic logic and not exact mathematical formulas.
I started 1-2 weeks ago but Im learning mainly in the evenings so theres not much experience.
I'm going back to the tutorials after this little experiment/break but I wanted to see if I can get something of my own working.
It consists of two classes - Main and Calculator.
Did I separate classes correctly or should it be rearranged?
Other Rookie mistakes?
General Review?
Main
package MainPackage;
import java.util.Scanner;
public class InterestAndDiscount {
public static double capital;
public static double interest;
public static double inflation;
public static double duration;
public static void main(String[] args) {
System.out.println("Provide the data for calculations:");
Scanner scanner = new Scanner(System.in);
System.out.println("What is the starting capital: ");
capital = scanner.nextDouble();
System.out.println("What is the rate of interest in %: ");
interest = scanner.nextDouble();
System.out.println("What is the inflation rate in %: ");
inflation = scanner.nextDouble();
System.out.println("How long is the duration in years: ");
duration = scanner.nextDouble();
Calculator calculator1 = new Calculator(capital, interest, inflation, duration);
calculator1.creditPayments();
calculator1.capitalIncrease();
calculator1.capitalDecrease();
calculator1.getInfo();
scanner.close();
}
}
Calculator
package MainPackage; | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
scanner.close();
}
}
Calculator
package MainPackage;
public class Calculator {
double capital;
double interest;
double duration;
double inflation;
double sumOfPayments=0;
double newValue=0;
double newCashValue=0;
Calculator(double capital, double interest, double inflation, double duration){
this.capital=capital;
this.interest=interest;
this.inflation=inflation;
this.duration=duration; | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
}
void capitalIncrease() {
double capital=this.capital;
double inflation=this.inflation;
double duration=this.duration;
for(int i=0; i<duration;i++) {
capital=capital*((100+inflation)/100);
System.out.printf("%d year: %,.2f\n",i+1, capital);
}
this.newValue=capital;
}
void capitalDecrease() {
double capital=this.sumOfPayments;
double inflation=this.inflation;
double duration=this.duration;
for(int i=0; i<duration;i++) {
capital=capital*((100-inflation)/100);
System.out.printf("%d year: %,.2f\n",i+1, capital);
}
newCashValue=capital;
}
void creditPayments() {
double capital=this.capital;
double interest=this.interest/12;
double duration=this.duration*12;
double amountPaid=0;
double monthlyPayment;
double monthlyInterest;
for(int i=0; i<duration;i++) {
monthlyInterest=(capital*((100+interest)/100)-capital);
capital=capital+monthlyInterest;
if(i>duration-2) {
monthlyPayment =(capital/(duration-i))+(monthlyInterest-(monthlyInterest/(duration/(i+1)))); //added this to avoid overpayment for last month
} else {
monthlyPayment=(capital/(duration-i))+(monthlyInterest);
}
capital=capital-monthlyPayment;
amountPaid=amountPaid+monthlyPayment;
System.out.printf("monthly Interest: %,.2f\n",monthlyInterest);
System.out.printf("monthly Payment: %,.2f\n",monthlyPayment);
System.out.printf("%d month left capital: %,.2f\n",i+1, capital);
} | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
this.sumOfPayments=amountPaid;
}
void getInfo() {
System.out.printf("Overall paid amount: %,.2f\n",this.sumOfPayments);
System.out.printf("Overall paid interest: %,.2f\n",this.sumOfPayments-this.capital);
System.out.printf("Property value increase: %,.2f\n",this.newValue-this.capital);
System.out.printf("Property value after %.0f years %,.2f \n",this.duration, this.newValue);
System.out.printf("Sum of Payments will be worhth: %,.2f in today`s money\n",this.newCashValue);
}
}
Answer: First of all, I'm coming from a C / C++ / C# and Haskell background and am not too familiar with Java.
However, the main focus of this review are general programming techniques that will help you write robust code that's easily understandable by your peers.
Mutable Global Variables
Making a field public static means that code outside your class can access it, so it essentially becomes a global variable. Global variables should never be mutable - use final to prevent code outside of your class from modifying them.
Howerver, since you only seem to be using these from inside your main method, why not make them local variables in there? | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
Separate computations from output
Also, comparing your main method and your getInfo - the latter is much easier to read because you don't intermingle your computations with those printf statements.
In your main method, I would do those 4 computations first - possibly storing their result in some structure / class - then insert a blank line and then your print statements. You already used descriptive variable names, which is great, and separating the computations from the output will not only make this more readable, but also help you in case you later want to refactor it to return results without printing them.
/Edit: when I first commented, I didn't realize that scanner.nextDouble() was a Java utility function that reads from standard input.
I would move that code into a separate method and insert some blank lines to make it a bit more readable.
Scanner scanner = new Scanner(System.in);
System.out.println("Provide the data for calculations:");
System.out.println("What is the starting capital: ");
capital = scanner.nextDouble();
System.out.println("What is the rate of interest in %: ");
interest = scanner.nextDouble();
System.out.println("What is the inflation rate in %: ");
inflation = scanner.nextDouble();
System.out.println("How long is the duration in years: ");
duration = scanner.nextDouble();
Put the above into a separate method and return these 4 values in a custom data type.
This will make your code much more composable because you can then easily swap out the interactive console input with something else - for instance when writing tests. | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
In your Calculator class, it is generally a good idea to sepatate inputs from data. What I mean by that is that any variables that are only assigned by your class constructor should be marked final - to make it clear that it is an input to your class and not something that your class computed.
Even just separating them with a blank line and marking the inputs final already makes it a bit easier to read:
public class Calculator {
// Inputs
final double capital;
final double interest;
final double duration;
final double inflation;
// Computed
double sumOfPayments=0;
double newValue=0;
double newCashValue=0;
Surprising Side-Effects
To make it easy for others to read and understand your code, never use two variables with the exact same same, but completely different meaning in different lexical scopes.
A computer program will understand that interest and this.interest are two distinct variables - but a human who has seen your outer definition may not realize that you're re-defining it it mean something completely different in an inner lexical scope.
This is also something that will really hurt you later on - imagine for instance that at some point, you need to add additional methods to your classes and also want to collaborate with other people on this. Well, it should be possible for somebody to just look at your class definition and one of it's methods to understand what that method does. For this to work, your other methods must not have any surprising side-effects - such as modifying class fields that look like read-only inputs.
Avoid copying class fiels into local variables:
void capitalIncrease() {
double capital=this.capital;
double inflation=this.inflation;
double duration=this.duration;
There is no need for doing so - it only leads to the following anti-pattern:
capital=capital*((100+inflation)/100); | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
java, beginner, calculator
As I explained above, this is a surprising side-effect as it is not immediately obvious to a reader, that capital no longer refers to the class field.
It is even worse in the creditPayments method, because first you have these assignments:
void creditPayments() {
double capital=this.capital;
double interest=this.interest/12;
double duration=this.duration*12;
and then this code in a loop:
monthlyInterest=(capital*((100+interest)/100) - capital);
capital=capital+monthlyInterest;
if (i > duration-2) {
monthlyPayment = (capital/(duration-i)) + (monthlyInterest - (monthlyInterest/(duration/(i+1)))); //added this to avoid overpayment for last month
} else {
monthlyPayment = (capital/(duration-i)) + (monthlyInterest);
}
capital = capital - monthlyPayment;
amountPaid = amountPaid + monthlyPayment;
A person reading this is likely going to focus on these computations to understand what your code does - the hard math behind them, and not so much the variable declarations at the beginning of the method.
"Time-Scoped" Data
In this particular algorithm, you have several parameters that are "scoped" to a particular time interval - for instance "interest" could be a monthly or yearly value.
You already recognized this in the "math" loop above, where you're using variables such as monthlyPayment. This is really great and shows an understanding of the fundamental concept.
Just try to do it consistently over that code.
You're only making it much harder on yourself when you have a yearly interest called interest, then divide that by 12 and have a variable called monthlyInterest in that same function that's used for something else. | {
"domain": "codereview.stackexchange",
"id": 44705,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, calculator",
"url": null
} |
performance, c, simd
Title: SIMD Vectorizing C Function Generating Floating-point Range
Question: I have a C function that generates a range from the given start, step_size and end values. I use this function in a .Net app by PInvoke, therefore I want to optimize it as much as possible. I am novice SIMD programmer but intermediate in C and x86. I have written the SIMD version of it but not sure that it is well-implemented and wonder if it can be optimized further or be written more efficiently. In essence, I need a code review for the SIMD part.
typedef struct NativeFixedPointDArray_s
{
int length;
PointD_t* memory_block;
}NativeFixedPointDArray_t;
uint64_t align(uint64_t num, uint64_t alignment) {
return (num + alignment - 1) & ~(alignment - 1);
}
NativeFixedDArray_t generate_range(double start, double step_size, double end)
{
int elementsCount = (int)round((end - start) / step_size) + 1;
double* data = malloc(elementsCount * sizeof(double));
if (!data)
return (NativeFixedDArray_t) { 0, 0 };
for (int i = 0; i < elementsCount - 1; i++)
{
data[i] = start;
start += step_size;
}
data[elementsCount - 1] = end;
return (NativeFixedDArray_t) { elementsCount, data };
}
NativeFixedDArray_t generate_range_simd(double start, double step_size, double end)
{
//Calculate the number of elements that will be included in the array using start, step_size and end values.
int elementsCount = (int)round((end - start) / step_size) + 1;
// Align the number of elements with 4 for SIMD optimization.
int alignedElementsCount = align(elementsCount, 4);
double* data = malloc(alignedElementsCount * sizeof(double));
if (!data)
return (NativeFixedDArray_t) { 0, 0 }; | {
"domain": "codereview.stackexchange",
"id": 44706,
"lm_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, simd",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.