text stringlengths 1 2.12k | source dict |
|---|---|
c#, factory-method
Title: Web scraper for e-commerce sites
Question: I'm building web scraper application which takes name, code and price from few sites. I thought factory pattern would fit in my application. I would like to someone review my code and tell if I something missed out.
I have class Item which holds scraped data.
public class Item
{
public string Code { get; set; }
public string Name { get; set; }
public string Price { get; set; }
}
Interface which have method RunScrapingAsync with one parameter list of item codes which I need scape.
public interface IWebScraper
{
Task<List<Item>> RunScrapingAsync(List<string> itemCodes);
}
There I have implementations for three scrapers (Amazon, EBay, AliExpress):
public class AmazonWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public AmazonWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://amazon.com");
}
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ItemCodes = itemCodes;
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
}
public class EBayWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public EBayWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://ebay.com");
}
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ItemCodes = itemCodes;
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
} | {
"domain": "codereview.stackexchange",
"id": 44341,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
public class AliExpressWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public AliExpressWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://aliexpress.com");
}
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ItemCodes = itemCodes;
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
}
Here is my factory class WebScraperFactory:
public enum WebSite
{
Amazon,
EBay,
AliExpress
}
public class WebScraperFactory
{
private readonly Dictionary<WebSite, IWebScraper> _scrapers;
public WebScraperFactory()
{
_scrapers = new Dictionary<WebSite, IWebScraper>();
foreach (WebSite webSite in Enum.GetValues(typeof(WebSite)))
{
_scrapers.Add(webSite, (IWebScraper)Activator.CreateInstance(Type.GetType($"{webSite}WebScraper")));
}
}
public async Task<List<Item>> Execute(WebSite website, List<string> itemCodes) => await _scrapers[website].RunScrapingAsync(itemCodes);
}
This is WinForm app so user have option to run one or more scraping (they are not all mandatory to run). So if user choose to run Amazon and AliExpress it will choose two files with codes add it in Dictionary and on every chosen website call webscraper factory.
Example:
var websitesItemCodes = new Dictionary<WebSite, List<string>>
{
{WebSite.Amazon, amazonCodes},
{WebSite.AliExpress, aliExpressCodes}
}
var websitesItems = new Dictionary<WebSite, List<Item>>
{
{WebSite.Amazon, null},
{WebSite.AliExpress, null}
}
var factory = new WebScraperFactory(); | {
"domain": "codereview.stackexchange",
"id": 44341,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
var factory = new WebScraperFactory();
foreach(var webSite in websitesItemCodes.Keys)
{
websitesItems[webSite] = await factory.Execute(webSite, websitesItemCodes[webSite]);
}
Answer: The point of a factory is to separate objects from their construction. A factory becomes compelling when that construction is somewhat complex. That's all a factory should be doing.
This factory violates Single Responsibility. It keeps object references and implements a common method for itself. That's the job of a base class, either "concrete" or abstract. This lazy construct will bite you in a growing code base. Hear me now and believe me later!
We did that once - no, many times in a factory that generated a number of types. Inevitably a required change on one class took three months because we had to decouple from the factory. This necessity was not trivial and it dominoed to others. Professionally embarrassing, the damaged reputation is hard to recover.
These classes should be subclasses because that is what they obviously are. An abstract class as the base-class is appropriate in this case. An "interface" - the C# keyword interface kind - is appropriate when we want to give unrelated classes the same behavior. By the way, using both interface and abstract class to define the same behavior is superfluous, and in my opinion wrong. It can lead to design corruption and problematic code variations. I've experienced this also.
Keep the factory but get the objects decoupled.
IWebScraper as Design
Web Scraping is a complex endeavor using many parts, participating classes,and algorithm details. This IWebScraper interface is obviously insufficient as it assumes away all complexity and details.
Give me a web scraping code framework, let's call it - which you have done. The framework's API is sufficient to implement web scrapers and therefore IWebScraper interface is unnecessary.
The web scraper "framework" code: | {
"domain": "codereview.stackexchange",
"id": 44341,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
provides an API to code against
requires implementation where needed
provides customization within temporal execution - method template pattern
fully consistent with the maxim Code to interfaces not implementation
Protects design integrity
Ensures execution consistency across implementations | {
"domain": "codereview.stackexchange",
"id": 44341,
"lm_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#, factory-method",
"url": null
} |
rust
Title: Finding the Median and Mode of a slice in Rust
Question: Overview
I’m trying to learn Rust, so I’m reading The Rust Programming Language. At Chapter 8, there was a task to write a program that calculates the median and mode of a bunch of numbers. I originally skipped the task and kept reading but I’ve returned to it as I think it will give me some practice with the language. I’ve designed my solution as a library crate that provides a function pub fn median_and_mode<T: Ord + Eq + Hash + Clone>(values: &mut [T]) -> Option<MedianAndMode<T>>.
The directory structure is as follows:
src
├── common.rs
├── lib.rs
├── select_and_iterate
│ └── test.rs
├── select_and_iterate.rs
└── test.rs
I took a hopefully more efficient approach to the task than sorting the list, by using the median of medians algorithm and quickselect, which I largely copied from Wikipedia, but slightly modified to also count each element. To do this I used a point in the algorithm where it already looped over every element. However, I’m unsure of if my use of a closure to do this might slow things down, as later iterations are passed a noop closure, which might slow things down a bit.
I used the proptest crate to create property-based tests for my code.
Here are the source files from my project:
lib.rs
mod common;
mod select_and_iterate;
#[cfg(test)]
mod test;
use std::{
collections::{HashMap, HashSet},
hash::Hash,
};
use crate::{common::noop, select_and_iterate::select_and_iterate};
#[derive(Debug, PartialEq, Eq)]
pub enum Median<T> {
At(T),
Between(T, T),
}
#[derive(Debug, PartialEq, Eq)]
pub struct Mode<T: Eq + Hash>(HashSet<T>);
#[derive(Debug, PartialEq, Eq)]
pub struct MedianAndMode<T: Eq + Hash> {
pub median: Median<T>,
pub mode: Mode<T>,
} | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
pub fn median_and_mode<T: Ord + Eq + Hash + Clone>(values: &mut [T]) -> Option<MedianAndMode<T>> {
let len = values.len();
if len == 0 {
return None;
}
let mut frequencies = HashMap::new();
let action = |x: &T| {
let frequency = frequencies.entry((*x).clone()).or_insert(0);
*frequency += 1;
};
let median;
if len % 2 == 1 {
let middle = len / 2;
let Some(median_index) = select_and_iterate(values, middle, action)
else { return None; };
median = Median::At(values[median_index].clone());
} else {
let middle_1 = len / 2 - 1;
let middle_2 = len / 2;
let Some(median_1_index) = select_and_iterate(values, middle_1, action)
else { return None; };
let median_1 = values[median_1_index].clone();
let Some(median_2_index) = select_and_iterate(values, middle_2, noop)
else { panic!() };
let median_2 = values[median_2_index].clone();
if median_1 == median_2 {
median = Median::At(median_1);
} else {
median = Median::Between(median_1, median_2);
}
}
let mode = Mode(get_mode(frequencies));
Some(MedianAndMode { median, mode })
}
fn get_mode<T: Eq + Hash>(frequencies: HashMap<T, usize>) -> HashSet<T> {
let mut modes = HashSet::new();
let mut highest_frequency = 0;
for (value, frequency) in frequencies {
match frequency.cmp(&highest_frequency) {
std::cmp::Ordering::Less => {}
std::cmp::Ordering::Equal => {
modes.insert(value);
}
std::cmp::Ordering::Greater => {
highest_frequency = frequency;
modes.clear();
modes.insert(value);
}
}
}
modes
}
select_and_iterate.rs
#[cfg(test)]
mod test;
use std::cmp::{min, Ordering};
use crate::common::noop; | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
use std::cmp::{min, Ordering};
use crate::common::noop;
// Algorithm stolen wholesale from Wikipedia: https://en.wikipedia.org/wiki/Median_of_medians
pub fn select_and_iterate<T: Ord + Clone>(
values: &mut [T],
index: usize,
action: impl FnMut(&T),
) -> Option<usize> {
let len = values.len();
if len == 0 || index > len {
return None;
}
Some(select_and_iterate_inner(values, index, action))
}
fn select_and_iterate_inner<T: Ord + Clone>(
values: &mut [T],
index: usize,
mut action: impl FnMut(&T),
) -> usize {
let len = values.len();
debug_assert_ne!(len, 0);
if len == 1 {
debug_assert_eq!(index, 0);
action(&values[0]);
return 0;
}
let pivot_index = pivot(values);
let pivot_index = partition(values, pivot_index, index, action);
match index.cmp(&pivot_index) {
Ordering::Less => select_and_iterate_inner(&mut values[0..pivot_index], index, noop),
Ordering::Equal => pivot_index,
Ordering::Greater => {
select_and_iterate_inner(
&mut values[pivot_index + 1..len],
index - (pivot_index + 1),
noop,
) + (pivot_index + 1)
}
}
}
fn pivot<T: Ord + Clone>(values: &mut [T]) -> usize {
let len = values.len();
if len <= 5 {
return median_of_5(values);
}
for i in (0..len - 1).step_by(5) {
let right_index = min(i + 4, len - 1);
let median = median_of_5(&mut values[i..right_index]);
values.swap(median, i / 5);
}
select_and_iterate_inner(&mut values[0..len / 5], (len - 1) / 10, noop)
}
fn median_of_5<T: Ord>(values: &mut [T]) -> usize {
values.sort();
(values.len() - 1) / 2
} | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
fn median_of_5<T: Ord>(values: &mut [T]) -> usize {
values.sort();
(values.len() - 1) / 2
}
fn partition<T: Ord + Clone>(
values: &mut [T],
pivot_index: usize,
target_index: usize,
mut action: impl FnMut(&T),
) -> usize {
let len = values.len();
let pivot_value_ref = &values[pivot_index];
action(pivot_value_ref);
let pivot_value = pivot_value_ref.clone();
values.swap(pivot_index, len - 1);
let mut store_index = 0;
for i in 0..len - 1 {
action(&values[i]);
if values[i] < pivot_value {
values.swap(store_index, i);
store_index += 1;
}
}
let mut store_index_eq = store_index;
for i in store_index..len - 1 {
if values[i] == pivot_value {
values.swap(store_index_eq, i);
store_index_eq += 1;
}
}
values.swap(len - 1, store_index_eq);
if target_index < store_index {
store_index
} else if target_index <= store_index_eq {
target_index
} else {
store_index_eq
}
}
common.rs
pub fn noop<T>(_: &T) {}
test.rs
use super::{median_and_mode, Median, MedianAndMode, Mode};
use proptest::{collection::vec, prop_assert, prop_assert_eq, prop_assert_ne, proptest};
use std::collections::HashSet;
// See https://github.com/proptest-rs/proptest/issues/256 | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
#[test]
fn test_median_and_mode_empty_array() {
let mut values: [i128; 0] = [];
let None = median_and_mode(&mut values)
else { panic!("Wrong result pattern") };
}
#[test]
fn test_median_and_mode_1() {
let mut values: [i128; 12] = [
30050, 17767, 12534, -24364, 20538, -17, 690, -7966, -40, -1172, -25598, 34,
];
let Some(MedianAndMode { median, mode }) = median_and_mode(&mut values)
else { panic!() };
assert_eq!(median, Median::Between(-17, 34));
assert_eq!(mode, Mode(HashSet::from_iter(values.iter().copied())))
}
#[test]
fn test_median_and_mode_2() {
let mut values: [i128; 9] = [
7952,
19412,
-1450,
6978825196251534519,
11125,
5270098434161345047,
-13739,
-27060,
-467,
];
let Some(MedianAndMode { median, mode }) = median_and_mode(&mut values)
else { panic!("Wrong result pattern") };
assert_eq!(median, Median::At(7952));
assert_eq!(mode, Mode(HashSet::from_iter(values.iter().copied())));
} | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
proptest! {
#[test]
fn proptest_median_and_mode(mut values in vec(i8::MIN..i8::MAX, 1..32768)) {
let len = values.len();
if len == 0 {
let None = median_and_mode(&mut values)
else { panic!("Wrong result pattern") };
} else {
let Some(MedianAndMode { median, mode }) = median_and_mode(&mut values)
else { panic!("Wrong result pattern") };
values.sort();
match median {
Median::At(x) => {
prop_assert_eq!(x, values[len / 2]);
},
Median::Between(x, y) => {
prop_assert_eq!(x, values[len / 2 - 1]);
prop_assert_eq!(y, values[len / 2]);
},
}
let Mode(mode) = mode;
prop_assert_ne!(mode.len(), 0);
let mut frequencies = Vec::new();
for value in mode {
frequencies.push(values.iter().filter(|n| **n == value).count())
};
let first_frequency = frequencies[0];
prop_assert!(first_frequency <= len);
prop_assert!(frequencies.iter().all(|n| *n == first_frequency));
}
}
#[test]
fn proptest_median_and_mode_singleton_vec(value in i128::MIN..i128::MAX) {
let mut values = vec![value];
let Some(MedianAndMode { median, mode }) = median_and_mode(&mut values)
else { panic!("Wrong result pattern") };
prop_assert_eq!(median, Median::At(value));
prop_assert_eq!(mode, Mode(HashSet::from([value])))
}
}
select_and_iterate/test.rs
use super::select_and_iterate;
use crate::common::noop;
use proptest::{collection::vec, prop_assert, prop_assert_eq, proptest};
use std::collections::HashMap;
#[test]
fn test_select_empty_vec() {
let mut values: Vec<i128> = vec![];
let None = select_and_iterate(&mut values, 0, noop)
else { panic!("Wrong result pattern") };
} | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
proptest! {
#[test]
fn proptest_select(mut values in vec(i8::MIN..i8::MAX, 1..32768), index in 0..usize::MAX) {
let len = values.len();
if len == 0 {
let None = select_and_iterate(&mut values, index, noop)
else { panic!("Wrong result pattern") };
} else {
let index = index % len;
let mut frequencies = HashMap::new();
let action = |x: &i8| {
let frequency = frequencies.entry(*x).or_insert(0);
*frequency += 1;
};
let Some(value_index) = select_and_iterate(&mut values, index, action)
else { panic!() };
let value = values[value_index];
values.sort();
prop_assert_eq!(value, values[index]);
for (value, frequency) in frequencies {
prop_assert!(values.contains(&value));
prop_assert!(frequency <= len);
}
}
}
#[test]
fn proptest_select_singleton_vec(value in i128::MIN..i128::MAX) {
let mut counter = 0;
let action = |_: &i128| {
counter += 1;
};
let mut values = vec![value];
let Some(0) = select_and_iterate(&mut values, 0, action)
else { panic!("Wrong result pattern") };
prop_assert_eq!(counter, 1);
}
}
Questions
In particular, I’m interested in these questions: | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
Questions
In particular, I’m interested in these questions:
Is this code actually notably faster than the sorting method? In my tests it seemed to perform O(n), as Wikipedia suggested
Does the use of a closure and passing noop to later iterations slow down the code notably?
Is the structure and organization of the code sensible?
Is the Clone requirement for median_and_mode sensible? I ran into issues with the borrow checker, which I still don’t fully understand, and used Clone, but I’m not sure if it’s a sensible requirement
Is the Clone requirement for select_and_iterate sensible? It comes from the call to clone in pivot, where I assume it’s because the compiler must assume that the mutable borrow in swap might result in a dangling pointer. Would this be a good place to use unsafe? Or is there some hack I’m not aware of that might circumvent this need? I assume it’s not that big of a deal as any other use of the same code could just pass references to be compared
Answer: The code looks good overall, it's well-organized, and easily readable. A pleasure to review.
Separation of concerns
While the exercise does suggest computing the median and the mode, I do not think it expects you to compute both in a single function. Unlike a minmax function, there's little to no synergy between the two.
As such, I would suggest splitting the two calculations.
Relatedly, the MedianAndMode struct is overkill, since you already designed two strong types (Median and Mode) a simple tuple would have been enough. And with the split function, Mode becomes overkill too.
Separation of concerns (2)
By splitting the top-level function, you can also split the select_and_iterate to be just select.
This removes the use of the closure.
Expression, Expression, Expression
Rust is an Expression-Oriented language, almost everything is an expression!
For example, in your calculation of the median you write:
let median;
if ... {
...
median = <a>;
} else {
...
median = <b>;
} | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
Which is statement oriented.
But in Rust, { ... } is an expression (returning the value of the expression after the last ;) and if ... { ... } else { ... } is also an expression!
Thus, idiomatically it would be:
let median = if ... {
...
<a>
} else {
...
<b>
};
It's shorter, to boot.
Impossible code-paths
Your code contains impossible code-path in the median calculation.
The only reason for select_and_iterate to return None are an empty slice and an erroneous index, neither of which should ever occur in the calls from median_and_mode.
It's distracting to have those impossible code-paths, so it may be worth spending a bit of time trying to see if there's a sensible way to express the inputs of select_and_iterate so as to avoid them.
(I am afraid I can't think of any, off the top of my hat)
Answers
Is this code actually notably faster than the sorting method? In my tests it seemed to perform O(n), as Wikipedia suggested
I'll trust Wikipedia on this one.
Does the use of a closure and passing noop to later iterations slow down the code notably?
It's not optimal.
Rust uses monomorphization, it's a fancy term to say that each generic function is "copy/pasted" for each unique set of generic parameters, and optimized separately.
Thus, calling select_and_iterate with action or noop is, each time, maximally efficient. There is, however, a slight inefficiency in calling both: each one is a specifically different block of code. And a complex one at that. Expect more cache misses, decoding stalls, etc... It won't be noticeable on large inputs, but it will be on short ones.
Is the structure and organization of the code sensible? | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
Is the structure and organization of the code sensible?
Yes.
I wouldn't bother splitting the tests in their own separate files unless they get really big, however, as that's a lot of ceremonial, and many folders (at scale), I typically just shove them at the bottom of the file.
And if the file gets really big due to lots of tests, I'll split the "production" code in it into several files, and split the tests to match.
Is the Clone requirement for median_and_mode sensible? I ran into issues with the borrow checker, which I still don’t fully understand, and used Clone, but I’m not sure if it’s a sensible requirement.
It's avoidable, but you'll have to structure the code differently.
First of all, you can't avoid it as long as you return copies. You could, instead, return indices or references.
However, to return indices or references, you must index into or refer to an immutable slice: if the elements are shuffled after the fact, suddenly you index or reference points to another element!
This naturally suggests how to play it:
First mutate the slice in order to compute the median.
Then memorize the median.
Then calculate the mode.
Return median and mode.
Is the Clone requirement for select_and_iterate sensible?
It's avoidable by using indexes instead of the element itself.
Doing so does open you to accidentally having the elements being shuffled under your feet, and your index suddenly referring to another element, which is a logical bug, but not a memory safety one, and thus which tests should be able to somewhat reliably detect.
I assume it’s not that big of a deal as any other use of the same code could just pass references to be compared.
It's possible to pass references but this requires an extra allocation for the Vec that will hold the references, so it's not great and it'd be better to remove the requirement if possible. | {
"domain": "codereview.stackexchange",
"id": 44342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
beginner, c, game, rock-paper-scissors
Title: Rock, Paper, Scissors game with CPU
Question: I have written the below shared code and wanted to ask for some optimization tips or even alternative (more elegant?) ways of solving the task at hand (maybe without gotos?). My code, even if 'crude', should work properly.
The exercise basically asks me to recreate a Rock, Paper, Scissors game with the CPU (randomizing the CPU's moves) and to print a summary of our interaction.
//Rock, Paper, Scissors
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//Variables Definition
int user_choice, computer_choice, rematch = 0; //Normal Variables
int games_number = 0, games_played = 0, user_wins = 0, computer_wins = 0, even_games = 0; //Counters
start:
//User Interface
printf("How many matches (to the best of 1) would you like to play?\n");
scanf("%d", &games_number);
//Input Management
if(games_number >= 1){
for(int i = 0; i < games_number; ++i){ //For cycle (match) beginning
srand(time(NULL)); //Computer choice randomization
games_played += 1; //Matches played counter increment
//Request of chosen move
printf("\nChoose your own move:\n1 = Rock\n2 = Paper\n3 = Scissors\n\n");
scanf("%d", &user_choice);
//Invalid input case
if(user_choice <= 0 || user_choice >= 4){
printf("\nYou have chosen an invalid move!\n(An invalid number was inserted)\n");
goto end;
}
//Computer move simulation
computer_choice = 1 + rand() % 3;
printf("(Computer's choice': %d)\n", computer_choice); //printf not required | {
"domain": "codereview.stackexchange",
"id": 44343,
"lm_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, game, rock-paper-scissors",
"url": null
} |
beginner, c, game, rock-paper-scissors
//Results computation
if(user_choice == computer_choice){ //user == pc
printf("\nYou are even!\n");
even_games += 1;
}else if(user_choice == 1 && computer_choice == 2){ //user: rock | pc: paper
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}else if(user_choice == 1 && computer_choice == 3){ //user: rock | pc: scissors
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 2 && computer_choice == 1){ //user: paper | pc: rock
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}else if(user_choice == 2 && computer_choice == 3){ //user: paper | pc: scissors
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 3 && computer_choice == 1){ //user: scissors | pc: rock
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else if(user_choice == 3 && computer_choice == 2){ //user: scissors | pc: paper
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}
}//for cycle (match) end
end:
//Rematch request
printf("\nDo you want to play again?\nYes: 1 || No: other\n");
scanf("%d", &rematch);
if(rematch == 1){
puts("");
goto start;
}
//Print summary
printf("\n| %s | %s | %s | %s |\n", "Matches Played", "User Victories", "Computer Victories", "Even Matches");
printf("| %14d | %14d | %17d | %12d |\n", games_played, user_wins, computer_wins, even_games);
}else{ //if (games_number >= 1) end
printf("\nAlright, go play something else then :'(\n");
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44343,
"lm_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, game, rock-paper-scissors",
"url": null
} |
beginner, c, game, rock-paper-scissors
return 0;
}
Answer:
move the srand to the top, no reason to call it multiple times
Get rid of the goto and instead rely an outer while loop and inner for loop (which you already have).
First loop is an endless loop while(1) that asks how many matches, if <=0 then exit the loop break. Add games_played to games_number so that if you finish one round and play again the count is total not just the last round
Next loop is for, this is the main loop
In the main loop after asking for input if it's invalid restart the loop with continue and decrement i so player plays the correct number of rounds
You could make the output of the computer choice more readable by adding a list of actions char actions[3][8]={"rock","paper","scissors"} and then output the corresponding action instead of the number printf("(Computer's choice': %s)\n", actions[computer_choice-1]);
I'd consolidate the win/lose/even into 3 if/else, if there is a tie, else if the computer wins, or if the player wins
increment games played last after playing, not at the beginning
If the player chooses not to replay you can exit with break in the outer loop
Print the stats if games_played > 0 (also minor spacing issue should be 18 not 17)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//Variables Definition
char actions[3][8]={"rock","paper","scissors"};
int user_choice, computer_choice, rematch = 0; //Normal Variables
int games_number = 0, games_played = 0, user_wins = 0, computer_wins = 0, even_games = 0; //Counters
srand(time(NULL)); //Computer choice randomization | {
"domain": "codereview.stackexchange",
"id": 44343,
"lm_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, game, rock-paper-scissors",
"url": null
} |
beginner, c, game, rock-paper-scissors
while(1){
//User Interface
printf("How many matches (to the best of 1) would you like to play?\n");
scanf("%d", &games_number);
if(games_number<=0){
printf("\nAlright, go play something else then :'(\n");
break;
}
for(int i = 0; i < games_number; ++i){
printf("Choose your own move:\n1 = Rock\n2 = Paper\n3 = Scissors\n\n");
scanf("%d", &user_choice);
//Invalid input case
if(user_choice <= 0 || user_choice >= 4){
printf("\nYou have chosen an invalid move!\n(An invalid number was inserted)\n");
i -= 1; // because you are asking user input again but don't want to increment round
continue;
}
computer_choice = 1 + rand() % 3;
printf("(Computer's choice': %s)\n", actions[computer_choice-1]);
if(user_choice == computer_choice){ //user == pc
printf("\nYou are even!\n");
even_games += 1;
} else if((user_choice < computer_choice)||
(user_choice == 3 && computer_choice == 1)){
printf("\nThe user has lost :(\n");
computer_wins += 1;
}else{
printf("\nThe user has won, congratulations!\n");
user_wins += 1;
}
games_played += 1;
}
printf("\nDo you want to play again?\n 1: Yes || Other: No\n");
scanf("%d", &rematch);
if(rematch != 1){
break;
}
}
if (games_played>0){
//Print summary
printf("\n| %s | %s | %s | %s |\n", "Matches Played", "User Victories", "Computer Victories", "Even Matches");
printf("| %14d | %14d | %18d | %12d |\n", games_played, user_wins, computer_wins, even_games);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44343,
"lm_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, game, rock-paper-scissors",
"url": null
} |
python
Title: Python function receive a str and return table
Question: Input: "Uno dos tres cuatro cinco"
Output: {"": ["Uno"], "Uno": ["dos"], "dos": ["tres"], "tres": ["cuatro"], "cuatro": ["cinco"]}
I created a function, that received 1 string argument. Function devide str to list and then to dict. First element in dictionary need to look like {"":null_index_in_the_string}.
Function:
def mimic_dict(str):
lst = str.split()
prev = ""
hash_table = {}
for elem in lst:
hash_table.setdefault(prev, []).append(elem)
prev = elem
return hash_table
Test:
def test():
lst = ["Uno dos tres cuatro cinco", "Uno dos\tdos\nsinco", "a cat and a dog a fly"]
check = ["{'': ['Uno'], 'Uno': ['dos'], 'dos': ['tres'], 'tres': ['cuatro'], 'cuatro': ['cinco']}", "{'': ['a'], 'a': ['cat', 'dog', 'fly'], 'cat': ['and'], 'and': ['a'], 'dog': ['a']}"]
res_bool, res_check = [], list(map(mimic_dict, lst))
res_check = list(map(str, res_check))
for elem in check:
if elem in res_check:
res_bool.append(True)
return res_bool | {
"domain": "codereview.stackexchange",
"id": 44344,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Answer: Your function name is not very helpful. Why is the function called
mimic_dict()? Perhaps the answer to that question is clear in the context of
your larger project. In any case, the reason is not evident to me, so I suggest
you put some effort into creating a better name. In the function's doc-string,
I attempt to describe the function's general behavior.
When feasible, use specific names rather than generic names. Your code uses
mostly generic names, such as str, lst, elem. But more specific names are
readily available: text, words, and curr. Notice in particular how much
better curr is than the bland elem. The latter tells us nearly nothing, but
curr emphasizes the contrast with prev and also ties into the function's
doc-string.
def mimic_dict(text):
'''
Takes some text, splits it into words, and returns a dict
where each previous word is the key for the current word (stored
in a list to accommodate duplicates).
'''
words = text.split()
prev = ''
d = {}
for curr in words:
d.setdefault(prev, []).append(curr)
prev = curr
return d | {
"domain": "codereview.stackexchange",
"id": 44344,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
When testing, don't stringify expected data. It's good that your question
includes some test code. However, your tests are a bit awkward because you
stringify the expected results. That's unnecessary. Just check for equality
against the expected dict.
Unify test data, linking input to expected output. As noted in a comment,
there was a mismatch between your number of test cases and expected outputs.
You can avoid such problems by unifying the test data from the outset, as shown
below.
def test_mimic_dict():
# Each test input is linked directly to expected output.
checks = [
(
"Uno dos tres cuatro cinco",
{'': ['Uno'], 'Uno': ['dos'], 'dos': ['tres'], 'tres': ['cuatro'], 'cuatro': ['cinco']},
),
(
"a cat and a dog a fly",
{'': ['a'], 'a': ['cat', 'dog', 'fly'], 'cat': ['and'], 'and': ['a'], 'dog': ['a']},
),
(
"Uno dos\tdos\nsinco",
{'': ['Uno'], 'Uno': ['dos'], 'dos': ['dos', 'sinco']},
),
]
for inp, exp in checks:
got = mimic_dict(inp)
if got == exp:
print('ok')
else:
print(got)
print(exp)
An alternative implementation using itertools.pairwise. Your current
approach is fine, but here's a different way to do it. You could
also use a collections.defaultdict rather than dict.setdefault.
from itertools import pairwise, chain
def mimic_dict(text):
d = {}
for prev, curr in pairwise(chain([''], text.split())):
d.setdefault(prev, []).append(curr)
return d | {
"domain": "codereview.stackexchange",
"id": 44344,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c#, performance, beginner
Title: Brute-force Integer Diophantine equations solver
Question: I want to improve the performance of my equation solver
So I have an expression:- 42a + 75b - 30c + 80d + 25e + 50f, let's call it D.
Variables a, b, c, d, e, f are positive integers with values from 0 to 150.
I need to find and filter solutions to D = -(v + 1) equation for each v, where v is an integer in the range from 0 to 3000. Solutions are filtered in a way where a variable is either 0 or at least 1. In other words, there are a total of 64 permutations for each v. I'm searching for the solution with the lowest a + b + c + d + e + f sum. Some permutations might not include any solutions, in which case it just returns Impossible.
This is more or less a typical Diophantine equation but I couldn't find a solver that would handle it. hackmath.net has a solver, but it doesn't take in more than 4 variables with constraints and also doesn't seem to have any API so that didn't help.
That's why I decided to make my own solver. Since I'm limiting a, b, c, d, e, f values making a brute-force algorithm didn't seem like such a bad idea, so I made one.
using System.Data;
const int c_maxVal = 150;
// valueSet[,] answerArray = new valueSet[3000 , 64];
// Lower size for testing
valueSet[,] answerArray = new valueSet[1 , 64];
for (int variation = 0; variation < answerArray.GetLength(0); variation++)
{
// FINDING SOLUTIONS
List<valueSet> results = new List<valueSet>();
Parallel.For(0, c_maxVal, a =>
{
for(int b = 0; b <= c_maxVal; b++)
{ | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
for (int c = 0; c <= c_maxVal; c++)
{
for (int d = 0; d <= c_maxVal; d++)
{
for (int e = 0; e <= c_maxVal; e++)
{
for (int f = 0; f <= c_maxVal; f++)
{
if (variation - 42 * a + 75 * b - 30 * c + 80 * d + 25 * e + 50 * f == -1)
{
lock (results)
{
results.Add(new() { _a = a, _b = b, _c = c, _d = d, _e = e, _f = f });
}
}
}
}
}
}
}
});
// FILTERING VALUES
for (int s = 0; s < answerArray.GetLength(1); s++)
{
BitArray bArr = new BitArray(new int[] { s });
bool[] bits = new bool[bArr.Length];
bArr.CopyTo(bits, 0);
int[] aRange = new int[] { bits[0] ? 1 : 0, bits[0] ? c_maxVal : 0 };
int[] bRange = new int[] { bits[1] ? 1 : 0, bits[1] ? c_maxVal : 0 };
int[] cRange = new int[] { bits[2] ? 1 : 0, bits[2] ? c_maxVal : 0 };
int[] dRange = new int[] { bits[3] ? 1 : 0, bits[3] ? c_maxVal : 0 };
int[] eRange = new int[] { bits[4] ? 1 : 0, bits[4] ? c_maxVal : 0 };
int[] fRange = new int[] { bits[5] ? 1 : 0, bits[5] ? c_maxVal : 0 };
List<valueSet> finalList = results.Where(set =>
set._a >= aRange[0] && set._a <= aRange[1] &&
set._b >= bRange[0] && set._b <= bRange[1] &&
set._c >= cRange[0] && set._c <= cRange[1] &&
set._d >= dRange[0] && set._d <= dRange[1] &&
set._e >= eRange[0] && set._e <= eRange[1] &&
set._f >= fRange[0] && set._f <= fRange[1]
).ToList();
valueSet finalSet = finalList.Find(set => set.count == finalList.Min(set => set.count)); | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
answerArray[variation, s] = finalSet;
}
}
// Console output for testing
Console.WriteLine();
for (int s = 0; s < answerArray.GetLength(1); s++)
{
Console.WriteLine($"Permutation #{s+1}");
Console.WriteLine(answerArray[0, s]);
}
struct valueSet
{
public int _a;
public int _b;
public int _c;
public int _d;
public int _e;
public int _f;
public int count { get { return _a + _b + _c + _d + _e + _f; } }
public override string ToString() => count > 0 ? $"a=[{_a}] b=[{_b}] c=[{_c}] d=[{_d}] e=[{_e}] f=[{_f}]" : "Impossible";
}
The main solution finder is what Parallel.For loop is for and I have no complaints about that (my CPU spikes up to 90% load when the loop is running, but otherwise it does it's job and it does it fast).
Filtering through all the solutions to find each permutation with the lowest variable sum is what's significantly slowing the program. My approach is to use a for loop and to convert it's iterator to a bit array on each step and then use each bit as a binary check for each variable. If the bit is set, then the range is from 1 to 100. If the bit is not set, then the range is from 0 to 0. My PC isn't that old, but it still takes a couple minutes to go through that search when testing just 1 variation (v from the prior explanation).
What I thought of doing:
Removing certain unnecessary permutations.
Some of the permutations will never have a solution. For example if only b is used, then the expression D can only have positive answers even though it's supposed to stay negative.
Is there any way to significantly improve the performance of my filtering algorithm?
A couple things to note before answering:
I know that b, e, f variables can substitute each other as they're all multiples of 25, but I still need them to be separate variables.
I plan on storing answerArray in a CSV file later and use it as a lookup table. | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
Answer: I'll let someone more familiar with the domain discuss better algorithms, so I'll just talk about easy, generally-applicable ideas.
The obvious place to start, is to find the minimal solution for each subset within the Parallel.For as part of the main loop: there's no need to record all the solutions (you only need to keep the small ones), and no need for the threads to talk until they've finished processing. You can maintain a bit-max for non-zero variables as you go, and use an array (just like answerArray) to keep track of the best solution found so far in the local thread, and aggregate the candidate solutions when the threads finish (e.g. can feed the data into a shared array as the last work of the thread, or accumulate all the results and aggregate them all that once).
This way, you remove the filtering stage, most of the inter-thread communication, and - depending on the problem - potentially a lot of unnecessary memory work.
Keeping track of the minimal solution also means you can filter out candidate solutions before trying them: there's no point evaluating a larger candidate solution if you already have a smaller one. If this proved effective at reducing runtime, then you could consider heuristics for changing the order in which you test solutions (e.g. try small candidates first); parallelise over the solution array, rather than values of a (so that different threads can't be looking the minimal solution for the same combination of variables; or reintroduce thread-communication so that they share a table of minimal solutions (can consider CAS or other methods to minimise thread contention).
Misc | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
The ToList on finalList is unnecessary and will probably just increase memory load, and you will be evaluating finalList.Min(set => set.count) for each execution of the outer lambda, which is completely unnecessary: instead, use an ArgMin function (if using .NET 7, you have MinBy in LINQ and can just wrap the whole in a try..catch to trap the error case): it'll be clearer and faster. Addressing this alone seems to provide a significant improvement: it takes the filtering from being quadratic in the number of solutions to linear in the number of solutions.
Rather than using Where to filter the masks for of the possible zero-nonzero variable combinations, you should group them somehow. The best thing to do would be to never put them into one list in the first place, but you could also just use GroupBy to do this, grouping by an integer mask rather than all the comparisons in your current code.
Note also that you are missing an obvious opportunity to parallelise the filtering.
Don't worry about your output format: you're not outputting a lot of data so you can afford to transform it later: choose data-structures that suit the data processing.
The loop over the last parameter is redundant: you can evaluate the last parameter directly (and then check that it's an integer)
valueSet doesn't obey typical .NET naming conventions: types and public members should be in ProperCamelCase
Refit (no filtering stage)
Simple refit based on paragraphs at the top performance (not touched valueSet or e.g. change the code to compute f directly):
public static valueSet[,] VM(int variations, int maxValue)
{
Console.WriteLine($"VM");
valueSet[,] answerArray = new valueSet[variations, 64];
for (int variation = 0; variation < answerArray.GetLength(0); variation++)
{
Parallel.For(0, maxValue, a =>
{
valueSet[] candidates = new valueSet[64];
int mask = a > 0 ? (1 << 0) : 0; | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
int mask = a > 0 ? (1 << 0) : 0;
mask &= ~0b111110;
for (int b = 0; b <= maxValue; b++)
{
mask &= ~0b111100;
for (int c = 0; c <= maxValue; c++)
{
mask &= ~0b111000;
for (int d = 0; d <= maxValue; d++)
{
mask &= ~0b110000;
for (int e = 0; e <= maxValue; e++)
{
mask &= ~0b100000;
for (int f = 0; f <= maxValue; f++)
{
if (variation - 42 * a + 75 * b - 30 * c + 80 * d + 25 * e + 50 * f == -1)
{
var s = new valueSet() { _a = a, _b = b, _c = c, _d = d, _e = e, _f = f };
var t = candidates[mask].count;
if (t == 0 || t > s.count)
{
candidates[mask] = s;
if (f > 0)
break;
}
}
mask |= (1 << 5);
}
mask |= (1 << 4);
}
mask |= (1 << 3);
}
mask |= (1 << 2);
}
mask |= (1 << 1);
}
lock (answerArray)
{
for (int i = 0; i < 64; i++)
{
var s = candidates[i];
var t = answerArray[variation, i].count;
if (s.count > 0 && (t == 0 || t > s.count))
answerArray[variation, i] = s;
}
}
});
} | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
return answerArray;
}
Ran on my machine in ~127s for maxVal = 100.
I really didn't put much effort into this, so it's not the nicest code ever, but should provide a clear example of how to do this without the explicit filtering stage and reduced opportunity for thread contention (though this clearly isn't a big deal, so possibly worth having a single array of solutions, so that they can 'share' the minimum solutions and further prune the search space, though I couldn't immediately get an improvement with some simple changes).
Faster Filtering
Lazily changing the filtering to use MinBy and try...catch helps a great deal; I've not de-duplicated the Where with e.g. a GroupBy because it makes more sense to note put them all entries with the same mask into one list in the first place, and I've not parallelised the code so that relative performance is more comparable with your original filtering code (parallelisation will help to get closer to the solution without filtering, as everything will be parallelised):
try
{
valueSet finalSet = results.Where(set =>
set._a >= aRange[0] && set._a <= aRange[1] &&
set._b >= bRange[0] && set._b <= bRange[1] &&
set._c >= cRange[0] && set._c <= cRange[1] &&
set._d >= dRange[0] && set._d <= dRange[1] &&
set._e >= eRange[0] && set._e <= eRange[1] &&
set._f >= fRange[0] && set._f <= fRange[1]
).MinBy(set => set.count);
answerArray[variation, s] = finalSet;
}
catch { } | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
c#, performance, beginner
answerArray[variation, s] = finalSet;
}
catch { }
Ran on my machine in ~182s for maxVal = 100.
I didn't let the original code run to completion for maxVal = 100, but it was running for about half an hour at least. It took 236s to run maxVal = 60 (compared to 7s for the filterless refit and 12s for the faster filtering) (I guess my CPU is slower than yours!)
Solving for all variations
The filter-free method lends itself to a modification to find solutions for a large number of variations, by computing the variation that is satisfied by each candidate solution. This answer is pretty long and intentionally focusses on the filtering per the OP, but an example of such a change in this regard can be found at https://gist.github.com/VisualMelon/71dab52a8657ac497724432207cde61a | {
"domain": "codereview.stackexchange",
"id": 44345,
"lm_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, beginner",
"url": null
} |
performance, rust, state-machine, lexical-analysis
Title: Rust state-machine lexer
Question: I tried implementing a lexer in rust that peeks ahead at the next character and makes a decision based on that.
However, i am told that this is bad practice, and instead i should be using finite-state-machines.
However, my implementation is slower than the original lexer, going from 1MB per 20ms to 1MB per 50ms to 1MB per 80 milliseconds running on debug mode.
Here is the code:
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum State {
Start,
Whitespace,
Comment,
Number,
Ident,
Slash,
LeftArrow,
RightArrow,
End,
NumberEnd,
IdentEnd,
Divide,
Less,
Greater,
LeftShift,
RightShift,
Equal,
LessOrEqual,
GreaterOrEqual,
}
const ADVANCE: &[bool] = &[
true, // Start
false, // Whitespace
false, // Comment
true, // Number
true, // Ident
true, // Slash
true, // LeftArrow
true, // RightArrow
false, // End
false, // NumberEnd
false, // IdentEnd
false, // Divide
false, // Less
false, // Greater
true, // LeftShift
true, // RightShift
true, // Equal
true, // LessOrEqual
true // GreaterOrEqual
]; | {
"domain": "codereview.stackexchange",
"id": 44346,
"lm_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, rust, state-machine, lexical-analysis",
"url": null
} |
performance, rust, state-machine, lexical-analysis
const TRANSITION: &[State] = &[
// Start Whitespace Comment Number Ident Slash LeftArrow RightArrow
State::Ident, State::Start, State::Comment, State::NumberEnd, State::Ident, State::Divide, State::Less, State::Greater, // Letter
State::Number, State::Start, State::Comment, State::Number, State::Ident, State::Divide, State::Less, State::Greater, // Number
State::Whitespace, State::Start, State::Comment, State::NumberEnd, State::IdentEnd, State::Divide, State::Less, State::Greater, // Whitespace
State::Whitespace, State::Start, State::Whitespace, State::NumberEnd, State::IdentEnd, State::Divide, State::Less, State::Greater, // Newline
State::Slash, State::Start, State::Comment, State::NumberEnd, State::IdentEnd, State::Comment, State::Less, State::Greater, // Slash
State::LeftArrow, State::Start, State::Comment, State::NumberEnd, State::IdentEnd, State::Divide, State::LeftShift, State::Greater, // LeftArrow
State::RightArrow, State::Start, State::Comment, State::NumberEnd, State::IdentEnd, State::Divide, State::Less, State::RightShift, // RightArrow
State::Equal, State::Start, State::Comment, State::NumberEnd, State::IdentEnd, State::Divide, State::LessOrEqual, State::GreaterOrEqual, // Equal
State::End, State::End, State::End, State::NumberEnd, State::IdentEnd, State::Divide, State::Less, State::Greater, // Eof
];
pub struct Cursor<'a> {
bytes: &'a [u8],
pub start_pos: usize,
pub pos: usize,
state: State
}
macro_rules! test {
($name:tt, $($code:tt)*) => {
{
let now = std::time::Instant::now();
$($code)*
println!("{}: {:?}", stringify!($name), now.elapsed());
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44346,
"lm_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, rust, state-machine, lexical-analysis",
"url": null
} |
performance, rust, state-machine, lexical-analysis
impl<'a> Cursor<'a> {
pub fn new(string: &'a str) -> Self {
Self {
bytes: string.as_bytes(),
start_pos: 0,
pos: 0,
state: State::Start
}
}
#[inline(always)]
fn advance(&mut self) -> usize {
let amount = if self.pos >= self.bytes.len() {
8
} else {
match self.bytes[self.pos] {
b'a'..=b'z' | b'A'..=b'Z' | 127.. => 0,
b'0'..=b'9' => 1,
b' ' | b'\t' | b'\r' => 2,
b'\n' => 3,
b'/' => 4,
b'<' => 5,
b'>' => 6,
b'=' => 7,
_ => todo!()
}
};
State::End as usize * amount
}
}
impl<'a> Iterator for Cursor<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.state = State::Start;
while self.state < State::End {
if self.state == State::Start { self.start_pos = self.pos; }
self.state = TRANSITION[self.advance() + self.state as usize];
if ADVANCE[self.state as usize] {
self.pos += self.bytes[self.pos].leading_ones().max(1) as usize;
}
}
if self.state == State::End {
None
} else {
Some(unsafe { std::str::from_utf8_unchecked(&self.bytes[self.start_pos..self.pos]) })
}
}
}
fn main() {
let code = "1 ".repeat(1_000_000);
let mut cursor: Cursor<'_> = Cursor::new(&code);
//test! { Next, cursor.advance(); };
test! {
Cursor,
while let Some(n) = cursor.next() {
//println!("{n:?} length {:?}", n.len());
}
};
} | {
"domain": "codereview.stackexchange",
"id": 44346,
"lm_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, rust, state-machine, lexical-analysis",
"url": null
} |
performance, rust, state-machine, lexical-analysis
Answer: As I understand it, (really fast parsing isn't my area), the idea behind lookup tables is to avoid branches and thus branch misprediction. So in order to make it really fast, you need to get rid of as many branches as possible in the parsing code.
You have a branch to decide whether to reset start_pos, a branch to decide whether to ADVANCE, as well as a match statement to classify the character class which possibly compiles to several branches.
It is probably worse than your previous attempt because the branch prediction worked better when you have different branches being tested in different parts of the lexer. Because this standardizes all the branches together, the branch predictor hasn't much of a hope.
But a more general issue is that if you want a really fast lexer built on a table like this, you probably don't want to build it by hand. You want to generate a lexer either using a crate like logos that builds a lexer for you or rolling your own generator. That way you can easily tweak the lexed language or the implementation strategy without completely rebuilding everything. | {
"domain": "codereview.stackexchange",
"id": 44346,
"lm_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, rust, state-machine, lexical-analysis",
"url": null
} |
beginner, c
Title: Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time
Question: Continuing to slowly progress through The C Programming Language by Brian Kernighan and Dennis Ritchie.
The code I came up with below is for Exercise 1-19 - Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.
Feedback is much appreciated.
// Exercise 1-19. Write a function reverse(s) that reverses the character string s.
// Use it to write a program that reverses its input a line at a time.
#include <stdio.h>
void reverseLine(char *s);
void reverseLine(char *s) {
int count;
count = 0;
for (int i = 0; s[i] != '\0'; i++) {
count++;
}
for (int j = count - 1; j >= 0; j--) {
putchar(s[j -1]);
}
putchar('\n');
}
int main() {
int ch, charCount;
char line[BUFSIZ];
charCount = 0;
while ((ch = getchar()) != EOF) {
if (charCount >= BUFSIZ - 1) {
fprintf(stderr, "Overly long line ignored.\n");
while ((ch = getchar()) != EOF && ch != '\n') {
;
}
line[charCount] = ch;
charCount = 0;
continue;
}
line[charCount++] = ch;
if (ch == '\n') {
line[charCount++] = '\0';
reverseLine(line);
charCount = 0;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44347,
"lm_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",
"url": null
} |
beginner, c
Answer: Your implementation is not what the exercise asked for. It asked for a function that reverses a string (implied: in-place), and separately, I/O to read and print lines using that function. What it did not ask for is a function that immediately prints the reverse of the string.
Your declaration of reverseLine is redundant so delete it; only the definition is needed.
In your current intepretation, s should be a const char *s since it isn't mutated, but again, the problem asks for in-place mutation.
Rather than ignoring long lines, just truncate them.
reverseLine should be static.
C allows for int main to omit the return, but that's a bad idea. Write the return.
In-predicate mutation, i.e. while ((ch = getchar()), is common but an anti-pattern. Do not mutate your variables on the inside of predicates.
reverseLine has re-implemented strlen. Don't do that; just call strlen. | {
"domain": "codereview.stackexchange",
"id": 44347,
"lm_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",
"url": null
} |
javascript, typescript
Title: Complex statement in typescript get?
Question: I have some get function like this
get customersAreNotValid(): boolean {
let customerIsValid = false;
if (this.customersOverview.mainCustomer) {
if (!this.customersOverview.mainCustomer.company) {
const { companyName, vatNumber, box, ...customer } = this.customersOverview.mainCustomer;
Object.values(customer).some(value => {
if (value === null || value === '') {
customerIsValid = true;
}
});
} else {
const { box, ...customer } = this.customersOverview.mainCustomer;
Object.values(customer).some(value => {
if (value === null || value === '') {
customerIsValid = true;
}
});
}
}
if (this.customersOverview.additionalCustomer) {
if (!this.customersOverview.additionalCustomer.company) {
const { companyName, vatNumber, box, ...customer } = this.customersOverview.additionalCustomer;
Object.values(customer).some(value => {
if (value === null || value === '') {
customerIsValid = true;
}
});
} else {
const { box, ...customer } = this.customersOverview.additionalCustomer;
Object.values(customer).some(value => {
if (value === null || value === '') {
customerIsValid = true;
}
});
}
}
return customerIsValid;
}
But I don't think that this is a good approach :( Any help about refactor?
Answer: Your code could be simplified to:
get customersAreNotValid(): boolean {
const customers = [
this.customersOverview.mainCustomer,
this.customersOverview.additionalCustomer,
]
return customers.some(oneCustomer => {
const { companyName, vatNumber, box, ...customer } = oneCustomer;
return Object.values(customer)
.some(value => value == null || value === '')
})
} | {
"domain": "codereview.stackexchange",
"id": 44348,
"lm_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, typescript",
"url": null
} |
javascript, typescript
return Object.values(customer)
.some(value => value == null || value === '')
})
}
And here's how it was done:
Object.values(customer).some(value => {
if (value === null || value === '') {
customerIsValid = true;
}
})
// to
customerIsValid = Object.values(customer).some(value => value == null || value === '')
You aren't really using array.some() properly. In your case, you're just using it to loop, but you're not really using how it checks if some values are what they say they are. array.some() already returns a boolean, you just need to assign that result to customerIsValid instead of manually doing it. Additional bonus: use == null to check for both undefined and null.
if (this.customersOverview.additionalCustomer) {
if (!this.customersOverview.additionalCustomer.company) {
// 1
} else {
// 2
}
}
// to
if (this.customersOverview.additionalCustomer) {
if (this.customersOverview.additionalCustomer.company) {
// 2
} else {
// 1
}
}
A minor nitpick, I recommend flipping conditionals so that it's all checking for truthiness instead of falsiness (as hinted by the presence of !). This way, it's easier to spot relationships that are really "and" and making it easier to collapse the condition to a condition1 && condition2 whenever possible. In this case, collapsing wasn't applied (the first level if doesn't have an else).
The same goes for methods and variables. Prefer positive-sided so that you don't have to do mind-bending is and is-not flipping in code.
const { companyName, vatNumber, box, ...customer } = this.customersOverview.additionalCustomer;
const { box, ...customer } = this.customersOverview.additionalCustomer;
// to
const { companyName, vatNumber, box, ...customer } = someCustomer | {
"domain": "codereview.stackexchange",
"id": 44348,
"lm_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, typescript",
"url": null
} |
javascript, typescript
// to
const { companyName, vatNumber, box, ...customer } = someCustomer
Destructuring can deal with first-level undefined properties. Seeing that mainCustomer is potentially a subset of additionalCustomer and that you only care about the ...customer, you can apply the same full destructure on mainCustomer. Both companyName and vatNumber are potentially undefined for mainCustomer, but that shouldn't matter because we don't care about them.
if (this.customersOverview.mainCustomer) {
if (!this.customersOverview.mainCustomer.company) {
} else {
}
}
if (this.customersOverview.additionalCustomer) {
if (!this.customersOverview.additionalCustomer.company) {
} else {
}
}
// to
const customers = [
this.customersOverview.mainCustomer,
this.customersOverview.additionalCustomer
]
const customerIsValid = customers.some(v => /* check properties of v */)
When you start repeating an operation, it's almost always a loop, an extra function, or both. So what I'd do first is find the few things that are different between the chunks of code, and extract them somewhere. Then, make the operation generic so that it accepts variable values in place of the values you extracted.
In your case, customerIsValid is true if either mainCustomer or additionalCustomer have some empty properties. This also shows another use for array.some().
get customersAreNotValid(): boolean {
Assuming mainCustomer and additionalCustomer are instances of subclasses of a base Customer class (and not just an interface to some plain object data), you could implement an isValid() method for it so that you can push off that responsibility to the customer object instead. That would simplify things for your cusotmersAreNotValid
get customersAreNotValid(): boolean {
const customers = [
this.customersOverview.mainCustomer,
this.customersOverview.additionalCustomer,
]
return customers.some(customer => !customer.isValid())
} | {
"domain": "codereview.stackexchange",
"id": 44348,
"lm_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, typescript",
"url": null
} |
c++, template, c++20
Title: Utility IOC Container
Question: This is an inversion-of-control object store. It is meant to be for a multithreaded application where it can load components at start-up based on complex environmental setup,
Worker threads can retrieve individual components on demand.
Do I need 2 overloaded functions of registerInstance()?
#include <iostream>
#include <vector>
#include <memory>
#include <ranges>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <iterator>
#include <any>
#include <typeindex>
#include <functional>
template <typename... Args>
concept NP = sizeof...(Args) == 1;
template <typename... Args>
concept PRS = sizeof...(Args) > 1;
class Factory
{
public:
template <PRS T, typename... Ps>
using Generator2 = std::function<std::unique_ptr<T>(Ps &&...arg)>;
template <NP T>
using Generator = std::function<std::unique_ptr<T>()>;
template <NP T>
void registerInstance(Generator<T> gen)
{
factoryMap_[typeid(T)] = gen;
}
template <PRS T>
void registerInstance(Generator2<T> gen)
{
factoryMap_[typeid(T)] = gen;
}
template <NP T>
std::unique_ptr<T> resolve()
{
auto it = factoryMap_.find(typeid(T));
try
{
return it == factoryMap_.end() ? nullptr : std::any_cast<Generator<T>>(it->second)();
}
catch (const std::bad_any_cast &o)
{
// logit
throw o;
}
}
static Factory &getInstance()
{
static Factory instance;
return instance;
}
private:
std::unordered_map<std::type_index, std::any> factoryMap_;
};
class DBOperations
{
public:
virtual ~DBOperations() = default;
virtual std::string handle() const
{
return "DB Opeation";
}
}; | {
"domain": "codereview.stackexchange",
"id": 44349,
"lm_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++, template, c++20",
"url": null
} |
c++, template, c++20
class NOSQLOperations
{
public:
virtual ~NOSQLOperations() = default;
NOSQLOperations(std::unique_ptr<DBOperations> &&obj) : compD_{std::move(obj)} {}
std::string handle() const
{
return compD_->handle() + "-NO SQL";
}
private:
std::unique_ptr<DBOperations> compD_;
};
class JsonParser
{
public:
JsonParser(std::unique_ptr<NOSQLOperations> &&obj) : compC_{std::move(obj)} {}
virtual ~JsonParser() = default;
std::string handle() const
{
return compC_->handle() + "-Json Parser";
}
private:
std::unique_ptr<NOSQLOperations> compC_;
};
class Handler
{
public:
virtual ~Handler() = default;
Handler(std::unique_ptr<JsonParser> &&obj) : compB_{std::move(obj)} {}
std::string handle() const
{
return compB_->handle() + "-Handler";
}
private:
std::unique_ptr<JsonParser> compB_;
};
void registerComponents()
{
auto &ioc = Factory::getInstance();
ioc.registerInstance<Handler>([&] { return std::make_unique<Handler>(ioc.resolve<JsonParser>()); });
ioc.registerInstance<JsonParser>([&] { return std::make_unique<JsonParser>(ioc.resolve<NOSQLOperations>()); });
ioc.registerInstance<NOSQLOperations>([&] { return std::make_unique<NOSQLOperations>(ioc.resolve<DBOperations>()); });
ioc.registerInstance<DBOperations>([&] { return std::make_unique<DBOperations>(); });
}
int main()
{
registerComponents(); // can be called at startup
auto &ioc = Factory::getInstance();
auto i = ioc.resolve<Handler>();
std::cout << i->handle() << '\n';
}
Answer: Naming things
What are NP and PRS abbreviations of? I don't have a clue. Especially for concepts I would choose clear names that express what the concepts mean.
Factory is a very generic name. A factory of what? What if you have a code base which needs more than one factory type? I would choose a more distinctive name for this class, even if it is never visible to any other source files.
It's not thread safe | {
"domain": "codereview.stackexchange",
"id": 44349,
"lm_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++, template, c++20",
"url": null
} |
c++, template, c++20
It is meant to be for a multithreaded application [...]
I don't see any mutexes or atomic operations in your code. Note that std::unique_ptr does not have anything to do with thread-safety.
No need for two overloads
Do I need 2 overloaded functions of registerInstance()?
No. Parameter packs can bind to zero or more arguments, so you don't need to make a special case for it. You can just write:
template <typename T, typename... Ps>
using Generator = std::function<std::unique_ptr<T>(Ps &&...arg)>;
template <typename T>
static void registerInstance(Generator<T> gen)
{
getInstance().factoryMap_[typeid(T)] = gen;
}
What about multiple instances of the same type?
What if you have some complicated scenario where you have two different databases? Maybe you have two different classes derived from DBOperations, or maybe just the same class but you have to pass a different database URI to the constructor? Consider:
registerInstance<DBOperations>([] {
return std::make_unique<MongoDBOperations>("example.com/db1");
});
registerInstance<DBOperations>([] {
return std::make_unique<CouchDBOperations>("example.com/db2");
});
This is a problem, because there is only place for one DBOperations in your factoryMap_. Also problematic is that the second call to registerInstance() will silently overwrite the previous one.
Do you need a registry at all?
The problem with your registry is that it is indexed based on types. Since types need to be known at compile time, there is not much point in having a run time map. The only thing you want is to be able to write code that uses a given object before it is defined. But you can declare variables before assigning values, so you can do:
template <typename T, typename... Ps>
using Generator = std::function<std::unique_ptr<T>(Ps &&...arg)>; | {
"domain": "codereview.stackexchange",
"id": 44349,
"lm_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++, template, c++20",
"url": null
} |
c++, template, c++20
Generator<Handler> handlerGenerator;
Generator<JsonParser> jsonParserGenerator;
Generator<NOSQLOperations> noSQLOperationsGenerator;
Generator<DBOperations> dbOperationsGenerator;
handlerGenerator = [&] { return std::make_unique<Handler>(jsonParserGenerator()); };
jsonParserGenerator = [&] { return std::make_unique<JsonParser>(noSQLOperationsGenerator()); };
noSQLOperationsGenerator = [&] { return std::make_unique<NOSQLOperations>(dbOperationsGenerator()); };
dbOperationsGenerator = [&] { return std::make_unique<DBOperations>(); };
auto handler = handlerGenerator();
std::cout << handler->handle() << '\n';
If you want to declare the instances in a header file that is included in multiple source files, you can make them inline.
Note that now you can easily declare two different generators of the same type. | {
"domain": "codereview.stackexchange",
"id": 44349,
"lm_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++, template, c++20",
"url": null
} |
c#, parsing, regex, comparative-review
Title: Parsing an email string
Question: My program needs to parse an e-mail string. There are two possibilities to enter an e-mail-address. Either with the alias or without one, plain the e-mail-address.
1st possibity:
string addressWithAlias = "test my address <bla@blub.com>";
2nd possibility:
string addressWithoutAlias = "bla@blub.com";
So, I wrote two functions:
private static string[] getAddressPartsRegex(string address)
{
string plainaddress = address.Trim();
Regex reg = new Regex(@"(.+?(?=<))<(.*@.*?)>");
var gr = reg.Match(plainaddress).Groups;
return gr.Count == 1
? new[] { plainaddress }
: new[] { gr[1].Value.Trim(), gr[2].Value.Trim() };
}
private static string[] getAddressParts(string address)
{
var splittedAdress = address.Split(' ');
return splittedAdress.Last().Trim().StartsWith("<")
? new[] { string.Join(" ", splittedAdress.Take(splittedAdress.Length - 1)), splittedAdress.Last().Trim(' ', '<', '>') }
: splittedAdress;
}
They both work fine and the results are the same. One uses regex, the other uses Split and Join.
What would you suggest to use, and why? What is the more beautiful function?
Are there any bugs I didn't see?
Answer: Consider taking advantage of existing features that could provide an additional layer of validation.
mainly System.Net.Mail.MailAddress
Also as mentioned in a comment, no need to be creating the regular expression every time the function is called.
static Regex mailExpression = new Regex(@"(.+?(?=<))<(.*@.*?)>");
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
var plainaddress = address.Trim();
var groups = mailExpression.Match(plainaddress).Groups; | {
"domain": "codereview.stackexchange",
"id": 44350,
"lm_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#, parsing, regex, comparative-review",
"url": null
} |
c#, parsing, regex, comparative-review
var plainaddress = address.Trim();
var groups = mailExpression.Match(plainaddress).Groups;
return groups.Count == 1
? new MailAddress(plainaddress)
: new MailAddress(groups[2].Value.Trim(), groups[1].Value.Trim());
}
According to reference source code, internally MailAddress will try to parse the address given to it.
This avoids having to roll your own parser as one already exists out of the box that has been tried, tested and is stable.
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
address = address.Trim();
return new MailAddress(address);
}
You have the added advantage of having a strongly typed object model to work with that will provide you with usable properties.
The following Unit Test demonstrates the desired behavior.
[TestClass]
public class EmailParserTest {
[TestMethod]
public void Should_Parse_EmailAddress_With_Alias() {
//Arrange
var expectedAlias = "test my address";
var expectedAddress = "bla@blub.com";
string addressWithAlias = "test my address <bla@blub.com>";
//Act
var mailAddressWithAlias = getAddress(addressWithAlias);
//Assert
mailAddressWithAlias
.Should()
.NotBeNull()
.And.Match<MailAddress>(_ => _.Address == expectedAddress && _.DisplayName == expectedAlias);
}
[TestMethod]
public void Should_Parse_EmailAddress_Without_Alias() {
//Arrange
var addressWithoutAlias = "bla@blub.com";
//Act
var mailAddressWithoutAlias = getAddress(addressWithoutAlias);
//Assert
mailAddressWithoutAlias
.Should()
.NotBeNull()
.And.Match<MailAddress>(_ => _.Address == addressWithoutAlias && _.DisplayName == string.Empty);
;
} | {
"domain": "codereview.stackexchange",
"id": 44350,
"lm_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#, parsing, regex, comparative-review",
"url": null
} |
c#, parsing, regex, comparative-review
private static MailAddress getAddress(string address) {
if (address == null) throw new ArgumentNullException("address");
if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException("invalid address", "address");
address = address.Trim();
return new MailAddress(address);
}
} | {
"domain": "codereview.stackexchange",
"id": 44350,
"lm_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#, parsing, regex, comparative-review",
"url": null
} |
c#, factory-method
Title: Web scraper for e-commerce sites Part II
Question: I asked the same question Web scraper for e-commerce sites yesterday and I'm now posting the revised code here.
I'm building web scraper application which takes name, code and price from few sites. I thought factory pattern would fit in my application. I would like to someone review my code and tell if I'm missing something.
I have class Item which holds scraped data.
public class Item
{
public string Code { get; set; }
public string Name { get; set; }
public string Price { get; set; }
}
An interfacem which has a method RunScrapingAsync with a list of item codes as the single parameter, which I need to scrape.
public interface IWebScraper
{
Task<List<Item>> RunScrapingAsync(List<string> itemCodes);
}
Then I have implementations for three scrapers (Amazon, EBay, AliExpress):
public class AmazonWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public AmazonWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://amazon.com");
}
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
}
public class EBayWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public EBayWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://ebay.com");
} | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
}
public class AliExpressWebScraper : IWebScraper
{
private static HttpClient client;
public List<string> ItemCodes { get; set; }
public AliExpressWebScraper()
{
client = new HttpClient(new HttpClientHandler() { Proxy = null });
client.BaseAddress = new Uri("https://aliexpress.com");
}
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes)
{
ConcurrentBag<Item> itemsConcurrentBag = new ConcurrentBag<Item>();
//for simplicity this logic is not important no need to go in details
return itemsConcurrentBag.ToList();
}
}
Here is my factory class WebScraperFactory:
public enum WebSite
{
Amazon,
EBay,
AliExpress
}
public class WebScraperFactory
{
public IWebScraper Create(WebSite website)
{
switch (website)
{
case WebSite.Amazon:
return new AmazonWebScraper();
case WebSite.EBay:
return new EBayWebScraper();
case WebSite.AliExpress:
return new AliExpressWebScraper();
default:
throw new NotImplementedException($"Not implemented create method in scraper factory for website {webSite}");
}
}
}
The WebScraper class, which holds all scrapers in a dictionary and uses them in the Execute method for the provided WebSite.
public class WebScraper
{
private readonly WebScraperFactory _webScraperFactory;
public WebScraper()
{
_webScraperFactory = new WebScraperFactory();
} | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
public WebScraper()
{
_webScraperFactory = new WebScraperFactory();
}
public async Task<List<Item>> Execute(WebSite webSite, List<string> itemCodes) =>
await _webScraperFactory.Create(webSite).RunScrapingAsync(itemCodes);
}
This is a WinForm app, so users have the option to run one or more scrapers (they are not all mandatory to run). So if a user chooses to run Amazon and AliExpress, it will choose two files with codes, adds them to the dictionary and calls the webscraper factory on every chosen website.
Example usage:
var codes = new Dictionary<WebSite, List<string>>
{
{WebSite.Amazon, amazonCodes},
{WebSite.AliExpress, aliExpressCodes}
}
var items = new Dictionary<WebSite, List<Item>>
{
{WebSite.Amazon, null},
{WebSite.AliExpress, null}
}
var webScraper = new WebScraper();
foreach(var webSite in websitesItemCodes.Keys)
{
items[webSite] = await webScraper.Execute(webSite, codes[webSite]);
}
Answer: IWebScraper
Based on the implementations it seems like you would gain more if you would define this interface as an abstract class to have a common place for the shared logic
public abstract class WebScraperBase
{
private readonly HttpClient client;
public WebScraperBase(Uri domain)
=> client = new HttpClient() { BaseAddress = domain };
public async Task<List<Item>> RunScrapingAsync(List<string> itemCodes, CancellationToken token = default)
{
ConcurrentBag<Item> itemsConcurrentBag = new();
await ScrapeAsync(itemCodes, itemsConcurrentBag, token);
return itemsConcurrentBag.ToList();
}
protected abstract Task ScrapeAsync(List<string> itemCodes, ConcurrentBag<Item> items, CancellationToken token);
}
I think the whole handler object is unnecessary: new HttpClientHandler() { Proxy = null }
I changed your RunScrapingAsync to be a template method | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
I've added a CancellationToken as a parameter to allow user cancellation/timeout
I also defined a ScrapeAsync method as a step method
I'm not sure why do have a class level List<string> property and a List<string> parameter as well
I've removed the former because based on the shared code fragment it was not in use
If it was in use inside the not shown part of the code under the RunScrapingAsync then please be aware that this property could be modified while the async method is running!!!!
XYZWebScraper
After the above changes the implementation of a given scraper could look like this
public class AliExpressWebScraper : WebScraperBase
{
public AliExpressWebScraper() : base(new Uri("https://aliexpress.com"))
{}
protected async override Task ScrapeAsync(List<string> itemCodes, ConcurrentBag<Item> items, CancellationToken token)
{
//for simplicity this logic is not important no need to go in
}
}
WebScraperFactory
If you could take advantage of switch expression then you can rewrite your Create like this
public static WebScraperBase Create(WebSite website)
=> website switch
{
WebSite.Amazon => new AmazonWebScraper(),
WebSite.EBay => new EBayWebScraper(),
WebSite.AliExpress => new AliExpressWebScraper(),
_ => throw new NotImplementedException($"Not implemented create method in scraper factory for website {webSite}"),
};
WebScraper
I do believe this whole class is unnecessary if you define the WebScraperFactory and its Create method as static (like above)
UPDATE #1
I completely overlooked that the client was defined as static inside the WebScraperBase. That implementation does not work so here are two alternatives:
Store the static HttpClient instances inside the WebScraperFactory and pass them to the ctor of the concrete scrapper instances | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
WebScraperFactory
private static Dictionary<WebSite, HttpClient> clients = new Dictionary<WebSite, HttpClient>
{
{ WebSite.Amazon, new HttpClient() { BaseAddress = new Uri("https://amazon.com") } },
{ WebSite.EBay, new HttpClient() { BaseAddress = new Uri("https://ebay.com") } },
{ WebSite.AliExpress, new HttpClient() { BaseAddress = new Uri("https://aliexpress.com") } }
};
public static WebScraperBase Create(WebSite website)
{
var client = clients.ContainsKey(website) ? clients[website] : throw new InvalidOperationException("...");
switch(website)
{
case WebSite.Amazon: return new AmazonWebScraper(client);
case WebSite.EBay: return new EBayWebScraper(client);
case WebSite.AliExpress: return new AliExpressWebScraper(client);
default: throw new NotImplementedException("...");
};
}
WebScraperBase
private readonly HttpClient client;
public WebScraperBase(HttpClient client)
=> this.client = client;
Use IHttpClientFactory to delegate the life cycle management of the underlying HttpClientHandlers to a dedicated component
Because you are using .NET Framework, not .NET Core you need to do the following workaround to be able to use IHttpClientFactory
WebScraperFactory
private static readonly IServiceProvider serviceProvider;
static WebScraperFactory()
{
var serviceCollection = new ServiceCollection().AddHttpClient();
serviceCollection.AddHttpClient(WebSite.Amazon.ToString(), c => c.BaseAddress = new Uri("https://amazon.com"));
serviceCollection.AddHttpClient(WebSite.EBay.ToString(), c => c.BaseAddress = new Uri("https://ebay.com"));
serviceCollection.AddHttpClient(WebSite.AliExpress.ToString(), c => c.BaseAddress = new Uri("https://aliexpress.com"));
serviceProvider = serviceCollection.BuildServiceProvider();
} | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
c#, factory-method
public static WebScraperBase Create(WebSite website)
{
var factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
var client = factory.CreateClient(website.ToString());
if(client.BaseAddress == null) throw new InvalidOperationException("...");
switch(website)
{
case WebSite.Amazon: return new AmazonWebScraper(client);
case WebSite.EBay: return new EBayWebScraper(client);
case WebSite.AliExpress: return new AliExpressWebScraper(client);
default: throw new NotImplementedException("...");
};
} | {
"domain": "codereview.stackexchange",
"id": 44351,
"lm_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#, factory-method",
"url": null
} |
beginner, c
Title: Write a Program Detab That Replaces Tabs in the Input with the Proper Number of Blanks to Space to the Next Tab Stop
Question: Continuing my K&R journey!
Please see below for my solution to:
Exercise 1-20: Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns.
#include <stdio.h>
#define TAB '\t' // character to look for
#define SPACE '-' // tab replacement char
#define TABSIZE 8 // fixed set of tab stops
#define MAXLINE 8000 // maximum number of chars in a line
static int getLine(char line[]);
static void processLine(char line[], int lineCharCount);
int main() {
int len; //length of line
char line[BUFSIZ]; //string constant array for appending ch
while ((len = getLine(line)) > 0) {
processLine(line, len);
}
return 0;
}
static int getLine(char line[]) {
int c;
int i;
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
line[i] = c;
}
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
static void processLine(char line[], int lineCharCount) {
int nonTabCount; // running count of characters up until \t is encountered
int i; // for loop
nonTabCount = 0;
for (i = 0; i < lineCharCount; i++) {
if (line[i] == TAB) {
nonTabCount++;
line[i] = SPACE;
putchar(line[i]);
while (TABSIZE - nonTabCount > 0) {
putchar(SPACE);
nonTabCount++;
}
nonTabCount = 0;
} else {
putchar(line[i]);
nonTabCount++;
if (nonTabCount >= TABSIZE) {
nonTabCount = 0;
}
}
}
}
Answer: Overall: Aside from bug, a very good post. | {
"domain": "codereview.stackexchange",
"id": 44352,
"lm_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",
"url": null
} |
beginner, c
Answer: Overall: Aside from bug, a very good post.
Nice layout & formatting
Good object names
Bug: Inconsistent size
With char line[BUFSIZ]; and C definition of "The value of the macro BUFSIZ shall be at least 256.", calling getLine(line) is a problem. getLine() assumes the buffer is MAXLINE or 8000.
Better to use the same. Even better, pass the size into getLine().
// static int getLine(char line[]) {
static size_t getLine(char line[], size_t size) {
I like size first to allow static code analysis with:
static size_t getLine(size_t size, char line[size]) {
In this case, best to initialize to handle tiny sizes.
// int c;
int c = 0;
Pedantic: string size
String size can exceed INT_MAX. Better to use size_t to express lineCharCount to handle all strings.
// processLine(char line[], int lineCharCount)
processLine(char line[], size_t lineCharCount)
Then use size_t i; in the function.
Simplify
Simpler and handles unsigned math well - no overflow.
// while (TABSIZE - nonTabCount > 0) {
while (TABSIZE > nonTabCount) { | {
"domain": "codereview.stackexchange",
"id": 44352,
"lm_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",
"url": null
} |
beginner, c
Printing
I'd print the processed line afterwards and avoid printing in processLine(). Of course that is tricky as the line grows.
Why change line[]?
processLine() has line[i] = SPACE;, but why change only 1 space? If anything the de-tabify process might add multiple spaces and that complicates things. Code instead could putchar(SPACE); and leave line[] unchanged.
If processLine() changed to leave char line[] unchanged, consider making that paramter const char line[].
String?
With processLine(char line[], int lineCharCount), I'd expect the function received a pointier to a string, in which case, the lineCharCount is not needed. Instead iterate until a null character is found.
Yet by passing lineCharCount does allow handling of a line of input with a null character that was read - an advance functionality.
Fixed tab size
"Assume a fixed set of tab stops, say every n columns." --> that sounds like n should be an option at program start to de-tabify at different values. Maybe that is for the next iteration of code.
Documentation
Coding goal deserves to be in the code as a comment.
Advanced: long line
When getLine() fills the buffer, yet the line is still not done, consider how one would re-work the function to convey that incomplete read to the caller and if the remainder of the line should remain unread.
Declare and initialize in one step
// int nonTabCount;
// nonTabCount = 0;
int nonTabCount = 0; | {
"domain": "codereview.stackexchange",
"id": 44352,
"lm_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",
"url": null
} |
python, performance, simulation, numerical-methods, physics
Title: Simulating a two-body collision problem to find digits of Pi
Question: I came across a nice video on 3Blue1Brown's channel that highlights a very indirect way to find the digits in Pi. I'd suggest watching the whole video, but briefly:
The setup is as above. A "small" body of unit mass is at rest on the left and a "large" body on the right is moving towards the left (the initial positions and velocities are irrelevant). Assuming perfectly elastic collisions and that the large body's mass to be the n-th power of 100, where n is a natural number, the total number of collisions is always floor(pi*(10n)).
The analytical reason for this is discussed here, but I've started learning a bit of Python and wanted to simulate this to improve my programming (i.e. I'm a beginner). Here's the code:
from fractions import Fraction
class Block:
# Creating a class since that helps keep track of attributes
def __init__(self, mass, velocity, position):
self.mass = mass
self.velocity = velocity
self.position = position
# Set initial conditions: the object on the left is at rest at x = 5 and has
# unit mass. The one on the right starts off at x = 10, with velocity =
# -5 units/s and has mass equal to 100^n, where n is user-specified.
# The number of collisions should be floor(Pi*10^n). e.g. n = 2 => 314,
# n = 3 => 3141, and so on
small = Block(1, 0, Fraction(32/10))
large = Block(100**int(input("Which power of 100 is the second mass? ")),
-7, Fraction(75,10))
# By "collision", we mean that either the position of both the objects is the
# same (both collide against each other) or the position of the small block is
# 0 (collision against wall)
def updateVelocities(collisions):
if(small.position == large.position != 0):
# Both blocks collide against each other
collisions += 1
temp = small.velocity | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
small.velocity = Fraction(((2*large.mass*large.velocity)+
(small.mass*small.velocity)-(large.mass*small.velocity)),
(small.mass + large.mass))
large.velocity = Fraction(((2*small.mass*temp)+(large.mass*large.velocity)
-(small.mass*large.velocity)),(small.mass + large.mass))
elif(small.position == 0 != large.position):
# The small block gets "reflected" off the wall
collisions += 1
small.velocity = -small.velocity
elif(small.position == large.position == 0):
# The rare instance in which both blocks move towards the wall and
# collide with the wall and against each other simultaneously
collisions += 2
small.velocity, large.velocity = -small.velocity, -large.velocity
else:
pass
return collisions
# Given the current positions and velocities, find the time to next collision
# This takes care of all different scenarios
def timeToNextCollision():
if(large.velocity >= small.velocity >= 0):
# Both blocks move towards right, but the large block is faster and the
# small block can't catch up
return float("inf")
elif(small.velocity >= 0 >= large.velocity):
# Both blocks are either moving towards each other, or one of the is at
# rest and the other is moving towards it. The wall is obviously ignored
# The condition small.velocity == 0 == large.velocity will also be ignored
# since if that's true, only the first if statement would be executed.
return Fraction(large.position - small.position,
small.velocity - large.velocity)
elif((large.velocity >= 0 and small.velocity < 0) or
(small.velocity <= large.velocity < 0)):
# Both blocks move towards left, but the large block can't catch up with
# the small block before the latter runs into the wall
return Fraction(-small.position, small.velocity) | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
elif(small.position == 0):
# Special case for when the small block is currently at the wall
if(large.velocity >= abs(small.velocity)):
# Small block can no longer catch up with large block
return float("inf")
else:
# Large block is either moving towards left or too slow moving towards
# the right. In either case, they will collide
return large.position/(abs(small.velocity) - large.velocity)
else:
# Both blocks move towards left, but large block is faster. If the
# distance between blocks is small enough compared to that between the wall
# and the small block, they will collide. Otherwise the small block will
# reach the wall before the large block has a chance to catch up
return min(Fraction(-small.position, small.velocity),
Fraction(large.position - small.position),
(small.velocity - large.velocity))
collisionCount = 0
while True:
t = timeToNextCollision()
if(t == float("inf")):
# No more collisions
break
# Update the distances to what they'll be during the next collision
small.position += small.velocity*t
large.position += large.velocity*t
# Update collision count AND velocities to post-collision values
collisionCount = updateVelocities(collisionCount)
print(collisionCount) | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
print(collisionCount)
The biggest headache was dealing with float's precision issues. For example, for a collision to register, the updated positions of the two blocks should exactly be the same. But with float's rounding issues, there would be a slight difference in the positions and the program would go haywire.
Even though this was corrected by using the Fraction data type, the run time of the program is really slow. If n=2, the program finishes within milliseconds, whereas for n=3, it takes a whopping 115 seconds. I'm not really aware of all the nuances of Python nor do I have any computer science knowledge, so I'd be really grateful if I can get some guidance on how I can improve the code.
Off the top of my head, perhaps using Fraction affects the run time, or I wrote the if conditions in a clumsy way, or wrote redundant code. I'm confused because there are many possibilities. In the first video I linked to, at around the 2:00 min mark, there's a simulation of collisions between 1 kg and 1003 kg, and it's so smooth and quick!
P.S. I used the Block class just to improve readability. I've tried using a simple list instead of a Block class object, but that only shaves off around 8 seconds or so. Not much improvement. I also tried using the numpy double data type - again, same rounding issues as with the default float type.
Answer: First, this is an awesome video! Upvoted for that reason alone. :)
If n=2, the program finishes within milliseconds, whereas for n=3, it takes a whopping 115 seconds. | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
If n=2, the program finishes within milliseconds, whereas for n=3, it takes a whopping 115 seconds.
Do you know about big-O notation? Just off the top of my head after watching that video: for n=2 you're computing the number of collisions for a 1kg block and a 100**2 = 10,000kg block, which we know from the video should be 314 collisions. For n=3 you're simulating 3141 collisions. That's 10 times as many collisions, simulated one at a time, so it should take 10 times as long. In general your program is going to take O(10n) steps to compute its result. So you shouldn't be surprised if it gets real slow real fast.
However, you're saying the difference between n=2 and n=3 is a factor of more than 100. That's surprising. I think you're right to blame Fraction — that is, you're dealing with much bigger numerators and denominators in the n=3 case, and bigger numbers naturally take more time to manipulate.
if(large.velocity >= small.velocity >= 0):
In general I like your use of chained comparisons... but why did you almost invariably put the biggest number on the left and the smallest on the right? That's backwards from how we usually write number lines.
And then sometimes you don't chain the comparison at all, for no reason I can detect:
elif((large.velocity >= 0 and small.velocity < 0) or
(small.velocity <= large.velocity < 0)):
I'd write this as
elif (small.velocity < 0 <= large.velocity) or (small.velocity <= large.velocity < 0):
Notice that you don't need parens around the condition of an if or elif in Python, and so it's not usual to write them.
return large.position/(abs(small.velocity) - large.velocity)
You didn't use Fraction here. Was that an oversight? Also, if this is a floating-point division, I might want to blame "repeated conversion from Fraction to floating-point and back" for some of your performance problems.
large = Block(100**int(input("Which power of 100 is the second mass? ")),
-7, Fraction(75,10)) | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
I strongly recommend moving the input onto its own source line. Mixing user input into the middle of an arithmetic expression is just asking for trouble. Plus, this lets you unambiguously name the n that you were trying to talk about in your question:
n = int(input("Which power of 100 is the second mass? "))
large = Block(100**n, -7, Fraction(75,10))
Actually, hang on; back up!
# Set initial conditions: the object on the left is at rest at x = 5 and has
# unit mass. The one on the right starts off at x = 10, with velocity =
# -5 units/s and has mass equal to 100^n, where n is user-specified.
# The number of collisions should be floor(Pi*10^n). e.g. n = 2 => 314,
# n = 3 => 3141, and so on
small = Block(1, 0, Fraction(32/10))
large = Block(100**int(input("Which power of 100 is the second mass? ")),
-7, Fraction(75,10))
That comment is ridiculously untrue! The object on the left is at rest at x = 3.2 (or x = 3 if you're in Python 2), and the object on the right starts off at x = 7.5 with velocity -7 units per second, not -5. So the comment is completely wrong. Besides, starting the big block with anything other than "velocity -1" is just wasting bits and CPU cycles. Who wants to multiply anything by 32/10 when you could be multiplying it by 1?
Also, all of that initial setup should be encapsulated into a __main__ block:
if __name__ == '__main__':
n = int(input("Which power of 100 is the second mass? "))
small = Block(1, 0, 1)
large = Block(100**n, -1, 2)
collisionCount = 0 | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
while True:
t = timeToNextCollision(small, large)
if t == float("inf"):
# No more collisions
break
# Update the distances to what they'll be during the next collision
small.position += small.velocity * t
large.position += large.velocity * t
# Update collision count AND velocities to post-collision values
collisionCount = updateVelocities(small, large, collisionCount)
print(collisionCount)
I changed your timeToNextCollision() to timeToNextCollision(small, large), passing the blocks to it as parameters, since it needs to look at the blocks in order to know what to do.
# Both blocks move towards left, but large block is faster. If the
# distance between blocks is small enough compared to that between the wall
# and the small block, they will collide. Otherwise the small block will
# reach the wall before the large block has a chance to catch up
return min(Fraction(-small.position, small.velocity),
Fraction(large.position - small.position),
(small.velocity - large.velocity))
I strongly recommend running your whole program through pylint or pyflakes and fixing all the style issues. Here specifically, I think it would benefit from the usual Python indentation style, which looks like this:
return min(
Fraction(-small.position, small.velocity),
Fraction(large.position - small.position),
(small.velocity - large.velocity)
)
This makes it very clear that you're taking the min of three things, not the usual two — and also you're constructing a Fraction from one argument, not the usual two. If this is intentional behavior, then the indentation is important because it communicates to your reader, "Hey, I know what I'm typing, don't worry" — and if this is unintentional behavior, then hey, you just found one of your bugs! | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
python, performance, simulation, numerical-methods, physics
Finally, let's fix your performance issue.
As I said, I assume that your program takes so long because you're manipulating gigantic numerators and denominators. Above about 2**64 (or maybe 2**32, I'm not sure), Python is going to switch from native integer representation to bignum representation, and get super slow. Reading the fractions docs tells me that there's a limit_denominator method that's used precisely to keep the numerator and denominator small. So let's use it!
while True:
t = timeToNextCollision(small, large)
if t == float("inf"):
# No more collisions
break
# Update the distances to what they'll be during the next collision
small.position += small.velocity * t
large.position += large.velocity * t
collisionCount = updateVelocities(collisionCount, small, large)
# Here's the new code!
small.position = small.position.limit_denominator(2**32)
large.position = large.position.limit_denominator(2**32)
small.velocity = small.velocity.limit_denominator(2**32)
large.velocity = large.velocity.limit_denominator(2**32)
With just this change (and the cleanups mentioned in this review, including fixing that bug that pyflakes would have found), I see your program taking the O(10n) that we expect it to:
$ time echo '2' | python x.py
Which power of 100 is the second mass? 314
real 0m0.240s
user 0m0.196s
sys 0m0.018s
$ time echo '3' | python x.py
Which power of 100 is the second mass? 3141
real 0m1.721s
user 0m1.697s
sys 0m0.015s
$ time echo '4' | python x.py
Which power of 100 is the second mass? 31415
real 0m22.497s
user 0m20.226s
sys 0m0.160s
Problem solved! | {
"domain": "codereview.stackexchange",
"id": 44353,
"lm_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, simulation, numerical-methods, physics",
"url": null
} |
html, css
Title: Piet Mondrian Painting with HTML & CSS
Question: a few weeks ago I started learning Flexbox and to practice my skills I did the following exercise:
Piet Mondrian was a 20th century Dutch painter whose paintings
emphasized simple geometric elements.
Inside a file called mondrian.html, create this Piet Mondrian painting (https://artmiamimagazine.com/wp-content/uploads/2019/02/Piet-Mondrian-d35kfou.jpg)
using HTML and flexbox.
If you're having trouble creating the whole thing, pick a "chunk" of
the painting and work on just that. Then pick another "chunk" and do
that, etc. How can you combine your chunks into a single image?
(think: HTML tree structure).
Some students have found printing the image and numbering each rectangle
helpful.
I would like to receive a review of the code. Is the use of the semantic tags correct? Is the code style right? What bad practices do I apply in the code? Have I overcomplicated myself? Is there a simpler and better way to solve the problem?
Code:
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.container {
display: flex;
border: 16px solid #292827;
height: 100vh;
}
.box_A,
.box_B {
flex: 1 0 auto;
}
.box_A {
border-right: 8px solid #292827;
}
.box_A > div,
.box_B > div {
height: 10%;
}
.row0,
.row1,
.row2,
.row3,
.row4,
.row5,
.row6,
.row7,
.row8,
.row9 {
display: flex;
}
.a1 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.a2 {
flex: 3 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.a3 {
flex: 2 0 auto;
background-color: #f9e217;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.b1 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.b1-bottom {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.b2 {
flex: 4 0 auto;
background-color: red;
box-shadow: -8px 0 0 0 #292827 inset;
}
.b3 {
flex: 2.5 0 auto;
background-color: #f9e217;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
.b3 {
flex: 2.5 0 auto;
background-color: #f9e217;
}
.b3-bottom {
flex: 2.5 0 auto;
background-color: #f9e217;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.c1 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.c2 {
flex: 4 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
background-color: red;
}
.c2-bottom {
flex: 4 0 auto;
background-color: red;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.c3 {
flex: 1.25 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.c3-bottom {
flex: 1.25 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.c4 {
flex: 1.25 0 auto;
}
.c4-bottom {
flex: 1.25 0 auto;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.d1 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.d2 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px 0 0 0 #292827 inset;
}
.d3 {
flex: 2 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.d4 {
flex: 2.5 0 auto;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.e1 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px 0 0 0 #292827 inset;
}
.e2 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.e3 {
flex: 2 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.e4 {
flex: 2.5 0 auto;
background-color: #0c7bbc;
}
.f1 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px 0 0 0 #292827 inset;
}
.f2 {
flex: 2 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.f3 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.f4 {
flex: 2.5 0 auto;
background-color: #0c7bbc;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.g1 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.g2 {
flex: 2 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.g3 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px 0 0 0 #292827 inset;
}
.g4 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
.g4 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.g5 {
flex: 2.5 0 auto;
background-color: red;
}
.h1 {
flex: 3 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.h2 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px 0 0 0 #292827 inset;
}
.h3 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.h4 {
flex: 2.5 0 auto;
background-color: red;
}
.i1 {
flex: 2 0 auto;
background-color: #0c7bbc;
box-shadow: -8px 0 0 0 #292827 inset;
}
.i2 {
flex: 0.5 0 auto;
background-color: #f9e217;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.i3 {
flex: 0.5 0 auto;
background-color: black;
box-shadow: -8px 0 0 0 #292827 inset;
}
.i4 {
flex: 3 0 auto;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.j1 {
flex: 2 0 auto;
background-color: #0c7bbc;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.j2 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.j3 {
flex: 2 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.j4 {
flex: 1 0 auto;
background-color: #f9e217;
}
.k1 {
flex: 2 0 auto;
background-color: red;
box-shadow: -8px 0 0 0 #292827 inset;
}
.k2 {
flex: 1 0 auto;
background-color: black;
box-shadow: -8px 0 0 0 #292827 inset;
}
.k3 {
flex: 2 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.k4 {
flex: 1 0 auto;
background-color: #f9e217;
}
.l1 {
flex: 2 0 auto;
background-color: red;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.l2 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.l3 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px 0 0 0 #292827 inset;
}
.l4 {
flex: 1 0 auto;
background-color: #f9e217;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.m1 {
flex: 2 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.m2 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.m3 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px -8px 0 0 #292827 inset;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
.m3 {
flex: 2 0 auto;
background-color: black;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.m4 {
flex: 1 0 auto;
}
.n1 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.n2 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.n3 {
flex: 3 0 auto;
background-color: #0c7bbc;
box-shadow: -8px 0 0 0 #292827 inset;
}
.n4 {
flex: 1 0 auto;
}
.o1 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.o2 {
flex: 1 0 auto;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.o3 {
flex: 3 0 auto;
background-color: #0c7bbc;
box-shadow: -8px 0 0 0 #292827 inset;
}
.o4 {
flex: 1 0 auto;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.p1 {
flex: 2 0 auto;
background-color: #f9e217;
box-shadow: -8px 0 0 0 #292827 inset;
}
.p2 {
flex: 3 0 auto;
background-color: #0c7bbc;
box-shadow: -8px 0 0 0 #292827 inset;
}
.p3 {
flex: 1 0 auto;
}
.q1 {
flex: 2 0 auto;
background-color: #f9e217;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.q2 {
flex: 3 0 auto;
background-color: #0c7bbc;
box-shadow: -8px -8px 0 0 #292827 inset;
}
.q3 {
flex: 1 0 auto;
box-shadow: 0 -8px 0 0 #292827 inset;
}
.r1 {
flex: 1 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.r2 {
flex: 1 0 auto;
background-color: black;
box-shadow: -8px 0 0 0 #292827 inset;
}
.r3 {
flex: 2.5 0 auto;
box-shadow: -8px 0 0 0 #292827 inset;
}
.r4 {
flex: 1.5 0 auto;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
<div class="container">
<div class="box_A">
<div class="row0">
<div class="a1"></div>
<div class="a2"></div>
<div class="a3"></div>
</div>
<div class="row1">
<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
</div>
<div class="row2">
<div class="b1-bottom"></div>
<div class="b2"></div>
<div class="b3-bottom"></div>
</div>
<div class="row3">
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<div class="c4"></div>
</div>
<div class="row4">
<div class="c1"></div>
<div class="c2-bottom"></div>
<div class="c3-bottom"></div>
<div class="c4-bottom"></div>
</div>
<div class="row5">
<div class="d1"></div>
<div class="d2"></div>
<div class="d3"></div>
<div class="d4"></div>
</div>
<div class="row6">
<div class="e1"></div>
<div class="e2"></div>
<div class="e3"></div>
<div class="e4"></div>
</div>
<div class="row7">
<div class="f1"></div>
<div class="f2"></div>
<div class="f3"></div>
<div class="f4"></div>
</div>
<div class="row8">
<div class="g1"></div>
<div class="g2"></div>
<div class="g3"></div>
<div class="g4"></div>
<div class="g5"></div>
</div>
<div class="row9">
<div class="h1"></div>
<div class="h2"></div>
<div class="h3"></div>
<div class="h4"></div>
</div>
</div>
<div class="box_B">
<div class="row0">
<div class="i1"></div>
<div class="i2"></div>
<div class="i3"></div>
<div class="i4"></div>
</div>
<div class="row1">
<div class="j1"></div>
<div class="j2"></div>
<div class="j3"></div>
<div class="j4"></div> | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
<div class="j2"></div>
<div class="j3"></div>
<div class="j4"></div>
</div>
<div class="row2">
<div class="k1"></div>
<div class="k2"></div>
<div class="k3"></div>
<div class="k4"></div>
</div>
<div class="row3">
<div class="l1"></div>
<div class="l2"></div>
<div class="l3"></div>
<div class="l4"></div>
</div>
<div class="row4">
<div class="m1"></div>
<div class="m2"></div>
<div class="m3"></div>
<div class="m4"></div>
</div>
<div class="row5">
<div class="n1"></div>
<div class="n2"></div>
<div class="n3"></div>
<div class="n4"></div>
</div>
<div class="row6">
<div class="o1"></div>
<div class="o2"></div>
<div class="o3"></div>
<div class="o4"></div>
</div>
<div class="row7">
<div class="p1"></div>
<div class="p2"></div>
<div class="p3"></div>
</div>
<div class="row8">
<div class="q1"></div>
<div class="q2"></div>
<div class="q3"></div>
</div>
<div class="row9">
<div class="r1"></div>
<div class="r2"></div>
<div class="r3"></div>
<div class="r4"></div>
</div>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
Thank you in advance for your comments.
Answer: CSS knows variables
In CSS it is possible to initialize a variable with the following syntax: --border-color: #292827. After the initialization it can be used with shadow-box: -8 0 0 0 var(--border-color) inset.
You can find more about it in the MDN docs.
Don't use classes as ids
Every element (the rows, boxes and cells) has its own class. But the purpose of a class is for it to be reused. The opposite is true for an id. An id gets only used once.
By using reusable classes we can achieve a more readable HTML and CSS. Because <div class="flex-2_5 border-right-and-bottom blue"></div> is better to read and understand than <div class="i5"></div>.
Let's fix the rows
In the given code we can easily replace the "id"s with reusable classes.
.row0,
.row1,
.row2,
.row3,
.row4,
.row5,
.row6,
.row7,
.row8,
.row9 {
display: flex;
}
All the classes for the rows can be replaced by one row class:
.row {
display: flex;
}
After that change we simply can mark a div as a row by <div class="row">...</div> instead of <div class=row1>...</div>, <div class=row2>...</div> and so on.
Let's fix the boxes
.box_A,
.box_B {
flex: 1 0 auto;
}
.box_A > div,
.box_B > div {
height: 10%;
}
In this case we can create again a single box-class. After that we can reuse it in the CSS and the HTML:
.box {
flex: 1 0 auto;
}
.box>div {
height: 10%;
}
<div class="box">
<!-- all the cells -->
</div>
<div class="box">
<!-- more cells -->
</div>
Let's fix the cells
This is the fun part. We don't need to create a class for every cell. Instead, we can extract the characteristics, put them into their own classes and reuse the created classes in the HTML.
First, we need to identify the characteristics:
cells can have the same width
cells can have the same borders (box-shadows)
cells can have the same color
Second, we create classes for those properties:
/* here are the sizes */
.flex-0_5 {
flex: 0.5 0 auto;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
.flex-1 {
flex: 1 0 auto;
}
/* ... and more sizes */
/* here are the borders */
.border-right {
box-shadow: var(--border-width) 0 0 0 var(--border-color) inset;
}
.border-bottom {
box-shadow: 0 var(--border-width) 0 0 var(--border-color) inset;
}
.border-right-and-bottom {
box-shadow: var(--border-width) var(--border-width) 0 0 var(--border-color) inset;
}
/* here are the colors */
.red {
background-color: red;
}
.yellow {
background-color: #f9e217;
}
.black {
background-color: black;
}
.blue {
background-color: #0c7bbc;
}
Final Solution
:root {
--border-width: -8px;
--border-color: #292827;
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.container {
display: flex;
border: 16px solid var(--border-color);
height: 100vh;
}
.box {
flex: 1 0 auto;
}
.box>div {
height: 10%;
}
.row {
display: flex;
}
.red {
background-color: red;
}
.yellow {
background-color: #f9e217;
}
.black {
background-color: black;
}
.blue {
background-color: #0c7bbc;
}
.flex-0_5 {
flex: 0.5 0 auto;
}
.flex-1 {
flex: 1 0 auto;
}
.flex-1_25 {
flex: 1.25 0 auto;
}
.flex-1_5 {
flex: 1.5 0 auto;
}
.flex-2 {
flex: 2 0 auto;
}
.flex-2_5 {
flex: 2.5 0 auto;
}
.flex-3 {
flex: 3 0 auto;
}
.flex-4 {
flex: 4 0 auto;
}
.border-right {
box-shadow: var(--border-width) 0 0 0 var(--border-color) inset;
}
.border-bottom {
box-shadow: 0 var(--border-width) 0 0 var(--border-color) inset;
} | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
.border-right-and-bottom {
box-shadow: var(--border-width) var(--border-width) 0 0 var(--border-color) inset;
}
<div class="container">
<div class="box">
<div class="row">
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-3 border-right-and-bottom"></div>
<div class="flex-2 border-right-and-bottom"></div>
</div>
<div class="row">
<div class="flex-1 border-right"></div>
<div class="flex-4 border-right red"></div>
<div class="flex-2_5 border-right yellow"></div>
</div>
<div class="row">
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-4 border-right red"></div>
<div class="flex-2_5 border-right-and-bottom yellow"></div>
</div>
<div class="row">
<div class="flex-1 border-right"></div>
<div class="flex-4 border-right red"></div>
<div class="flex-1_25 border-right"></div>
<div class="flex-1_25 border-right"></div>
</div>
<div class="row">
<div class="flex-1 border-right"></div>
<div class="flex-4 border-right-and-bottom red"></div>
<div class="flex-1_25 border-right-and-bottom"></div>
<div class="flex-1_25 border-right-and-bottom"></div>
</div>
<div class="row">
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-2 border-right black"></div>
<div class="flex-2 border-right"></div>
<div class="flex-2_5 border-right-and-bottom"></div>
</div>
<div class="row">
<div class="flex-1 border-right yellow"></div>
<div class="flex-2 border-right-and-bottom black"></div>
<div class="flex-2 border-right-and-bottom"></div>
<div class="flex-2_5 border-right blue"></div>
</div>
<div class="row">
<div class="flex-1 border-right yellow"></div>
<div class="flex-2 border-right"></div>
<div class="flex-2 border-right-and-bottom black"></div>
<div class="flex-2_5 border-right-and-bottom blue"></div> | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
<div class="flex-2_5 border-right-and-bottom blue"></div>
</div>
<div class="row">
<div class="flex-1 border-right-and-bottom yellow"></div>
<div class="flex-2 border-right-and-bottom"></div>
<div class="flex-1 border-right yellow"></div>
<div class="flex-1 border-right"></div>
<div class="flex-2_5 border-right red"></div>
</div>
<div class="row">
<div class="flex-3 border-right yellow"></div>
<div class="flex-1 border-right yellow"></div>
<div class="flex-1 border-right"></div>
<div class="flex-2_5 border-right red"></div>
</div>
</div>
<div class="box">
<div class="row">
<div class="flex-2 border-right blue"></div>
<div class="flex-0_5 border-right-and-bottom yellow"></div>
<div class="flex-0_5 border-right-and-bottom black"></div>
<div class="flex-3 border-bottom"></div>
</div>
<div class="row">
<div class="flex-2 border-right-and-bottom blue"></div>
<div class="flex-1 border-right-and-bottom yellow"></div>
<div class="flex-2 border-right"></div>
<div class="flex-1 yellow"></div>
</div>
<div class="row">
<div class="flex-2 border-right red"></div>
<div class="flex-1 border-right-and-bottom black"></div>
<div class="flex-2 border-right-and-bottom"></div>
<div class="flex-1 yellow"></div>
</div>
<div class="row">
<div class="flex-2 border-right-and-bottom red"></div>
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-2 border-right black"></div>
<div class="flex-1 border-bottom yellow"></div>
</div>
<div class="row">
<div class="flex-2 border-right-and-bottom"></div>
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-2 border-right-and-bottom black"></div>
<div class="flex-1"></div>
</div>
<div class="row">
<div class="flex-1 border-right"></div> | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
html, css
</div>
<div class="row">
<div class="flex-1 border-right"></div>
<div class="flex-1 border-right"></div>
<div class="flex-3 border-right blue"></div>
<div class="flex-1"></div>
</div>
<div class="row">
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-1 border-right-and-bottom"></div>
<div class="flex-3 border-right blue"></div>
<div class="flex-1 border-bottom"></div>
</div>
<div class="row">
<div class="flex-2 border-right yellow"></div>
<div class="flex-3 border-right blue"></div>
<div class="flex-1"></div>
</div>
<div class="row">
<div class="flex-2 border-right-and-bottom yellow"></div>
<div class="flex-3 border-right-and-bottom blue"></div>
<div class="flex-1 border-bottom"></div>
</div>
<div class="row">
<div class="flex-1 border-right"></div>
<div class="flex-1 border-right black"></div>
<div class="flex-2_5 border-right"></div>
<div class="flex-1_5"></div>
</div>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 44354,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css",
"url": null
} |
performance, beginner, c, programming-challenge, c99
Title: Simple photomosaic generator
Question: I wrote an implementation of Robert Heaton's Programming Exercise for Advanced Beginners #4 (photomosaics) in C99 using the MagickCore library. The full code is as follows:
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <MagickCore/MagickCore.h>
#define DIE(rc, fmt, ...) { fprintf(stderr, "FATAL: "fmt"\n", __VA_ARGS__); exit(rc); }
#define WARN(fmt, ...) { fprintf(stderr, "WARN: " fmt"\n", __VA_ARGS__); }
#define assert_error(expression, s) if(!expression) { perror(s); abort(); }
typedef struct {
unsigned int r, g, b;
} Pixel;
typedef enum { L, UL, XU, XUL, F } NUM_TYPES;
#define MAX_FN_LEN 150
#define IMG_LIST_MAX_SIZE 5091
static const char *cache_filename = "/home/wilson/.cache/photomosaics/avgs";
static char *cache_buf = NULL;
static size_t cache_max_size;
static ssize_t initial_cache_size = 1;
static ssize_t cache_size = 0;
static time_t cache_mtime;
static long *deletables;
static size_t deletables_ind = 0;
static char temp_dirname[] = "/tmp/photomosaics-XXXXXX";
static char **inner_cache_tmp_files;
static char **files_inner_cached = NULL;
static size_t files_inner_cached_ind = 0;
static void try(int exit_code, char *function_name) {
if(exit_code != 0) perror(function_name);
}
static size_t slen(const char *s, size_t maxlen) {
char *pos = memchr(s, '\0', maxlen);
return pos ? (size_t)(pos - s) : maxlen;
}
static size_t indof(const char *s, char ch, size_t maxlen) {
char *pos = memchr(s, ch, maxlen);
return pos ? (size_t)(pos - s) : maxlen;
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
static bool parse_num(const char *str, NUM_TYPES type, void *out) {
char *endptr;
const char *old_locale = setlocale(LC_ALL, NULL);
setlocale(LC_ALL|~LC_NUMERIC, "");
errno = 0;
int my_errno = 0;
switch(type) {
case L:
*((long *)out) = strtol(str, &endptr, 10);
break;
case UL:
*((unsigned long *)out) = strtoul(str, &endptr, 10);
break;
case XU: {
unsigned long tmp = strtoul(str, &endptr, 16);
if(tmp > UINT_MAX) my_errno = ERANGE;
else *((unsigned int *)out) = tmp;
}
break;
case XUL:
*((unsigned long *)out) = strtoul(str, &endptr, 16);
break;
case F:
*((float *)out) = strtof(str, &endptr);
break;
}
setlocale(LC_ALL, old_locale);
if(errno) return false;
if(my_errno) {
errno = my_errno;
return false;
}
/*N.B. fails on "partial" conversions or if str is empty*/
return *str != '\0' && *endptr == '\0';
}
/*static bool parse_float(char *str, float *out) {*/
/* return parse_num(str, F, out);*/
/*}*/
/*static bool parse_long(char *str, long *out) {*/
/* return parse_num(str, L, out);*/
/*}*/
static bool parse_hex_tou(char *str, unsigned int *out) {
return parse_num(str, XU, out);
}
static bool parse_ulong(char *str, unsigned long *out) {
return parse_num(str, UL, out);
}
static Pixel hexstr_top(const char *hs) {
char rstr[3] = {hs[0], hs[1],};
char gstr[3] = {hs[2], hs[3],};
char bstr[3] = {hs[4], hs[5],};
Pixel p;
parse_hex_tou(rstr, &p.r);
parse_hex_tou(gstr, &p.g);
parse_hex_tou(bstr, &p.b);
return p;
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
static ssize_t cache_grep(char *key) {
if(cache_size == -1)
return -1;
if(!cache_buf) {
/* init cache */
errno = 0;
FILE *cache_file = fopen(cache_filename, "r");
struct stat cache_st;
if(!cache_file) {
WARN("Couldn't open cache file '%s'. "
"Please ensure the directory exists.", cache_filename);
perror("fopen");
}
else {
if(stat(cache_filename, &cache_st) == 0)
errno = 0;
else if(errno == ENOENT) {
/* create the file and try again just in case that's the only error */
errno = 0;
FILE *tmp_cache_file = fopen(cache_filename, "a");
if(!tmp_cache_file) {
WARN("Couldn't open cache file '%s'. "
"Please ensure the directory exists.", cache_filename);
perror("fopen");
}
else {
try(fclose(tmp_cache_file), "fclose");
if(stat(cache_filename, &cache_st) != 0) {
WARN("Could not stat cache file '%s'", cache_filename);
perror("stat");
}
}
}
}
if(errno) {
WARN("Will stop attempting to cache to '%s' for the remainder of execution.", cache_filename);
cache_size = -1;
return -1;
}
/* No errors, proceed to populate cache_buf */ | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
/* No errors, proceed to populate cache_buf */
cache_mtime = cache_st.st_mtime;
long cache_file_size = cache_st.st_size;
/* The following 2 mallocs are guesses; will realloc later if needed */
cache_max_size = (cache_file_size < 5822 ? 5822 : cache_file_size) + 5 * MAX_FN_LEN;
cache_buf = malloc(cache_max_size);
deletables = malloc(50 * sizeof(long));
initial_cache_size = cache_size = fread(cache_buf, 1, cache_file_size, cache_file);
cache_buf[cache_size] = 0; /* For the initial strncat later */
assert(cache_size == cache_file_size);
try(fclose(cache_file), "fclose");
}
if(cache_size == 0) return -1;
char filename[MAX_FN_LEN];
struct stat file_st; | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
for(ssize_t i=0; i < cache_size; i += indof(cache_buf + i, '\n', cache_size - i) + 1) {
/* If we already marked it for deletion, we want the image's cache entry which
we put at the bottom of the buffer, in case the avg color has changed. */
bool skip = false;
for(size_t j=0; j < deletables_ind; j++) {
if(deletables[j] == i) {
skip = true;
break;
}
}
if(skip) continue;
size_t fn_len = 0;
size_t fn_begin = i;
for(; i < cache_size; i++) {
if((filename[i-fn_begin]=cache_buf[i]) == '\t') {
fn_len = i - fn_begin;
filename[fn_len] = '\0';
i++;
break;
}
}
assert(fn_len);
if(!strncmp(filename, key, fn_len)) {
//Already exists in cache
try(stat(filename, &file_st), "stat");
//The sole use of `initial_...`. Prevents the caller from re- and recaching newly-added files
if(i > initial_cache_size - 1 || file_st.st_mtime < cache_mtime) {
/* Cache entry is up to date */
return i;
}
/* Not up to date. Caller will create a new cache entry,
then we will delete this line at the end of the program */
if(deletables_ind > 49) {
deletables = realloc(deletables, (deletables_ind + 1) * sizeof(deletables[0]));
assert_error(deletables, "realloc");
}
deletables[deletables_ind++] = fn_begin;
return -1;
}
}
return -1;
}
static bool cache_fetch(char *key, Pixel *value) {
ssize_t i = cache_grep(key);
if(i == -1) return false;
char hexstr[7];
assert(indof(cache_buf + i, '\n', cache_size - i) == 6);
hexstr[0] = 0;
strncat(hexstr, cache_buf + i, 6);
*value = hexstr_top(hexstr);
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
strncat(hexstr, cache_buf + i, 6);
*value = hexstr_top(hexstr);
return true;
}
static bool cache_put(char *key, Pixel value) {
if(!cache_buf) return false;
char entry[MAX_FN_LEN + 9];
int entry_length = sprintf(entry, "%s\t%02x%02x%02x\n", key, value.r, value.g, value.b);
size_t new_size_of_cache = cache_size + entry_length + 1;
if(new_size_of_cache > cache_max_size) {
cache_buf = realloc(cache_buf, new_size_of_cache);
assert_error(cache_buf, "realloc");
cache_max_size = new_size_of_cache;
}
strncat(cache_buf, entry, entry_length);
cache_size = new_size_of_cache - 1;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
static Pixel get_avg_color(unsigned char *pixels, const size_t pixels_column_cnt, const ssize_t x, const ssize_t y, const size_t width, const size_t height) {
Pixel p = {0};
int i = y * pixels_column_cnt + x * 3;
for(unsigned long c=0; c < width*height;) {
p.r += pixels[i++];
p.g += pixels[i++];
p.b += pixels[i++];
if(++c % width == 0)
i += (pixels_column_cnt - width) * 3; //next row ...
}
p.r /= width*height;
p.g /= width*height;
p.b /= width*height;
return p;
}
static bool get_resized_pixel_info(char *filename, const size_t width, const size_t height, unsigned char *pixels_out, ExceptionInfo *exception) {
if(!files_inner_cached) {
inner_cache_tmp_files = malloc(IMG_LIST_MAX_SIZE * sizeof(char*));
files_inner_cached = malloc(IMG_LIST_MAX_SIZE * sizeof(char*));
}
const size_t pixels_arr_size = width * height * 3;
bool file_is_cached = false;
size_t i;
for(i=0; i < files_inner_cached_ind; i++) {
if(!strcmp(files_inner_cached[i], filename)) {
file_is_cached = true;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
if(file_is_cached) {
FILE *inner_cache = fopen(inner_cache_tmp_files[i], "rb");
assert_error(inner_cache, "fopen");
size_t z = fread(pixels_out, 1, pixels_arr_size, inner_cache);
fclose(inner_cache);
return z == pixels_arr_size;
}
else {
if(files_inner_cached_ind == 0)
mkdtemp(temp_dirname);
const size_t filename_len = strlen(filename);
const size_t dirname_len = strlen(temp_dirname);
char *temp_name = malloc(filename_len);
char *temp_path = malloc(filename_len + dirname_len + 2);
temp_name[0] = 0;
strncat(temp_name, filename, filename_len);
/* TODO gracefully handle slashes (?) and percents in the filenames themselves */
for(size_t c=0; c < filename_len; ++c) if(temp_name[c] == '/') temp_name[c] = '%';
temp_path[0] = 0;
strncat(temp_path, temp_dirname, dirname_len);
temp_path[dirname_len] = '/';
temp_path[dirname_len+1] = 0;
strncat(temp_path, temp_name, filename_len);
free(temp_name);
FILE *inner_cache = fopen(temp_path, "wb");
assert_error(inner_cache, "fopen");
ImageInfo *image_info = CloneImageInfo((ImageInfo *)NULL);
image_info->filename[0] = 0;
strncat(image_info->filename, filename, filename_len);
Image *src_img = ReadImage(image_info, exception);
Image *src_img_r = ResizeImage(src_img, width, height, LanczosFilter, exception); | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
if(!src_img_r) MagickError(exception->severity, exception->reason, exception->description);
ExportImagePixels(src_img_r, 0, 0, width, height, "RGB", CharPixel, pixels_out, exception);
if(exception->severity != UndefinedException) CatchException(exception);
DestroyImage(src_img);
DestroyImage(src_img_r);
DestroyImageInfo(image_info);
assert(fwrite(pixels_out, 3, pixels_arr_size / 3, inner_cache) == pixels_arr_size / 3);
fclose(inner_cache);
inner_cache_tmp_files[files_inner_cached_ind] = malloc(strlen(temp_path) + 1);
strcpy(inner_cache_tmp_files[files_inner_cached_ind], temp_path);
files_inner_cached[files_inner_cached_ind] = malloc(strlen(filename) + 1);
files_inner_cached[files_inner_cached_ind][0] = 0;
strncat(files_inner_cached[files_inner_cached_ind++], filename, filename_len);
free(temp_path);
return true;
}
}
static unsigned char *get_img_with_closest_avg(char *img_list, size_t img_list_size, Pixel p, const size_t width, const size_t height, ExceptionInfo *exception) {
const size_t pixels_arr_size = width * height * 3;
unsigned char *pixels_of_closest = malloc(pixels_arr_size);
unsigned char *pixels = malloc(pixels_arr_size);
float distance_of_closest = sqrtf(powf(0xff, 2) * 3); //max diff value
bool test_pxofcls_populated = false; | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
for(size_t c=0; c < img_list_size;) {
Pixel avg;
bool fetched_avg_from_cache = cache_fetch(&img_list[c], &avg);
if(!fetched_avg_from_cache) {
assert(get_resized_pixel_info(&img_list[c], width, height, pixels, exception));
avg = get_avg_color(pixels, width, 0, 0, width, height);
assert(cache_put(&img_list[c], avg));
}
long rdiff = (long)avg.r - p.r;
long gdiff = (long)avg.g - p.g;
long bdiff = (long)avg.b - p.b;
float new_distance = sqrtf(powf(rdiff, 2) + powf(gdiff, 2) + powf(bdiff, 2));
if(new_distance < distance_of_closest) {
distance_of_closest = new_distance;
if(fetched_avg_from_cache)
assert(get_resized_pixel_info(&img_list[c], width, height, pixels, exception));
// For now, return any perfect match
if(new_distance < 0.01f) {
free(pixels_of_closest);
return pixels;
}
memcpy(pixels_of_closest, pixels, pixels_arr_size);
test_pxofcls_populated = true;
}
c += slen(&img_list[c], img_list_size - c) + 1;
}
assert(test_pxofcls_populated);
free(pixels);
return pixels_of_closest;
}
static Image *photomosaic(Image *image, const size_t each_width, const size_t each_height, ExceptionInfo *exception) {
const size_t pixel_cnt = image->columns * image->rows;
unsigned char *pixels = malloc(pixel_cnt * 3);
FILE *f = popen("find $(find ~/pics -type d | grep -vE 'redacted|not_real') -maxdepth 1 -type f -print0", "r");
char buf[IMG_LIST_MAX_SIZE];
size_t bytes_read = fread(buf, 1, IMG_LIST_MAX_SIZE, f);
try(pclose(f), "pclose");
assert(ExportImagePixels(image, 0, 0, image->columns, image->rows, "RGB", CharPixel, pixels, exception)); | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
for(size_t i=0, j=0; i < pixel_cnt;) {
/*Specifying 0 for y allows us to automatically use i to "roll over" into next row*/
Pixel p = get_avg_color(pixels, image->columns, i, 0, each_width, each_height);
unsigned char *new_pixels = get_img_with_closest_avg(buf, bytes_read, p, each_width, each_height, exception);
for(size_t c=0; c < each_width*each_height;) {
pixels[j] = new_pixels[c*3];
pixels[j+1] = new_pixels[c*3+1];
pixels[j+2] = new_pixels[c*3+2];
j += 3;
if(++c % each_width == 0)
j += (image->columns - each_width) * 3; //next row ...
}
i += each_width; //next splotch
/*If this row is done, skip over all the rows we just splotched*/
if(i % image->columns == 0)
i += image->columns * (each_height - 1);
j = i * 3;
free(new_pixels);
}
Image *new_image = ConstituteImage(image->columns, image->rows, "RGB", CharPixel, pixels, exception);
free(pixels);
if(!new_image)
MagickError(exception->severity, exception->reason, exception->description);
return new_image;
}
void usage(char *progname) {
fprintf(stderr,
"Usage: %s (-h | (-i <input_file> -o <output_file> -w <width> -l <length>))\n"
"\t-h\tPrint this help message and exit.\n"
"\tThis program creates a photomosaic by replacing each block\n\t"
"of 'input_file' of size 'width' x 'length' by the resized\n\t"
"version of some image with a similar average color.\n\t"
"Writes the new image to the filename specified by 'output_file'.\n"
"\n\nExit status:\n"
"\t0\tSpecified operation succeeded\n"
"\t1\tError reading or performing some operation on an image\n"
"\t2\tError parsing command line arguments\n"
, progname);
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
int main(int argc, char **argv) {
ExceptionInfo *exception;
Image *input_img, *output_img = NULL;
const size_t max_fn_len = 400;
char input_img_filename[max_fn_len];
input_img_filename[0] = 0;
char output_img_filename[max_fn_len];
output_img_filename[0] = 0;
ImageInfo *image_info, *new_image_info = NULL;
size_t length = 1, width = 1;
int opt;
while((opt=getopt(argc, argv, "hi:o:l:w:")) > -1) {
switch(opt) {
case 'h':
usage(argv[0]);
return 0;
case 'i':
if(slen(optarg, max_fn_len) == max_fn_len) DIE(2, "Argument \"%s\" to option -i should be less than %zu characters.", optarg, max_fn_len)
strncat(input_img_filename, optarg, max_fn_len - 1);
break;
case 'l':
if(!parse_ulong(optarg, &length))
DIE(2, "Argument \"%s\" to option -l could not be parsed to an unsigned long int.", optarg);
break;
case 'o':
if(slen(optarg, max_fn_len) == max_fn_len) DIE(2, "Argument \"%s\" to option -o should be less than %zu characters.", optarg, max_fn_len)
strncat(output_img_filename, optarg, max_fn_len - 1);
break;
case 'w':
if(!parse_ulong(optarg, &width))
DIE(2, "Argument \"%s\" to option -w could not be parsed to an unsigned long int.", optarg);
break;
}
}
if(slen(input_img_filename, max_fn_len) < 1) DIE(2, "No input image specified.%s", "");
if(slen(output_img_filename, max_fn_len) < 1) DIE(2, "No output image specified.%s", "");
MagickCoreGenesis(*argv, MagickTrue);
exception = AcquireExceptionInfo(); | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
MagickCoreGenesis(*argv, MagickTrue);
exception = AcquireExceptionInfo();
image_info = CloneImageInfo((ImageInfo *)NULL);
strcpy(image_info->filename, input_img_filename);
input_img = ReadImage(image_info, exception);
if(exception->severity != UndefinedException)
CatchException(exception);
if(!input_img)
DIE(1, "Input image %s could not be read.", input_img_filename);
output_img = photomosaic(input_img, width, length, exception);
if(exception->severity != UndefinedException)
CatchException(exception);
/* Teardown */
if(files_inner_cached) {
for(size_t i=0; i < files_inner_cached_ind; i++) {
try(remove(inner_cache_tmp_files[i]), "remove");
free(inner_cache_tmp_files[i]);
free(files_inner_cached[i]);
}
try(remove(temp_dirname), "remove");
}
if(cache_buf) {
FILE *cache = fopen(cache_filename, "w");
if(!cache) {
WARN("Failed to reopen the cache file '%s' for writing "
"in order to update the cache properly:", cache_filename);
perror("fopen");
WARN("The cache at '%s' may now contain duplicate entries.", cache_filename);
}
else for(ssize_t i=0; i < cache_size;) {
bool keep = true;
for(size_t j=0; j < deletables_ind; j++) {
if(deletables[j] == i) {
keep = false;
break;
}
}
size_t line_len = indof(cache_buf + i, '\n', cache_size - i);
if(keep) for(size_t j=0; j <= line_len; j++) assert(fputc(cache_buf[i+j], cache) != EOF);
i += line_len + 1;
}
if(cache) fclose(cache);
free(deletables);
free(cache_buf);
} | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
if(output_img) {
new_image_info = CloneImageInfo((ImageInfo *)NULL);
strcpy(output_img->filename, output_img_filename);
WriteImage(new_image_info, output_img, exception);
DestroyImage(output_img);
DestroyImageInfo(new_image_info);
}
DestroyImage(input_img);
DestroyImageInfo(image_info);
DestroyExceptionInfo(exception);
MagickCoreTerminus();
return 0;
}
(can also view at https://github.com/thenewmantis/photomosaics/blob/ffb7821da62a5f6852d79889b1a3cd1f527babdf/photomosaics.c)
I compile with the following command:
gcc -ansi -std=c99 -Wall -Wpedantic -Wextra -D_POSIX_C_SOURCE=200809L -lm `pkg-config --cflags --libs MagickWand`
I receive no warnings on my machine.
I am a beginner in C and looking for feedback particularly on the following things: | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
Performance/speed. When creating a mosaic of a 3264x2448 input image in 24x17 blocks, it takes almost a minute and a half, which I consider reasonably good. With a 4214x2863 image broken into 7x7 blocks, it's closer to 7 minutes (is this reasonable? Opinions?). I'm wondering if there is an obviously faster way to work with the "inner cache" (the cache for each execution which stores all the pixel information for each image). My general goal with this is to have something that will run as fast as possible without the need for a large quantity of pre-existing cached data.
"Obvious" standard ways of doing things in C99 that I may have missed. My experience learning C so far has been working through Robert Heaton's exercises one by one and using Linux manpages and StackOverflow when I need help, so there may be things that are in some book/class that every beginner has read/taken, which I am simply not aware of.
Portability. Feel free to ignore for now that my method of creating a temp cache in get_resized_pixel_info will not work on Windows (the UNIX find command on line 367 likewise is just a placeholder which I intend to replace with some better method of supplying source images), but in general I am looking for ways to reduce my dependency on compiler specific extensions, the POSIX standard and implementation-defined outcomes. (This is why I rolled my own slen instead of just using strnlen, although I still need -D_POSIX_C_SOURCE=200809L until I define my own mkdtemp analogue et al.)
Answer: I get a lot of warnings when compiling, particularly for signed/unsigned conversions and for passing string literals as char* (e.g. to try()). These are easily fixed.
There's no need for parse_num() and the NUM_TYPES type. The only call sites are within parse_hex_tou() and parse_ulong(). And those functions' call sites are:
Pixel p;
parse_hex_tou(rstr, &p.r);
parse_hex_tou(gstr, &p.g);
parse_hex_tou(bstr, &p.b);
return p;
and | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
and
while((opt=getopt(argc, argv, "hi:o:l:w:")) > -1) {
switch(opt) {
case 'l':
if(!parse_ulong(optarg, &length))
DIE(2, "Argument \"%s\" to option -l could not be parsed to an unsigned long int.", optarg);
break;
case 'w':
if(!parse_ulong(optarg, &width))
DIE(2, "Argument \"%s\" to option -w could not be parsed to an unsigned long int.", optarg);
break;
}
}
In both these cases, we'd like to set and restore the locale just once rather than for each number. And we have undefined behaviour in a couple of places: passing a null pointer as the locale argument, and using the returned string pointer after another intervening setlocale() call. We can fix both of those with a simple old_locale = setlocale(LC_NUMERIC, "C").
For the first of those functions, where we completely ignore parse failures, I'd use a simple sscanf("%2x%2x%2x") for the conversion (and consider checking the result, or at least returning a predictable value on failure). For the second, we can have a much simpler function which no longer requires a switch.
There's a portability bug that we pass address of a size_t to parse_ulong. We need to be reading as the correct type on platforms where these are not the same type. The best way to do that is using sscanf("%zu") (or perhaps sscanf("%zu%n") so we can check the conversion consumed the entire string).
We don't need to copy strings from the command-line, nor impose arbitrary limits on their length:
const size_t max_fn_len = 400;
char input_img_filename[max_fn_len];
input_img_filename[0] = 0;
char output_img_filename[max_fn_len];
output_img_filename[0] = 0;
We can simply have
char const *input_img_filename = NULL;
char const *output_img_filename = NULL; | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
performance, beginner, c, programming-challenge, c99
and just assign the pointer when parsing arguments:
int opt;
while((opt=getopt(argc, argv, "hi:o:l:w:")) > -1) {
switch(opt) {
case 'i':
input_img_filename = optarg;
break;
case 'o':
output_img_filename = optarg;
break;
}
}
if (!input_img_filename) DIE(2, "No input image specified.%s", "");
if (!output_img_filename) DIE(2, "No output image specified.%s", "");
Usability: when we ask for help using -h option, the help is printed to the standard error stream. I would expect that to go to the standard output stream, since the help message is then the expected output.
We should produce some error-stream output if an unrecognised option is passed, though - add a case '?' to handle that. | {
"domain": "codereview.stackexchange",
"id": 44355,
"lm_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, beginner, c, programming-challenge, c99",
"url": null
} |
bash, shell, sh
Title: Shell script to download, compile and run Analog Clock in AEC
Question: As some of you know, I have made a programming language, called AEC, and written two compilers for it, one targetting x86 and other targetting WebAssembly. Recently, I have tried to write two shell scripts to download, compile and use those compilers, and run the Analog Clock example. I have put those two shell scripts on my blog, and it is important for me that they run on as many computers as possible. Here is what I've made by now.
Shell script to use the AEC-to-x86 compiler:
mkdir ArithmeticExpressionCompiler
cd ArithmeticExpressionCompiler
if [ $(command -v wget > /dev/null 2>&1 ; echo $?) -eq 0 ] # Check if "wget" exists, see those StackOverflow answers for more details:
# https://stackoverflow.com/a/75103891/8902065
# https://stackoverflow.com/a/75103209/8902065
then
wget https://flatassembler.github.io/Duktape.zip
else
curl -o Duktape.zip https://flatassembler.github.io/Duktape.zip
fi
unzip Duktape.zip
if [ $(command -v clang > /dev/null 2>&1 ; echo $?) -eq 0 ] # We prefer "clang" to "gcc" because... what if somebody tries to run this in CygWin terminal? GCC will not work then, CLANG might.
then
c_compiler="clang"
else
c_compiler="gcc"
fi
$c_compiler -o aec aec.c duktape.c -lm # The linker that comes with recent versions of Debian Linux insists that "-lm" is put AFTER the source files, or else it outputs some confusing error message.
if [ "$OS" = "Windows_NT" ]
then
./aec analogClockForWindows.aec
$c_compiler -o analogClockForWindows analogClockForWindows.s -m32
./analogClockForWindows
else
./aec analogClock.aec
$c_compiler -o analogClock analogClock.s -m32
./analogClock
fi | {
"domain": "codereview.stackexchange",
"id": 44356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, sh",
"url": null
} |
bash, shell, sh
Shell script to use the AEC-to-WebAssembly compiler:
if [ $(command -v git > /dev/null 2>&1 ; echo $?) -eq 0 ]
then
git clone https://github.com/FlatAssembler/AECforWebAssembly.git
cd AECforWebAssembly
elif [ $(command -v wget > /dev/null 2>&1 ; echo $?) -eq 0 ]
then
mkdir AECforWebAssembly
cd AECforWebAssembly
wget https://github.com/FlatAssembler/AECforWebAssembly/archive/refs/heads/master.zip
unzip master.zip
cd AECforWebAssembly-master
else
mkdir AECforWebAssembly
cd AECforWebAssembly
curl -o AECforWebAssembly.zip -L https://github.com/FlatAssembler/AECforWebAssembly/archive/refs/heads/master.zip # Without the "-L", "curl" will store HTTP Response headers of redirects to the ZIP file instead of the actual ZIP file.
unzip AECforWebAssembly.zip
cd AECforWebAssembly-master
fi
if [ $(command -v g++ > /dev/null 2>&1 ; echo $?) -eq 0 ]
then
g++ -std=c++11 -o aec AECforWebAssembly.cpp # "-std=c++11" should not be necessary for newer versions of "g++". Let me know if it is, as that probably means I disobeyed some new C++ standard (say, C++23).
else
clang++ -o aec AECforWebAssembly.cpp
fi
cd analogClock
../aec analogClock.aec
npx -p wabt wat2wasm analogClock.wat
if [ "$OS" = "Windows_NT" ] # https://stackoverflow.com/a/75125384/8902065
# https://www.reddit.com/r/bash/comments/10cip05/comment/j4h9f0x/?utm_source=share&utm_medium=web2x&context=3
then
node_version=$(node.exe -v)
else # We are presumably running on an UNIX-like system, where storing output of some program into a variable works as expected.
node_version=$(node -v)
fi
# "node -v" outputs version in the format "v18.12.1"
node_version=${node_version:1} # Remove 'v' at the beginning
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=$(($node_version)) # Convert the NodeJS version number from a string to an integer.
if [ $node_version -lt 11 ]
then | {
"domain": "codereview.stackexchange",
"id": 44356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, sh",
"url": null
} |
bash, shell, sh
if [ $node_version -lt 11 ]
then
echo "NodeJS version is lower than 11 (it is $node_version), you will probably run into trouble!"
fi
node analogClock | {
"domain": "codereview.stackexchange",
"id": 44356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, sh",
"url": null
} |
bash, shell, sh
So, what do you think, how can I improve those shell scripts? The most important thing for me is that they run on as many computers as possible, simply by being copied-and-pasted into a terminal emulator.
Answer: First things first: neither script has a #! line to select a specific shell. If it's intended to be portable, I recommend #!/bin/sh. And set some options: I recommend using both -u and -e to simplify the error-handling.
This is an anti-pattern:
[ $(command -v wget > /dev/null 2>&1 ; echo $?) -eq 0 ]
There's no need to print out the exit status like that - just use it directly:
command -v wget > /dev/null 2>&1
We have a lot of repetition, particularly of URLs. Fix that using variables, so that it's easier to change the hosting.
All that said, I think it's probably better to use existing tools such as Autoconf, and include that in your repo so that users can simply git clone && ./configure && make in the usual manner without having to do something special for your sources.
You will probably want to supply a makefile pattern rule that matches *.aec files. | {
"domain": "codereview.stackexchange",
"id": 44356,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, sh",
"url": null
} |
node.js, security, authentication, express.js
Title: Basic node authentication system
Question: I built a basic authentication system for a node application and I have some security concerns. The username and password the user enters when they log in are stored as plaintext using express-sessions. Then whenever they make a request I call a function to make sure it matches the hashed password stored in the database. My concern is that storing passwords as plaintext using express-sessions is a vulnerability. Anyone familiar with express-sessions let me know if there is something I should do when configuring it to make sure the data is secure (or some alternative if this method for authentication is not viable). Also looking for advice concerning efficiency and obvious bad practices.
Login Router:
router.get('/',(req,res)=>{
authenticate(req.session.username,req.session.password,(result)=>{
if (result){//redirects to homepage if logged in
res.redirect('/')
}
else{
res.render('login')
}
})
})
router.post('/',(req,res)=>{
let db=dbGetter.getDb()
db.collection('users').findOne({username:req.body.username},async (err,result)=>{
//queries database for user matching entered username
if (err) {
console.error(err);
} else {
if (result) {
if( await bcrypt.compare(req.body.password,result.password)){//compares entered password to db
//stores username and password as plain text in session
req.session.username=req.body.username
req.session.password=req.body.password
res.redirect('/')
}
else{
console.log('wrong password')
}
} else {
console.log("user does not exist");
}
}
})
}) | {
"domain": "codereview.stackexchange",
"id": 44357,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "node.js, security, authentication, express.js",
"url": null
} |
node.js, security, authentication, express.js
Register Router:
router.get('/', (req,res)=>{
authenticate(req.session.username,req.session.password,(result)=>{
if (result){//redirects to homepage if logged in
res.redirect('/')
}
else{
res.render('register')
}
})
})
router.post('/',async(req,res)=>{
try{
const hashedPassword=await bcrypt.hash(req.body.password,10)
const user= new User({
username:req.body.username,
password:hashedPassword
})
user.save((err)=>{
if(err){
console.log('error saving user to db')
}
else{
res.redirect('/login')
}
})
}
catch(err){
console.error(err)
res.redirect('/register')
}
})
Homepage Router:
router.get('/',(req,res)=>{
authenticate(req.session.username,req.session.password,(result)=>{
if (result){
res.render('index',{username: req.session.username})
}
else{//redirects to login page if not logged in
res.redirect('/login')
}
})
})
Authenticate function:
function authenticate(username,password,cb){
let db=dbGetter.getDb()
db.collection('users').findOne({username:username},async (err,result)=>{
if (err) {
console.error(err);
} else {
if (result) {
if( await bcrypt.compare(password,result.password)){
cb (true)
}
else{
cb(false)
}
}else{
cb(false)
}
}
})
} | {
"domain": "codereview.stackexchange",
"id": 44357,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "node.js, security, authentication, express.js",
"url": null
} |
node.js, security, authentication, express.js
}
})
}
Answer: Short answer: yes, don't do it.
Don't put password into session. On one hand, the security of it depends on the used session store. On other hand, you don't need the password in session or anywhere else.
In fact, don't put username and especially email into session either.
Put there the primary key. Only verify password in login process. As long as user id is in session it is logged user and you can get it from db by id.
However, this way after changing password, previously logged in sessions remain logged in. You should deploy a separate mechanism to prevent that. Like putting a separate hash into session and change it along with password.
But this is still quite insecure, because the authentication relies solely on a cookie. You should use a csrf token to prevent xss attacks.
But that still has issues and it would be best to use Authorization header and access tokens instead of cookie based auth.
Security is a very complex topic... | {
"domain": "codereview.stackexchange",
"id": 44357,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "node.js, security, authentication, express.js",
"url": null
} |
php, mysql, lookup
Title: Converting a query result into an key=>value pairs for a lookup table
Question: My app has a number of lookup tables stored in a MySQL database that are used for various purposes such as a select element.
Unfortunately, the query results aren't in an easily-digestible format and need some massaging to be more useful to me.
For example, when you query one of the lookup tables for all values, you get an array like this:
0 => ['level_id' => 1, 'level' => 'Trivial'],
1 => ['level_id' => 2, 'level' => 'Moderate']
2 => ['level_id' => 3, 'level' => 'Challenging'],
3 => ['level_id' => 4, 'level' => 'Formidable']
But for my purposes, this is what I want:
1 => 'Trivial',
2 => 'Moderate',
3 => 'Challenging',
4 => 'Formidable'
(Note that the array keys are the same as the record id).
If the array has more than one additional column, the result will be contained in sub-arrays:
3 => ['level' => 'Challenging', 'description' => 'Foobar'],
4 => ['level' => 'Formidable', 'description' => 'Bazbat']
This is all very trivial, but I wrote this function that I'd like you to review to know if there is a better way to do this in PHP.
The function needs to be generic so it can use any lookup array without having to know the column names.
<?php
// Turn an array into a key=>value pair. Assumes the key is the first item in the sub-array.
public function column_into_keys(array $array): array {
// get the name of the column that contains the record id
$key = key($array[0]);
foreach($array as $row) {
// pop the new key off the top of the array
$id = array_shift($row);
// is there only one item left in the array?
if (count($row) == 1)
// get the first value
$result[$id] = current($row);
else
// get all of the values
$result[$id] = $row;
}
return $result;
} | {
"domain": "codereview.stackexchange",
"id": 44358,
"lm_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, mysql, lookup",
"url": null
} |
php, mysql, lookup
return $result;
}
Answer: Given you are working with PHP, there is no reason to neglect such a feature that already exists in the language.
For example when you query one of the lookup tables for all values,
$data = $pdo->query("SELECT * FROM lookup")->fetchAll(PDO::FETCH_KEY_PAIR);
you get an array like this:
1 => 'Trivial',
2 => 'Moderate',
3 => 'Challenging',
4 => 'Formidable'
all thanks to PDO::FETCH_KEY_PAIR fetch mode.
Of course it works only with PDO, but you are supposed to use this driver anyway. | {
"domain": "codereview.stackexchange",
"id": 44358,
"lm_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, mysql, lookup",
"url": null
} |
react.js, memoization
Title: Improving performance with a react modal where the component runs on every page
Question: I have a simple cookie popup where the component technically runs on every page, giving the user the option to accept all or essential cookies. Once they accept an option, the popup no longer shows. However, I keep wondering whether many of the variables need to be memoised because the CookiePopup component itself renders on every page.
export const CookiePopup = () => {
const { cookieConsentSet, setCookieConsent } = useContext<CookieContextType>(CookieContext);
// note: cookieConsentSet just gets a consent cookie value (so is null or string)
const [modalIsOpen, setIsOpen] = useState<boolean>(false);
const [showMoreInfo, setShowMoreInfo] = useState<boolean>(false);
const btnText = useMemo<string>(() => `${showMoreInfo ? 'Allow Essential' : 'Manage'} Cookies`, [showMoreInfo]);
const descriptiveText = useMemo<string>(
() => (showMoreInfo ? COOKIE_BANNER_MSG_DETAILED : COOKIE_BANNER_MSG_BRIEF),
[showMoreInfo]
);
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
setShowMoreInfo(false);
};
const acceptCookies = () => {
const expiryDate: Date = new Date(new Date().setFullYear(new Date().getFullYear() + 1)); // 1 year from now
document.cookie = `cookieConsent=all; expires=${expiryDate.toUTCString()};`;
setCookieConsent('all');
closeModal();
};
const declineCookies = () => {
const expiryDate: Date = new Date(new Date().setDate(new Date().getDate() + 1)); // expires in 1 day
document.cookie = `cookieConsent=essential; expires=${expiryDate.toUTCString()};`;
setCookieConsent('essential');
closeModal();
};
const manageCookies = () => {
if (!showMoreInfo) {
setShowMoreInfo(true);
return;
}
declineCookies();
}; | {
"domain": "codereview.stackexchange",
"id": 44359,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, memoization",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.