text
stringlengths
1
2.12k
source
dict
rust, game-of-life impl Iterator for NeighborsIter { type Item = Cell; fn next(&mut self) -> Option<Self::Item> { match self.state { 0 => { self.cell.x.decrement(); self.cell.y.decrement() } 1 => { self.cell.y.increment() } 2 => { self.cell.y.increment() } 3 => { self.cell.x.increment() } 4 => { self.cell.x.increment() } 5 => { self.cell.y.decrement() } 6 => { self.cell.y.decrement() } 7 => { self.cell.x.decrement() } _ => { return None; } } self.state += 1; Some(self.cell) } } #[derive(Debug)] struct Board { state: State } impl Board { pub fn new() -> Self { Board { state: [[false; WIDTH]; HEIGHT] } } pub fn from(state: State) -> Self { Board { state } } pub fn next_step(self) -> Board { let mut next_state = [[false; WIDTH]; HEIGHT]; for row in 0..HEIGHT { for col in 0..WIDTH { match self.count_neighbors(Cell::new(row, col)) { 3 => next_state[row][col] = true, 2 if self.state[row][col] => next_state[row][col] = true, _ => {} } } } Board { state: next_state } } fn count_neighbors(&self, cell: Cell) -> u8 { let mut neighbours: u8 = 0; for cell in cell.into_neighbors_iter() { if self.state[cell.x.value][cell.y.value] { neighbours += 1; } } neighbours } } Performance: After benchmarking the performance of the original implementation from the author and my new implementation, it is clear that the original modulus approach yields significantly slower performance on top of being more unreadable. Experiment 1 parameters: Grid - 100x100
{ "domain": "codereview.stackexchange", "id": 43722, "lm_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, game-of-life", "url": null }
rust, game-of-life Experiment 1 parameters: Grid - 100x100 Starting sate - Randomly generated (but same between the two methods) Game steps - 1000 Experiment 1 average execution time: Original implementation: 381.86 ms New implementation: 162.13 ms Experiment 2 parameters: Grid - 10x10 Starting sate - Randomly generated (but same between the two methods) Game steps - 10000 Experiment 2 average execution time: Original implementation: 33.209 ms New implementation: 14.175 ms Additional information: The library used for the benchmarking is criterion. And the raw data can be seen bellow. game-of-life new impl, (100x100), random state, 1000 steps time: [158.70 ms 162.13 ms 166.53 ms] Found 7 outliers among 100 measurements (7.00%) 2 (2.00%) high mild 5 (5.00%) high severe --------------------------------------------------------------------- game-of-life original impl, (100x100), random state, 1000 steps time: [381.63 ms 381.86 ms 382.13 ms] Found 6 outliers among 100 measurements (6.00%) 2 (2.00%) low mild 2 (2.00%) high mild 2 (2.00%) high severe -------------------------------------------------------------------- game-of-life new impl, (10x10), random state, 10000 steps time: [13.847 ms 14.175 ms 14.580 ms] Found 10 outliers among 100 measurements (10.00%) 2 (2.00%) high mild 8 (8.00%) high severe
{ "domain": "codereview.stackexchange", "id": 43722, "lm_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, game-of-life", "url": null }
rust, game-of-life --------------------------------------------------------------------- game-of-life original impl, (10x10), random state, 10000 steps time: [33.176 ms 33.209 ms 33.247 ms] Found 9 outliers among 100 measurements (9.00%) 2 (2.00%) low mild 4 (4.00%) high mild 3 (3.00%) high severe
{ "domain": "codereview.stackexchange", "id": 43722, "lm_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, game-of-life", "url": null }
java, fizzbuzz Title: yet another fizz buzz Question: FizzBuzz is a well known Exercise among programmers, but I wanted to add an aspect called "openClosed" principle (from SOLID) FizzBuzz is a very simple programming task, used in software developer job interviews, to determine whether the job candidate can actually write code. It was invented by Imran Ghory, and popularized by Jeff Atwood. Here is a description of the task: Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. App for running an example public class App{ public static void main(String[] args) { FizzBuzz fizzBuzz = new FizzBuzz(); fizzBuzz.addHandler(new FizzHandler()); fizzBuzz.addHandler(new BuzzHandler()); fizzBuzz.print(100); } } Handler public interface Handler { boolean matches(int number); String getMessage(); } FizzHandler an Handler implementation public class FizzHandler implements Handler { @Override public boolean matches(int number) { return number % 3 == 0; } @Override public String getMessage() { return "Fizz"; } } BuzzHandler an Handler implementation public class BuzzHandler implements Handler { @Override public boolean matches(int number) { return number % 5 == 0; } @Override public String getMessage() { return "Buzz"; } } FizzBuzz public class FizzBuzz { private List<Handler> handlers = new ArrayList<>(); public void print(int countDestination) { IntStream.range(0,countDestination).forEach(this::printFizzBuzz); }
{ "domain": "codereview.stackexchange", "id": 43723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, fizzbuzz", "url": null }
java, fizzbuzz private void printFizzBuzz(int i) { List<Handler> matchingHandler = handlers.stream().filter(h -> h.matches(i)).toList(); String output = matchingHandler.isEmpty()? Integer.toString(i): matchingHandler.stream().map(Handler::getMessage).collect(Collectors.joining()); System.out.println(output); } public void addHandler(Handler handler) { handlers.add(handler); } }
{ "domain": "codereview.stackexchange", "id": 43723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, fizzbuzz", "url": null }
java, fizzbuzz Answer: The handlers combine matching and processing into the same class. Two responsibilities in one module violates single responsibility principle. To me the handlers look like unnecessary decoration for Predicate<Integer> and Supplier<String>. Combining them together, behind a specialized interface, makes reuse and change more complicated. The FizzBuzz class combines the looping functionality and the handler matching. Again two responsibilities. It relies on the fact that the user must register the handlers in a specific order, which cannot be deduced from anything in the API. I would rather see the handlers be associated with a priority or some other way where their execution order is made clear in the registration code. I personally associate handler registration with a map. I don't know if other share this but changing the method name to addLast(Handler) would already make it clear that there is an order. The API does not make it clear that the class also relies on both handlers being executed when they both match. I don't have an API change ready that would rectify this so at least it should be documented in the JavaDoc. The print(int countDestination) gives no clues about the parameter actually defining a range. It should be renamed to printRange(int start, int end). It should also include error checking for start being greater than end. I'm not sure if printing a range should be a feature at all. The FizzBuzz class could just be a Function<Integer, String> so it could be included in stream operations elsewhere. After all, an IntStream is much more versatile than always forcing the user into a "zero to something" range. The handlers always output to System.out which closes the main method to change. There is no way to write the output to, for example, a network socket. The FizzBuzz probably should just produce the data and let some other component decide where it gets written.
{ "domain": "codereview.stackexchange", "id": 43723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, fizzbuzz", "url": null }
c++, c++17, reflection, enum, factory-method Title: Instantiating a C++ class based on an enum value
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method Question: I have a bit of code duplication and trying to figure a better way to reduce it. I'm looking for any suggestions. If this was in Java I could easily use reflection. The code posted is a basic sample but hopefully, gives the idea of the duplication problem I'm having. The application is made up of "events" that get serialised to and from json. An event is never changing so all the fields are const. I have a method that creates a child instance of the event class by just passing the enum like so: std::shared_ptr<Event> Event::createInstance(const EventType eventType) { switch (eventType) { case EVENT_TYPE_SET_MATCH_TYPE: return std::make_shared<Event::SetMatchType>(); case EVENT_TYPE_SET_MATCH_TEAM_PLAYER: return std::make_shared<Event::SetPlayer>(); case EVENT_TYPE_SET_MATCH_TEAM: return std::make_shared<Event::SetTeam>(); case EVENT_TYPE_START_INNINGS: return std::make_shared<Event::StartInnings>(); case EVENT_TYPE_END_INNINGS: return std::make_shared<Event::EndInnings>(); case EVENT_TYPE_START_MATCH: return std::make_shared<Event::StartMatch>(); case EVENT_TYPE_START_OVER: return std::make_shared<Event::StartOver>(); case EVENT_TYPE_END_OVER: return std::make_shared<Event::EndOver>(); case EVENT_TYPE_BALL: return std::make_shared<Event::Ball>(); case EVENT_TYPE_EXTRA_BALL: return std::make_shared<Event::ExtraBall>(); case EVENT_TYPE_PENALTY: return std::make_shared<Event::Penalty>(); case EVENT_TYPE_RETIRE: return std::make_shared<Event::Retire>(); case EVENT_TYPE_RESUME_MATCH: return std::make_shared<Event::ResumeMatch>(); case EVENT_TYPE_END_MATCH: return std::make_shared<Event::EndMatch>(); case EVENT_TYPE_SWAP_BATSMAN:
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method return std::make_shared<Event::EndMatch>(); case EVENT_TYPE_SWAP_BATSMAN: return std::make_shared<Event::SwapBatsman>(); case EVENT_TYPE_NEW_BATSMAN: return std::make_shared<Event::NewBatsman>(); case EVENT_TYPE_NEW_BOWLER: return std::make_shared<Event::NewBowler>(); case EVENT_TYPE_NEW_WICKET_KEEPER: return std::make_shared<Event::NewWicketKeeper>(); case EVENT_TYPE_WICKET: return std::make_shared<Event::Wicket>(); case EVENT_TYPE_UNDO: return std::make_shared<Event::Undo>(); case EVENT_TYPE_AUDIT_ADD: return std::make_shared<Event::AuditAddBall>(); case EVENT_TYPE_AUDIT_REMOVE: return std::make_shared<Event::AuditRemove>(); case EVENT_TYPE_AUDIT_MODIFY: return std::make_shared<Event::AuditModify>(); case EVENT_TYPE_AUDIT_RETIRE_MODIFY: return std::make_shared<Event::AuditModifyRetirement>(); case EVENT_TYPE_ADD_NOTE: return std::make_shared<Event::AddNote>(); case EVENT_TYPE_REMOVE_NOTE: return std::make_shared<Event::RemoveNote>(); case EVENT_TYPE_NEW_CAPTAIN: return std::make_shared<Event::SetCaptain>(); default: break; }
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method return nullptr; } I have another method that creates a child instance of the event class by json: std::shared_ptr<Event> Event::createInstanceFromJson(const Value &serializedJson) { auto member = serializedJson.FindMember("Event.eventType"); if (member == serializedJson.MemberEnd()) { throw std::invalid_argument{"Error..."}; } auto eventType = static_cast<EventType>(member->value.GetInt());
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method switch (eventType) { case EVENT_TYPE_SET_MATCH_TYPE: return std::make_shared<Event::SetMatchType>(serializedJson); case EVENT_TYPE_SET_MATCH_TEAM_PLAYER: return std::make_shared<Event::SetPlayer>(serializedJson); case EVENT_TYPE_SET_MATCH_TEAM: return std::make_shared<Event::SetTeam>(serializedJson); case EVENT_TYPE_START_INNINGS: return std::make_shared<Event::StartInnings>(serializedJson); case EVENT_TYPE_END_INNINGS: return std::make_shared<Event::EndInnings>(serializedJson); case EVENT_TYPE_START_MATCH: return std::make_shared<Event::StartMatch>(serializedJson); case EVENT_TYPE_START_OVER: return std::make_shared<Event::StartOver>(serializedJson); case EVENT_TYPE_END_OVER: return std::make_shared<Event::EndOver>(serializedJson); case EVENT_TYPE_BALL: return std::make_shared<Event::Ball>(serializedJson); case EVENT_TYPE_EXTRA_BALL: return std::make_shared<Event::ExtraBall>(serializedJson); case EVENT_TYPE_PENALTY: return std::make_shared<Event::Penalty>(serializedJson); case EVENT_TYPE_RETIRE: return std::make_shared<Event::Retire>(serializedJson); case EVENT_TYPE_RESUME_MATCH: return std::make_shared<Event::ResumeMatch>(serializedJson); case EVENT_TYPE_END_MATCH: return std::make_shared<Event::EndMatch>(serializedJson); case EVENT_TYPE_SWAP_BATSMAN: return std::make_shared<Event::SwapBatsman>(serializedJson); case EVENT_TYPE_NEW_BATSMAN: return std::make_shared<Event::NewBatsman>(serializedJson); case EVENT_TYPE_NEW_BOWLER: return std::make_shared<Event::NewBowler>(serializedJson); case EVENT_TYPE_NEW_WICKET_KEEPER: return std::make_shared<Event::NewWicketKeeper>(serializedJson);
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method return std::make_shared<Event::NewWicketKeeper>(serializedJson); case EVENT_TYPE_WICKET: return std::make_shared<Event::Wicket>(serializedJson); case EVENT_TYPE_UNDO: return std::make_shared<Event::Undo>(serializedJson); case EVENT_TYPE_AUDIT_ADD: return std::make_shared<Event::AuditAddBall>(serializedJson); case EVENT_TYPE_AUDIT_REMOVE: return std::make_shared<Event::AuditRemove>(serializedJson); case EVENT_TYPE_AUDIT_MODIFY: return std::make_shared<Event::AuditModify>(serializedJson); case EVENT_TYPE_AUDIT_RETIRE_MODIFY: return std::make_shared<Event::AuditModifyRetirement>(serializedJson); case EVENT_TYPE_ADD_NOTE: return std::make_shared<Event::AddNote>(serializedJson); case EVENT_TYPE_REMOVE_NOTE: return std::make_shared<Event::RemoveNote>(serializedJson); case EVENT_TYPE_NEW_CAPTAIN: return std::make_shared<Event::SetCaptain>(serializedJson); default: break; } return nullptr; }
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method I also have a map that stores a static method to each event: static const auto EVENT_TYPE_TO_PRE_CHECK = std::map<EventType, std::function<void()>> { {EVENT_TYPE_SET_MATCH_TYPE, Event::SetMatchType::preCheck}, {EVENT_TYPE_SET_MATCH_TEAM_PLAYER, Event::SetPlayer::preCheck}, {EVENT_TYPE_SET_MATCH_TEAM, Event::SetTeam::preCheck}, {EVENT_TYPE_START_INNINGS, Event::StartInnings::preCheck}, {EVENT_TYPE_END_INNINGS, Event::EndInnings::preCheck}, {EVENT_TYPE_START_MATCH, Event::StartMatch::preCheck}, {EVENT_TYPE_START_OVER, Event::StartOver::preCheck}, {EVENT_TYPE_END_OVER, Event::EndOver::preCheck}, {EVENT_TYPE_BALL, Event::Ball::preCheck}, {EVENT_TYPE_EXTRA_BALL, Event::ExtraBall::preCheck}, {EVENT_TYPE_PENALTY, Event::Penalty::preCheck}, {EVENT_TYPE_RETIRE, Event::Retire::preCheck}, {EVENT_TYPE_RESUME_MATCH, Event::ResumeMatch::preCheck}, {EVENT_TYPE_END_MATCH, Event::EndMatch::preCheck}, {EVENT_TYPE_SWAP_BATSMAN, Event::SwapBatsman::preCheck}, {EVENT_TYPE_NEW_BATSMAN, Event::NewBatsman::preCheck}, {EVENT_TYPE_NEW_BOWLER, Event::NewBowler::preCheck}, {EVENT_TYPE_NEW_WICKET_KEEPER, Event::NewWicketKeeper::preCheck}, {EVENT_TYPE_WICKET, Event::Wicket::preCheck}, {EVENT_TYPE_UNDO, Event::Undo::preCheck}, {EVENT_TYPE_AUDIT_ADD, Event::AuditAddBall::preCheck}, {EVENT_TYPE_AUDIT_REMOVE, Event::AuditRemove::preCheck}, {EVENT_TYPE_AUDIT_MODIFY, Event::AuditModify::preCheck}, {EVENT_TYPE_AUDIT_RETIRE_MODIFY, Event::AuditModifyRetirement::preCheck}, {EVENT_TYPE_ADD_NOTE, Event::AddNote::preCheck}, {EVENT_TYPE_REMOVE_NOTE, Event::RemoveNote::preCheck}, {EVENT_TYPE_NEW_CAPTAIN, Event::SetCaptain::preCheck} }; I am happy to supply more information around this problem if needed.
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method I am happy to supply more information around this problem if needed. Answer: You are suffering from repetition. Repeatedly, and it's mindmeltingly repetitive. What you have is a list of types, which you repeat all over, and the corresponding enum-values. For the sake of simplicity and efficiency, let's assume the enum-values start at 0 and follow consecutively. It's easy to generalize, if you need it. What you need is a way to apply some code (a generic lambda, or its moral equivalent in pre-C++14 code) to all those enum+type pairs. A bit of generic machinery: template <std::size_t Is, class F> static inline void static_for_impl(F&& f, std::index_sequence<Is...>) { (f(std::integral_constant<std::size_t, Is>()), ...); } template <std::size_t N, class F> void static_for(F f) { static_for_impl(f, std::make_index_sequence<N>()); } template <class tuple, class F> void for_all_types(F f) { static_for<std::tuple_size_v<tuple>>([&](auto N){ using T = std::tuple_element_t<N, tuple>; if constexpr (!std::is_same_v<void, T>) f((T*)0, N); }); } template <class R, class tuple, class F> R select_type(F f, std::size_t i) { R r; bool found = false; for_all_types<tuple>([&](auto p, auto N){ if (i == N) { r = f(p); found = true; } }); if (!found) throw std::invalid_argument(); return r; } Some place to store all the types, and only once: using my_type_list = std::tuple<type0, type1, type2, type3, type4, ...>; An example use: template<class... X, class ET> auto Event::createInstance(const ET eventType, X&&... x) { return select_type<std::shared_ptr<Event>, my_type_list>([&](auto p){ return std::make_shared<std::decay_t<decltype(*p)>>(std::forward<X>(x)...); }, (std::size_t)eventType); }
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
c++, c++17, reflection, enum, factory-method The call to functions like classname::preCheck is probably normally best solved with a virtual function, unless you need a normal pointer, or you don't actually have an instance to play with like in your case: template<class F, class ET> auto eventType_to_preCheck(const ET eventType) { return select_type<F*, my_type_list>([](auto p){ F* f = std::decay_t<decltype(*p)>::preCheck; return f; }, (std::size_t)eventType); } // You'll have to supply the exact signature when calling
{ "domain": "codereview.stackexchange", "id": 43724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, reflection, enum, factory-method", "url": null }
haskell, interval Title: Generate varied values of some parameters over a neighboring interval Question: I was recently tasked with creating a function that could generate a "varied" version of some collection of parameters. As in, it should take in a list of parameters, and then vary the value of the first one while leaving the rest fixed -- thus creating some variations. We then move on to the next parameter, and repeat the same process (vary the one we are focusing on, leave other parameters fixed). This continues until we run out of parameters. Parameters are "varied" by looking up an interval of multipliers in a Map, generating num multipliers in that interval, followed by multiplying the parameter by those multipliers to get its varied versions. I tried solving this problem completely from scratch, rather than using some pre-existing libraries. My approach used the following A zipper so I could have a "cursor" to point to the parameter I was currently focusing on and varying Use the state monad to generate some variations based on the current state of the zipper, then shift the cursor,etc. I do think my code feels rather overcomplicated and messy though, so I would like some feedback on how I could have done things better. Further notes: I did use GADTs despite not being very well versed in them. This was because I wanted to impose the Num constraint for my RealInterval datatype. I feel that maybe an Interval typeclass was unnecessary. {-# LANGUAGE GADTs, MultiParamTypeClasses, FunctionalDependencies, BangPatterns #-} {-# LANGUAGE DeriveFunctor, DeriveTraversable, DeriveFoldable #-} import Control.Monad.Trans.State.Lazy import Data.Function import Debug.Trace import qualified Data.Map as M import Data.Maybe import Data.List data Zipper a = Zipper {left :: [a], focus :: a, right :: [a]} deriving (Functor, Traversable, Foldable, Show)
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval fromList :: [a] -> Maybe (Zipper a) fromList [] = Nothing fromList (x:xs) = Just $ Zipper [] x xs
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval toList :: Zipper a -> [a] toList (Zipper l f r) = transfer l (f:r) where transfer [] l = l transfer (x:xs) l = transfer xs (x:l) class Interval i where -- Generate a bunch of values in the interval, ranging from its start to end, with a step size specified by the 2nd argument. range :: (Ord a, Fractional a) => i a -> a -> [a] range i stepSize | stepSize == 0 = [] | otherwise = go seed [] where (trueStart, trueEnd) = endpoints i (incStart, incEnd) = hasEndpoints i next = if trueStart <= trueEnd then subtract stepSize else (+stepSize) prev = if trueStart <= trueEnd then subtract stepSize else (+stepSize) start = if incStart then trueStart else next trueStart end = if incEnd then trueEnd else prev trueEnd seed = if start <= end then end else start go !curr ls | not $ i `has` curr = ls | otherwise = go (prev curr) (curr:ls) -- builds list backwards -- Generate equally spaced values in the interval (as specified by the integer like number. Returns an empty list if negative, for now. linspace :: (Ord b, Fractional b, Integral a) => i b -> a -> [b] linspace i n = range i stepSize where (start, end) = endpoints i stepSize = (end - start) / fromIntegral (n-1) endpoints :: Num a => i a -> (a,a) -- Get the endpoints of the interval (start, end) has :: (Ord a, Num a) => i a -> a -> Bool -- Check for whether a number is within an interval hasEndpoints :: i a -> (Bool, Bool) -- Tells whether each endpoint of the interval is included -- bisect :: Num a => i a -> a -> Maybe (i a, i a) -- Attempts to bisect the interval around the provided value, if possible.
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval data RealInterval a where RealInterval :: Num a => (a, Bool) -> (a, Bool) -> RealInterval a instance Show a => Show (RealInterval a) where show (RealInterval s e) = show s ++ " to " ++ show e -- newtype RealInterval a = RealInterval {getEndpoints :: (Double, Double)} instance Interval RealInterval where endpoints (RealInterval s e) = (fst s, fst e) has i v | prod < 0 = True | prod > 0 = False | otherwise = l == 0 && hs || r == 0 && he where (s, e) = endpoints i (hs, he) = hasEndpoints i l = v - s r = v - e prod = l*r hasEndpoints (RealInterval s e) = (snd s, snd e) shift :: Zipper a -> Maybe (Zipper a) shift (Zipper l f r) = case r of [] -> Nothing (x:xs) -> Just $ Zipper (f:l) x xs varyParams :: (Ord a, Fractional a, Integral b, Interval i) => M.Map a (i a) -> b -> [a] -> [[a]] varyParams multipliers num params = case fromList params of Nothing -> [[]] Just z -> evalState genVar z where variations z = do let f = focus z m <- maybe [] (flip linspace num) (M.lookup f multipliers) pure . toList $ z {focus = m*f} genVar = do z <- get let v = variations z case shift z of Nothing -> pure v Just z -> do put z rest <- genVar pure (v ++ rest) Answer: thanks for the question! This has been an interesting code review for me to do. The author of the code (who I presume is you) seems to clearly possess technical skill in programming, but perhaps is missing knowledge of Haskell idioms. In no particular order, here are some comments:
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval Some of the language extensions you enable are not actually used, like FunctionalDependencies. They are then just clutter and should be removed. If you run ghc with -Wall -Werror, it will tell you about unused extensions I would advise avoiding unqualified wildcard imports like import Data.Maybe. With more than one such import, it becomes difficult for readers who aren't using IDEs (like me!) to know where imported values are coming from. Prefer either import qualified Data.Maybe as Maybe or import Data.Maybe (maybe, fromMaybe{-, so on -}) You note that you've enabled GADTs in order to include the Num constraint in your RealInterval constructor. I would generally advice against doing this. For any constructor with a constraint (such as RealInterval), we can remove the constraint and move it to callsites. This can be annoying, but means that the datatype is more flexible. What if you want a RealInterval of something which is not a Num (for instance, Int)? I can't remember where I heard this, but I believe that originally Haskell allowed constraints in types without requiring the GADTs language extension. It was decided that it was better to disallow this, and the feature was removed. Formatting: your formatting has a lot of unnecessary indentation. Perhaps this is intentional? If not, you can indent less as follows: Replace do, case, and where clauses that look like do a b case x of y -> ... z -> ... where x = ... y = ... respectively with do a b case x of y -> ... z -> ... where x = ... y = ... Formatting: more generally, your formatting is just very strange for Haskell code. This is not necessarily bad. It's up to you whether or not you want to conform to existing standards. If you do, I would recommend looking up a format guide or using an auto-formatter. Your implementation of has is pretty cool! In particular, I like the prod trick
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval Your implementation of has is pretty cool! In particular, I like the prod trick The range function can be implemented more simply as range :: (Interval i, Ord a, Fractional a) => i a -> a -> [a] range i 0 = [] range i stepSize = reverse $ takeWhile (>= x0') $ iterate (subtract stepSize) xf' where (x0, xf) = endpoints i (h0, hf) = hasEndpoints i x0' = if h0 then x0 else x0 + stepSize xf' = if hf then xf else xf - stepSize Generally, your code makes me think you are coming from an imperative language. Idiomatic Haskell usually reads more as a description of what you want from the program rather than a sequence of steps instructing how to get it. For range particularly: "I want the reverse of the prefix greater than x0' of a list constructed by repeated applications of subtract stepSize to xf' This can be a strange and difficult transition to make. My only recommendation is to keep writing Haskell, and, in particular, read others' Haskell. You're using where clauses in implementations of function methods. I didn't know you can do that! Neat. You ask if the Interval type class is unnecessary. The answer is... maybe. If the only instance you're using is RealInterval then, yes, the class is unnecessary, because you can replace all uses of types i implementing Interval with uses of RealInterval.
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
haskell, interval On the topic of typeclasses: typically* when writing a typeclass, one defines least number of methods require in order to encapsulate all desired functionality. Other operations, which are defined in terms of these methods, are not included in the typeclass. In your case, the interval class only needs endpoints and hasEndpoints: all three of range, has, and linspace can be placed outside the typeclass, because they are implemented in terms of endpoints and hasEndpoints. Note that you'll need to add an Interval i => constraint to each. * The only reason I know of to violate this is to allow typeclass instances to provide a more efficient implementation of an operation Sigh ... I had a lot more to say, but I had to reboot my computer and my work on this question got lost. I hope what I've said so far has been useful, and I'll offer one more thing: Conceptually, the structure of the varyParams function is this: we have some things (ie, a list of a) and for each thing we have a number of ways we can vary it. A "variation of an a" can be expressed as an a -> a, and "a number of ways to vary an a" is then a [a -> a]. See if you can write a function vary :: (a -> [a -> a]) -> [a] -> [[a]] Which accepts a function f :: a -> [a -> a] and list xs :: [a]. The function f gives for each a a number of ways to vary it, and the list xs gives a bunch of as. What is produced are the variations like you have in your original code. This vary function exposes the structure of varyParams that I was talking about before. This should make the code more readable. Plus, generalizing is fun! (or at least I think so). If you can write vary, you should be able to also use it to re-write varyParams. That is what I had done; sorry that I lost it. Edit: Oh, yeah! One last thing. Cheers to your use of Zippers! They are so cool.
{ "domain": "codereview.stackexchange", "id": 43725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, interval", "url": null }
python, parsing, web-scraping Title: Parsing: Сollecting data from a book site Question: A task: Сollect data from the site in the following format: book; user; book_rating; comment_rating; publication_date; comment For one book at once several pages of reviews (or more than one). Problem: One request to the site can be sent once every 0.25 seconds, so async requests don't work. Question: Can data collection be accelerated? Сode structure: Link to the page with the book from Top_link.txt → Get links to pages with reviews of this book (function score_link) → Get each review in a loop (function score_user) → Collect data from the review (function score_user) Code: import os import requests from fake_useragent import UserAgent from selectolax.lexbor import LexborHTMLParser from time import sleep from tqdm import tqdm # The function concatenates the current directory and the file name def path_to_file(name): return os.path.join(os.path.dirname(__file__), name) # Read links to sites from top_link.txt with open(path_to_file('top_link.txt'), 'r', encoding="utf-8") as f: text = f.read() book_id = [int(element.strip("'{}")) for element in text.split(", ")] sites = [f"https://fantlab.ru/work{i}" for i in sorted(book_id)] # Activate UserAgent useragent = UserAgent() # Get the html page and request response status. def get_html(url): headers = {"Accept": "*/*", "User-Agent": useragent.random} # Establish a permanent connection session = requests.Session() session.headers = headers adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) session.mount('http://', ​​adapter) resp = requests.get(url, headers=headers) html = resp.text return html, resp.status_code # Get links to review pages def score_link(html, url): tree = LexborHTMLParser(html) tree_users_list = tree.css_first(r'span.page-links')
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping link_list = [] # Users without this element have no reviews if tree_users_list is not None: tree_users = tree_users_list.css(r'a') for user in tree_users: # Link to comment page link = url + user.attributes['href'] link_list.append(link) return link_list else: link_list.append(url) return link_list # Get user feedback def score_user(links): score_list = [] # Follow links to review pages for url in links: html, status_code = get_html(url) tree = LexborHTMLParser(html) # Check server response if status_code == 200: score = tree.css("div.responses-list > div.response-item") if score is not None: # Go through reviews for user in score: book_link = url.split('?')[0] user_id = user.css_first( r'p.response-autor-info>b>a').attributes['href'] book_rating = user.css_first( r'div.clearfix>div.response-autor-mark>b>span').text() comment_rating = user.css_first( r'div.response-votetab>span:nth-of-type(2)').text() data_score = user.css_first( r'p.response-autor-info>span').attributes['content'] body_score = user.css_first( r'div.response-body-home').text().replace('\n', ' ') score_list.append( f'{book_link};{user_id};{book_rating};{comment_rating};{data_score};{body_score}\n' ) elif status_code == 429: sleep(1) print('ERROE_429:', url) sleep(0.25) return score_list
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping sleep(0.25) return score_list with open(path_to_file("user.csv"), "a+", encoding='utf-8') as file: file.write( "book; user; book_rating; rating_rating; publication_date; comment \n" ) for url in tqdm(sites): html, status_code = get_html(url) line = ''.join(score_user(score_link(html, url))) if line is not None: file.write(line) sleep(0.5) Answer: See my comment under your post for why your question can hardly be answered accurately right now. What I like about your code: Your main loop is nice and short, well done! You have a couple of functions that do one thing -- good! You use libraries appropriately! Here's some general advice.
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping You import os to resolve the absolute path of top_link.txt, which is in the same path as your script. Assuming the working directory is the one where your script resides, this is unnecessary. You can remove path_to_file and import os. This will speed up the startup of your script. You have function definitions and code in between each other. Create a main function with a if __name__ == "__main__" guard. I often place that at the top of all the function definitions, below imports and constants. That way I see the entry-point to your script easily. Since you ask for performance: You have a sleep(0.5) at the very bottom of the script, outside of the for-loop above it. I cannot think of a reason where that's necessary except if you start your script by double-clicking and want to wait half a second between main routine is finished and the window closing. You user.csv in read+append mode. Then you write a header. A header in CSV only makes sense in the first line of the file. That would mean you write a new file, otherwise you duplicate the header. I would recommend checking if the file exists with pathlib.Path (os.path works, but is not pythonic). Also, you never actually read from the file, so a mode is fine. If you use pathlib.Path, you can simplify reading top_link.txt to one simple function call that comes with Path. The beginning of main is there to create sites. After this is generated, you don't need text and book_id anymore. That is perfect to create a function. if line is not None: this can never be the case, since "".join([]) is a str of length 0. So you probably want to check that you have a non-empty string. Then you can just write if line:. The same argument goes for tree.css_first. From the signature of that function it does not look like it could return None, but I'm not familiar with the library to be sure here.
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping You have three different sleep times in your code, namely 0.25, 0.5, and 1. You only explained where one of these come from. This is an anti-pattern called "magic numbers". Replace them by constants with a good name. Your code had two ZWSPs (zero-width spaces) in it, which upset part of my IDE. I have removed them. Now to the meat of the script: score_user has 5 levels of indentation. That is very hard to read, and often a sign of convoluted code. Especially if you have nested ifs, you can reverse the logic of the conditions and continue the loop or return from the function early. That makes it clear what's happening in these cases without having to read the body of the big loop. I refactored that in a slightly unconventional way. I first checked if the status code is not 200 or 429 and handled that. Then I handled the case of 429. Then the rest of the function handles 200. Calculating the individual values of score_list looks fairly complex, and therefore deserves its own function.
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping If you apply these recommendations, the code looks like this. from pathlib import Path from typing import List import requests from requests import adapters from fake_useragent import UserAgent from selectolax.lexbor import LexborHTMLParser from time import sleep from tqdm import tqdm RATE_LIMIT_DELAY = 1 MINIMUM_DELAY_BETWEEN_REQUESTS = 0.25 USER_CSV_PATH = Path("user.csv") TOP_LINK_PATH = Path("top_link.txt") CSV_HEADER = "book; user; book_rating; rating_rating; publication_date; comment \n" # Activate UserAgent useragent = UserAgent() def main(): sites = generate_sites_from_file(TOP_LINK_PATH) if not USER_CSV_PATH.exists(): create_file_with_header(USER_CSV_PATH) with open("user.csv", "a", encoding="utf-8") as file: for url in tqdm(sites): html, status_code = get_html(url) line = "".join(score_user(score_link(html, url))) if line: file.write(line) # Get the html page and request response status. def get_html(url): headers = {"Accept": "*/*", "User-Agent": useragent.random} # Establish a permanent connection session = requests.Session() session.headers = headers adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) session.mount("http://", adapter) resp = requests.get(url, headers=headers) html = resp.text return html, resp.status_code # Get links to review pages def score_link(html, url): tree = LexborHTMLParser(html) tree_users_list = tree.css_first(r"span.page-links") link_list = [] # Users without this element have no reviews if tree_users_list is not None: tree_users = tree_users_list.css(r"a") for user in tree_users: # Link to comment page link = url + user.attributes["href"] link_list.append(link) return link_list else: link_list.append(url) return link_list
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
python, parsing, web-scraping # Get user feedback def score_user(links): score_list = [] # Follow links to review pages for url in links: html, status_code = get_html(url) tree = LexborHTMLParser(html) # Check server response if status_code != 200: print(f'ERROR_{status_code}:{url}') sleep(RATE_LIMIT_DELAY) continue # now status_code must be 200 score = tree.css("div.responses-list > div.response-item") if score is not None: # Go through reviews for user in score: score_list.append(generate_score_list_entry(url, user)) sleep(MINIMUM_DELAY_BETWEEN_REQUESTS) return score_list def generate_score_list_entry(url, user): book_link = url.split("?")[0] user_id = user.css_first(r"p.response-autor-info>b>a").attributes["href"] book_rating = user.css_first(r"div.clearfix>div.response-autor-mark>b>span").text() comment_rating = user.css_first(r"div.response-votetab>span:nth-of-type(2)").text() data_score = user.css_first(r"p.response-autor-info>span").attributes["content"] body_score = user.css_first(r"div.response-body-home").text().replace("\n", " ") value = f"{book_link};{user_id};{book_rating};{comment_rating};{data_score};{body_score}\n" return value def create_file_with_header(path: Path) -> None: with open(path, "w") as fd: fd.write(CSV_HEADER) def generate_sites_from_file(path: Path) -> List[str]: text = path.read_text() book_id = [int(element.strip("'{}")) for element in text.split(", ")] return [f"https://fantlab.ru/work{i}" for i in sorted(book_id)] if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 43726, "lm_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, parsing, web-scraping", "url": null }
c++, beginner, fizzbuzz Title: Sum of FizzBuzz numbers with modern C++ Question: I am learning to write more modern C++, since my C++ is from the 1990s (I'm a C# programmer). I need to get used to the STL algorithms and such. So I tried some kata, summing up numbers in a given range that are divisible by 3 or 5, using new C++11/14/17 stuff. I know that it can be solved mathematically in O(1), but this question is not about performance. You can of course make performance suggestions, but not the O(1) mathematical complete rewrite, please. First of all, let me say I am quite happy with the main method. That's sort of how I imagined it shall look like. It uses an iterator and an STL algorithm to sum it up. int main() { MultiplesOf3Or5Iterator<1,999> numberGenerator; std::cout << std::accumulate(numberGenerator.begin(), numberGenerator.end(), 0L) << '\n'; } I took the idea of an iterator from Cpp Reference, but I got some warnings for the code there, which guided me into a direction of not inheriting from std::iterator. So this is what I came up with. It contains comments of where I'm still not happy with the result. template<long FROM, long TO> class MultiplesOf3Or5Iterator { public: class iterator { public: using iterator_category = std::input_iterator_tag; using value_type = long; using difference_type = long; using pointer = const long*; using reference = long; public: explicit iterator(long _num = 0) : num(_num) { // I really don't like the cast in here direction = isForward() ? static_cast<std::function<long(long, long)>>(std::plus()) : std::minus(); ++(*this); // start with the first valid number } iterator& operator++() {
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz do { num = direction(num, 1); } while (!isDivisable()); return *this; } iterator operator++(int) { ++(*this); iterator retval = *this; return retval; } bool operator==(iterator other) const { return num == other.num; } bool operator!=(iterator other) const { return !(*this == other); } reference operator*() const { return num; } private: long num = FROM; std::function<long(long, long)> direction; std::vector<long> const divisors{ 3,5 }; // no need to make these configurable at the moment bool isDivisable() const { // While this is a "modern" style foreach loop, I don't really like this part. // I think there should be a more expressive style for (long divisor : divisors) { if (num % divisor == 0) { return true; } } return false; } bool isForward() const { return TO >= FROM; } }; iterator begin() { return iterator(FROM); } iterator end() { return iterator(TO); } }; And yeah, honestly, that's quite a bunch of code just to have some numbers which are divisible by 3 or 5. It kinda violates the KISS and YAGNI principle. What have I tried? I looked up the Forum of the source of the kata, but the C++ answers there are either optimized or written in the 1990 old C-like style, not using any modern C++ stuff (which is ok, but not what I want to learn right now). I looked up several Fizzbuzz C++ questions here on Code Review, but none seems to use an iterator approach like mine.
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz Answer: Design review Not bad! There is a little bit of conceptual confusion (you have an iterator that has an iterator?), and perhaps a little bit of over-engineering, but generally this design is quite good. I really like the ergonomics of it—your main() function is indeed beautiful; that’s what good C++ code looks like. Before I review your design, let me show you roughly what I might have done had I chosen to do the same project. This is because what I would have done is almost identical what you would have done, but for a few divergent design decisions that I want to highlight, and it’s quicker to illustrate those few differences rather than explain them. Right, so if I were doing this—making a custom iterator that returns the FizzBuzz magic numbers (numbers divisible by 3 and 5)—I would start with just the iterator, like so: // Instead of assuming long, I'm leaving the type as a template parameter. // I'm also taking a predicate as a template parameter, which increases the // flexibility of the type. To duplicate the behaviour of your iterator, you // would use this predicate: // template <typename T> // struct fizzbuzz_predicate // { // constexpr auto operator()(T const& v) const noexcept // { // return ((v % 3) == 0) or ((v % 5) == 0); // } // }; // We'll name it later. template <typename T, typename Predicate> class ???_iterator { T _current; public: // Note: I'm making this iterator bidirectional, not just input. Input // is too restrictive. We *might* go all the way to random access... // but... well, we'll discuss it later. using iterator_category = std::bidirectional_iterator_tag; using value_type = T; // Could use long here, but ptrdiff_t is the "correct" type (by default). using difference_type = std::ptrdiff_t; // Iterators need a default constructor, but it can leave the iterator // in an unspecified state. constexpr ???_iterator() = default;
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz // !!! This is not a good constructor to have as part of the public // interface... but bear with it for now constexpr explicit ???_iterator(T v) : _current{std::move(v)} {} // Required for all iterators: constexpr auto operator*() const noexcept { return _current; } constexpr auto operator++() -> ???_iterator& { auto const predicate = Predicate{}; do { // Note that I'm not supporting automatically decrementing. I'll // explain why later. ++_current; } while (not predicate(_current)); return *this; } constexpr auto operator++(int) -> ???_iterator { auto temp = *this; ++(*this); return temp; } // Required for bidi iterators: constexpr auto operator--() -> ???_iterator& { auto const predicate = Predicate{}; do { --_current; } while (not predicate(_current)); return *this; } constexpr auto operator--(int) -> ???_iterator { auto temp = *this; --(*this); return temp; } // In C++20, this is all you need. operator!= is automatically synthesized. constexpr auto operator==(???_iterator const&) const noexcept -> bool = default; }; That’s a very rough first pass of the iterator I’d make to solve this problem. So, first, you’ll note that I made it bidirectional, rather than just an input iterator. In your case, I would say that at the very minimum, it should be a forward iterator, not an input iterator. “Input iterator” means that you can’t expect to get the same sequence if you run the iterator twice. In other words: auto numberGenerator = MultiplesOf3Or5Iterator<1, 999>{}; auto first = numberGenerator.begin(); auto last = numberGenerator.end(); std::ranges::for_each(first, last, [](auto&& n) { std::cout << n << ' '; }
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz std::ranges::for_each(first, last, [](auto&& n) { std::cout << n << ' '; } // If the iterator is an input iterator, then we should expect a different // result from what we got in the line above. // If the iterator is a forward iterator, then we should get the same result. std::ranges::for_each(first, last, [](auto&& n) { std::cout << n << ' '; }
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz Given that you would expect to get the same sequence for both runs through it, this means that it should be a forward iterator, not an input iterator. I actually went a little further, and made it a bidirectional iterator. This was a design descision, and one that comes with consequences. Bidirectional iterators are much more useful than forward iterators… but the cost is that it makes it much more difficult to implement automatic decrementing. You see, your iterator automatically detects when FROM is greater than TO, and if so, uses std::minus instead of std::plus. That’s cool, but it only really works if you allow one directional traversal. If you want bidirectional traversal, then you need to use two function objects: you need std::plus and std::minus, and you need to swap them around depending on the direction. That’s a lot more complexity. See, I could do that… but… there’s a very good reason not to put too much complexity into a single “thing”, and that is that you can always externalize that complexity and reuse it. Let me put that in simple English: you could do what you did, and build an iterator that is smart enough to go both ways… or… you could build a much simpler iterator, and take advantage of std::ranges::reverse_view. And the latter, in my opinion, is what modern C++ is really about. So you see, you could either massively complicate your iterator to allow going downward from 100 to 1 as auto v = MultiplesOf3Or5Iterator<100, 1>{};… or… you could make a simple iterator, and just do auto v = MultiplesOf3Or5Iterator<1, 100>{} | std::ranges::views::reverse;. (Or you could use reverse iterators; you have options!) For me, the latter makes more sense. The next design decision I made was to make the value type const. This seems like the only sensible choice. If the value type isn’t const, then you could do: auto numberGenerator = MultiplesOf3Or5Iterator<1, 999>{}; auto first = numberGenerator.begin(); *first = 1234; // <- what?
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz *first = 1234; // <- what? Now, having made that iterator, the next thing I’d do is make a view out of it. That’s actually what MultiplesOf3Or5Iterator is. It’s not an iterator, it’s a view. A view is a range that doesn’t hold any data, but merely provides iterators that give a view of something. (A range that holds data is a container, like std::vector.) In your case, MultiplesOf3Or5Iterator is a view that provides iterators that gives a view of a sequence of numbers that satisfy the FizzBuzz rule (divisible by 3 or 5). So, here’s how I’d write that view: template <typename T, typename Predicate> class fizzbuzz_view : public std::ranges::view_interface<fizzbuzz_view<T, Predicate>> { // Doesn't need to be public! class iterator { T _current; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = std::add_const_t<T>; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; constexpr iterator() = default; // Could now make this constructor private, and make the view a // friend, so that only the view can construct iterators. constexpr explicit iterator(T v) : _current{std::move(v)} {} constexpr auto operator*() const noexcept -> reference { return _current; } constexpr auto operator++() -> ???_iterator& { auto const predicate = Predicate{}; do { ++_current; } while (not predicate(_current)); return *this; } constexpr auto operator++(int) -> ???_iterator { auto temp = *this; ++(*this); return temp; } constexpr auto operator--() -> ???_iterator& { auto const predicate = Predicate{}; do { --_current; } while (not predicate(_current));
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz return *this; } constexpr auto operator--(int) -> ???_iterator { auto temp = *this; --(*this); return temp; } // In C++20, this is all you need. operator!= is automatically synthesized. constexpr auto operator==(???_iterator const&) const noexcept -> bool = default; }; T _start; T _finish; public: constexpr fizzbuzz_view(T s, T f) : _start{std::move(s)} , _finish{std::move(f)} { // Might want to verify that start <= finish. } constexpr auto begin() const { return iterator{_start}; } constexpr auto end() const { return iterator{_finish}; } }; That’s basically all you need. With that, you could do: // Print all fizzbuzz values between 1 and 99: std::ranges::for_each(fizzbuzz_view{1, 99}, [](auto&& v) { std::cout << v << '\n'; }); // Print the first 3 fizzbuzz values between 1 and 99, in reverse order: for (auto&& v : fizzbuzz_view{1, 99} | std::ranges::views::take{3} | std::ranges::views::revesre) std::cout << v << '\n'; // Your example: auto const v = fizzbuzz_view{1L, 999L}; auto const sum = std::accumulate(std::ranges::begin(v), std::ranges::end(v), 0L); … and more. I would suggest you research ranges and views. That’s what you are skirting around, and that is what the future of C++ looks like. You are… almost… there, which is why your code is already very good modern C++. But as you can see, going 100% of the way to ranges and views comes with incredible benefits. And those benefits will only get better. This is the direction future C++ is going in. So, in summary: You have some conceptual confusion. You don’t have an iterator with an iterator, you have a view with an iterator. Getting the concepts and terminology correct is important, because it helps you realize how to integrate your type with the standard library, and other people’s libraries.
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz Your iterator’s category should be at least forward iterator. However, since it is so trivial to implement decrementing, you might as well make it bidirectional as well. You have made your iterator intrinsically bidirectional—meaning that ++ will make it go forward or backward. That’s not wrong… however… I would suggest simplifying, and making ++ only go forward, while adding -- to go backward. Surprisingly, this simplification makes the iterator more flexible, because now it will work with reverse views (and reverse iterators), so you can integrate so much more easily with other stuff. Code review template<long FROM, long TO> First, you should never use ALL_CAPS identifiers. By convention ALL_CAPS is reserved for macros. Now, there is really no reason to hard-code long as the value type. There’s no reason to prevent users from using, say, int or unsigned long long. The easiest way to increase flexibility is to simply do: template <auto From, auto To> Of course, you want to make sure that the two types are the same, so: template <auto From, decltype(From) To> // or: template <auto From, auto To> requires std::same_as<From, To> But it might be a good idea to constrain the type, because it has to be an integer (otherwise you can’t use operator%), so: template <std::integral auto From, decltype(From) To>
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz However… I would suggest that encoding the from and to limits in the type isn’t a good idea at all. You see, when you encode the limits in the type, you are telling me that MultiplesOf3Or5Iterator<1, 10> and MultiplesOf3Or5Iterator<2, 20> are completely different “things”. You are telling me that a function that iterates over the first type must be a completely different function than one that iterates over the second type. But that’s… silly. There’s no reason a single function couldn’t iterate over a fizzbuzz range from 1 to 10 or 2 to 20. I get that in ages past, the only way to encode compile-time constants was to use template parameters like that. But these days, that’s no longer necessary. So I would suggest simply doing: template <std::integral T> class MultiplesOf3Or5View // <- note: view, not iterator Now the view class really only needs begin() and end(). Even iterator doesn’t need to be part of the public interface, but there’s no harm. However, if you’re no longer putting the limits in the type, you will probably need a constructor to set those limits, so your view class will probably look like: template <std::integral T> class MultiplesOf3Or5View { T _start; T _finish; public: constexpr MultiplesOf3Or5View(T start, T finish) : _start{std::move(start)} , _finish{std::move(finish)} { // Might want to verify that start <= finish } constexpr auto begin() const { /* ... */ } constexpr auto end() const { /* ... */ } }; Now, into iterator. I already mentioned that the category should be at least fowrard iterator. I would also drop pointer and reference; you don’t need them. I’m going to skip down to the member variables, and come back to the rest of the class: long num = FROM; std::function<long(long, long)> direction; std::vector<long> const divisors{ 3,5 }; // no need to make these configurable at the moment
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz Iterators should be lightweight, and in particular should be O(1) copyable. Neither std::function nor std::vector are lightweight, and std::vector in particular has O(n) copy. It’s good to make your stuff flexible, but there is such a thing as too flexible. There is no reason for the divisors to be run-time configurable, is there? Even if there were, it seems silly to truck around a copy of all the divisors with every iterator. Wouldn’t it make more sense to have a single copy in the view class, and iterators just have a reference to it? (That would mean the view would have to outlive the iterators… but, I mean, that’s true for every other view or container, so it’s not really a big deal.) I would also throw out the direction member altogether. Again, there is such a thing as too much flexibility. Your type has literally two directions, and the direction is decided internally; it’s not user-configurable (a user can’t decide to use std::multiplies instead of std::plus, for example). There is no need to hold a std::function to some arbitrary increment function. Finally, using the member initializer = FROM seems like a good idea, but it is thwarted by the constructor. I’ll get back to that. So I would say your member variables just need to be: long num = FROM; bool direction = true; std::vector<long> const* p_divisors = nullptr; // or you can have a // default static // vector of divisors // to initialize to // (but you don't need // one, because a // default-constructed // iterator should // never be
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz // never be // incremented)
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz That will make your iterators much cheaper to move and copy. So now let’s get back to the constructors: explicit iterator(long _num = 0) : num(_num) { // I really don't like the cast in here direction = isForward() ? static_cast<std::function<long(long, long)>>(std::plus()) : std::minus(); ++(*this); // start with the first valid number } I am really not a fan of default arguments, and in this case your use of them has made you shoot yourself in the foot. Because of the member initializer, you want num to default initialize to FROM, which makes sense. But because you have done long _num = 0 in the argument list here, you’ve outsmarted yourself. The solution is simple: don’t use default arguments. You want two constructors, one that takes no arguments, and one that takes an initializer. That’s two constructors. constexpr iterator() noexcept = default; constexpr iterator(long _num) : num(num) , direction(isForward()) , p_divisors(/* ??? */) { // ??? } But there’s a snag. What to put in the initializer for the divisors? Well, clearly, you need another argument. So: // In the view template <std::integral T> class MultiplesOf3Or5View { T _start; T _finish; std::vector<T> _divisors; public: constexpr MultiplesOf3Or5View(T start, T finish) : _start{std::move(start)} , _finish{std::move(finish)} , _divisors{T(3), T(5)} {} constexpr auto begin() const { return iterator{_start, _start <= _finish, _divisors}; } constexpr auto end() const { /* ... */ } }; // In the iterator class iterator { T _num = {}; bool _direction = true; std::vector<T> const* _p_divisors = nullptr; public: constexpr iterator() = default;
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz public: constexpr iterator() = default; constexpr iterator(T n, bool direction, std::vector<T> const& divisors) : _num{n} , _direction{direction} , _p_divisors{&divisors} {} }; There’s one more issue with the constructor. Let me bring it back: explicit iterator(long _num = 0) : num(_num) { // I really don't like the cast in here direction = isForward() ? static_cast<std::function<long(long, long)>>(std::plus()) : std::minus(); ++(*this); // start with the first valid number } You have a bug. It’s that last line. You are not wrong to want to make sure the iterator starts on a valid number. Let’s assume the divisors are 3 and 5 (the standard FizzBuzz numbers). If you start with FROM as 1… well, you want to immediately advance to 3. That makes sense. But… what if you start with FROM as 3? It’s already valid. Yet… you immediately increment it. What would you expect from the following: auto view = MultiplesOf3Or5Iterator<1, 10>{}; for (auto p = view.begin(); p != view.end(); ++p) std::cout << *p << ' '; Personally, I would expect: 3 5 9 Now what would you expect from: auto view = MultiplesOf3Or5Iterator<3, 10>{}; for (auto p = view.begin(); p != view.end(); ++p) std::cout << *p << ' '; Personally, I would expect the same as above, not: 5 9 On to the incrementer: iterator& operator++() { do { num = direction(num, 1); } while (!isDivisable()); return *this; } As I mentioned above, requiring a completely arbitrary direction function is a bit much. You’re going to go forward and backward. What else is there? Up and down? Ana and kata? So all you need is just _direction ? ++_num : --_num;. bool operator==(iterator other) const { return num == other.num; } bool operator!=(iterator other) const { return !(*this == other); }
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz As of C++20, you don’t need the second function. It will be auto-synthesized. bool isDivisable() const { // While this is a "modern" style foreach loop, I don't really like this part. // I think there should be a more expressive style for (long divisor : divisors) { if (num % divisor == 0) { return true; } } return false; } You are quite right that this loop is not exactly great. You should generally avoid for loops altogether in modern C++. In this case, what you want is probably std::ranges::any_of(). So: constexpr bool isDivisable() const { return std::ranges::any_of( *_divisors, [_num](auto& n) { return _num % n; } ); } Or, in English: return true if any of the divisors are evenly divisible into _num. Suggested future directions As I said, what you have now is already very good, modern-looking C++. You could pretty much leave what you have as-is, and it would be perfectly usable in modern code. But there are ways you could make your code even more powerful, even more flexible, and even more integrated with modern C++ paradigms. I would suggest starting from a high-level API view, and asking how users might want to construct FizzBuzz views. In my opinion (and, from here on out, it’s all opinion), there are basically 4 ways: A simple range: fizzbuzz_view{1, 20}, generates 3, 5, 9, 10, 12, 15, 18. A simple range, with adjustible divisors: fizzbuzz_view{1, 20, {3, 8}}, generates 3, 8, 9, 12, 15, 16, 18. An open range: fizzbuzz_view{7}, generates 9, 10, 12, 15, 18, 20, 21, … (on to infinity). An open range, with adjustible divisors: fizzbuzz_view{7, {3, 8}}, generates 8, 9, 12, 15, 16, 18, 20, 21, … (on to infinity).
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
c++, beginner, fizzbuzz The open ranges should use std::unreachable_sentinel as the end iterator. (See std::ranges::iota_view for inspiration.) I would also suggest using compile-time argument deduction to determine the type of the number, with the ability to override. So: Usage Number type fizzbuzz_view{1, 10} int fizzbuzz_view{1uL, 10uL} unsigned long fizzbuzz_view<long>{1, 10} long fizzbuzz_view{1} int fizzbuzz_view{1uL} unsigned long fizzbuzz_view<long>{1} long fizzbuzz_view{1, 10L} <compile-time error> fizzbuzz_view<long>{1, 10L} long I would also suggest exploring some gotchas and corner cases: What happens if the starting value is valid? (Your code currently skips past it.) What happens if the starting value is not valid? (Should you accept what the user has given you as the first value, or skip past it immediately to the first valid value?) What happens if the stopping value is valid? (Should it be counted? Or not?) What happens if there are no more valid values (before overflow)? If you do prevent overflow for signed types (which would make sense; signed overflow is UB), should you also prevent it for unsigned types (unsigned overflow is not UB, it wraps, and some algorithms count on that)? Finally, just for the sake of completeness, I should point out that what you’re doing is already supported by the standard components: auto main() -> int { auto const is_fizzbuzz_number = [](auto n) { return ((n % 3) == 0) or ((n % 5) == 0); }; auto view = std::ranges::views::iota(1L, 999L) | std::ranges::views::filter(is_fizzbuzz_number); std::cout << std::accumulate(view.begin(), view.end(), 0L) << '\n'; } Because std::accumulate() still requires iterators, we can’t write the above as a single line… but if/when it ever accepts ranges, then the whole body of main() above could be a one-liner.
{ "domain": "codereview.stackexchange", "id": 43727, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, fizzbuzz", "url": null }
sql, bash, nosql Title: Change query strings with a Bash script Question: The following script changes start and end dates of several queries saved as files in the folder /app/queries. It is used by executing the script and passing two date strings as arguments, for example: ./config_query.sh 2022-03-28 2022-03-30 This would change all start dates of all queries in the folder /app/queries with the first parameter and all end dates with the second parameter. I would like to get some feedback concerning the readability of the script. Especially the sed commands are very hard to read, which makes the script hard to maintain and extend. Is there a better way to change the start and end dates of the queries? This is the script: #!/usr/bin/env bash #: Title : config_query.sh #: Date : 2022-04-06 #: Version : 1.0 #: Description : Change start and end dates of queries to values of parameters $1 and $2. #: Options : None # Note: The script assumes that both date strings are valid dates in format YYYY-mm-dd. # Date format validation is performed by the script. # Date value validation is not performed by the script, i.e. valid dates have to be passed to generate consistent queries. ROOT="/app" QUERIES="${ROOT}/queries" arr=( "${QUERIES}/leads.flux" "${QUERIES}/subs.flux" "${QUERIES}/gads.sql" "${QUERIES}/ms.sql" "${QUERIES}/li.sql" ) # Check number of arguments passed to script: if [ "$#" -ne 2 ]; then echo "Illegal number of arguments. Program expects two date strings (YYYY-mm-dd)." exit $? fi START_DATE=$1 END_DATE=$2 # Check if start and end are formatted correctly: for date in $START_DATE $END_DATE do format="^[0-9]{4}-[0-9]{2}-[0-9]{2}$" if ! [[ $date =~ $format ]] then echo "Date $date is incorrectly formatted (not YYYY-mm-dd)." exit $? fi done START_DATE_DECR=$(date '+%Y-%m-%d' -d "$START_DATE - 1 day") START_DATE_INCR=$(date '+%Y-%m-%d' -d "$START_DATE + 1 day") END_DATE_INCR=$(date '+%Y-%m-%d' -d "$END_DATE + 1 day")
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql # Replaces 'start' and 'stop' in Influx leads query: sed -i -E "s/start: .{4}-.{2}-.{2}T00:00:00.000Z, stop: .{4}-.{2}-.{2}/start: ${START_DATE}T00:00:00.000Z, stop: ${END_DATE}/g" "${arr[0]}" # Replaces 'start' and 'stop' in Influx subs query: sed -i -E "s/start: .{4}-.{2}-.{2}T00:00:00.000Z, stop: .{4}-.{2}-.{2}/start: ${START_DATE_DECR}T00:00:00.000Z, stop: ${END_DATE_INCR}/g" "${arr[1]}" sed -i -E "s/start: .{4}-.{2}-.{2}T00:00:00.000Z, stop: .{4}-.{2}-.{2}.*delete.first.row/start: ${START_DATE_INCR}T00:00:00.000Z, stop: ${END_DATE_INCR}T00:00:00.000Z) \/\/ delete first row/g" "${arr[1]}" # Replaces 'START_DATE' and 'END_DATE' in Bigquery queries: for ((i=2; i<${#arr[@]}; i++)) do sed -i -E "s/\('.{4}-.{2}-.{2}', DATE_SUB\('.{4}-.{2}-.{2}',/\('$START_DATE', DATE_SUB\('$END_DATE',/g" "${arr[$i]}"; sed -i -E "s/>= '.{4}-.{2}-.{2}'/>= '$START_DATE'/g" "${arr[$i]}"; sed -i -E "s/< '.{4}-.{2}-.{2}'/< '$END_DATE'/g" "${arr[$i]}"; done These are the queries as a reference (I don't seek feedback for the queries, I just included them for completeness): /app/queries/gads.sql: WITH dates AS ( SELECT * FROM UNNEST(GENERATE_DATE_ARRAY('2022-03-11', DATE_SUB('2022-03-15', INTERVAL 1 DAY), INTERVAL 1 DAY)) AS date ), gads_data AS ( SELECT DATE(__hevo_report_date) AS date, campaign, ad_group, sum(impressions) AS impressions, sum(clicks) AS clicks, ROUND(sum(cost)/1000000, 2) AS spend FROM `table1` WHERE DATE(__hevo_report_date) >= '2022-03-11' AND DATE(__hevo_report_date) < '2022-03-15' GROUP BY date, campaign, ad_group ) SELECT dates.date, campaign, ad_group, impressions, clicks, spend FROM dates LEFT OUTER JOIN gads_data ON dates.date = gads_data.date ORDER BY dates.date
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql # li.sql WITH dates AS ( SELECT date FROM UNNEST(GENERATE_DATE_ARRAY('2022-03-11', DATE_SUB('2022-03-15', INTERVAL 1 DAY), INTERVAL 1 DAY)) AS date ), gads_data AS ( SELECT DATE(TIMESTAMP_MILLIS(date)) AS date, campaign_id, sum(impressions) AS impressions, sum(clicks) AS clicks, sum(cost_in_local_currency) AS spend FROM `table2` WHERE DATE(TIMESTAMP_MILLIS(date)) >= '2022-03-11' AND DATE(TIMESTAMP_MILLIS(date)) < '2022-03-15' GROUP BY date, campaign_id ), names AS ( SELECT id, name AS campaign FROM `ten-x-studio-data.threema.li_campaign` ) SELECT dates.date, campaign, impressions, clicks, spend FROM dates LEFT OUTER JOIN gads_data ON dates.date = gads_data.date LEFT OUTER JOIN names ON gads_data.campaign_id = names.id ORDER BY dates.date /app/queries/ms.sql: WITH dates AS ( SELECT * FROM UNNEST(GENERATE_DATE_ARRAY('2022-03-11', DATE_SUB('2022-03-15', INTERVAL 1 DAY), INTERVAL 1 DAY)) AS date ), ms_data AS ( SELECT DATE(date) AS date, campaign_name AS campaign, ad_group_name AS ad_group, sum(impressions) AS impressions, sum(clicks) AS clicks, sum(spend) AS spend FROM `table3` WHERE DATE(date) >= '2022-03-11' AND DATE(date) < '2022-03-15' GROUP BY date, campaign_name, ad_group_name ) SELECT dates.date, campaign, ad_group, impressions, clicks, spend FROM dates LEFT OUTER JOIN ms_data ON dates.date = ms_data.date ORDER BY dates.date /app/queries/leads.flux: from(bucket: "bucket1") |> range(start: 2022-03-11T00:00:00.000Z, stop: 2022-03-15T00:00:00.000Z) |> filter(fn: (r) => r["env"] == "productive") |> duplicate(as: "val", column: "_value") |> difference(columns: ["val"], nonNegative: true, keepFirst: true) |> fill(column: "val", value: 0.0) |> group(columns: ["_field", "path"]) |> aggregateWindow(every: 1d, fn: sum, column: "val") |> yield(name: "mean")
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql app/queries/subs.flux: // Get added values a = from(bucket: "bucket2") |> range(start: 2022-03-10T00:00:00.000Z, stop: 2022-03-16T00:00:00.000Z) |> filter(fn: (r) => r["env"] == "productive") |> duplicate(column: "_value", as: "added_values") |> difference(columns: ["added_values"], nonNegative: true, keepFirst: true) |> fill(column: "added_values", value: 0.0) |> aggregateWindow(every: 1d, fn: sum, column: "added_values") |> map(fn:(r) => ({r with _time: string(v: r._time)})) |> drop(columns:["_measurement", "_start", "_stop", "env"]) // Get total values b = from(bucket: "bucket2") |> range(start: 2022-03-10T00:00:00.000Z, stop: 2022-03-16T00:00:00.000Z) |> filter(fn: (r) => r["env"] == "productive") |> aggregateWindow(every: 1d, fn: last, column: "_value") |> map(fn:(r) => ({r with _time: string(v: r._time)})) |> drop(columns:["_measurement", "_start", "_stop", "env"]) // Get subtracted values c = from(bucket: "bucket2") |> range(start: 2022-03-10T00:00:00.000Z, stop: 2022-03-16T00:00:00.000Z) |> filter(fn: (r) => r["env"] == "productive") |> duplicate(column: "_value", as: "sub_values") |> difference(columns: ["sub_values"], nonNegative: false, keepFirst: true) |> fill(column: "sub_values", value: 0.0) |> map(fn: (r) => ({r with sub_values: if r.sub_values < 0.0 then r.sub_values else 0.0})) |> aggregateWindow(every: 1d, fn: sum, column: "sub_values") |> map(fn:(r) => ({r with _time: string(v: r._time)})) |> drop(columns:["_measurement", "_start", "_stop", "env"]) temp = join(tables: {a:a, b:b}, on: ["_field", "_time", "isTrial", "offer", "segment"] )
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql temp = join(tables: {a:a, b:b}, on: ["_field", "_time", "isTrial", "offer", "segment"] ) res = join(tables: {temp:temp, c:c}, on: ["_field", "_time", "isTrial", "offer", "segment"] ) |> map(fn: (r) => ({ r with _time: time(v: r._time) })) |> range(start: 2022-03-12T00:00:00.000Z, stop: 2022-03-16T00:00:00.000Z) // delete first row |> group() |> sort(columns: ["_time", "_field", "isTrial", "offer", "segment"], desc: false) |> yield() ``` Answer: Generating files from template files Replacing dates in files correctly can be tricky. It requires carefully crafting the pattern so that: It correctly matches the values to replace. It does not match anything else unintended. I think a more robust alternative would be to define template files with clear placeholders that should be replaced with computed values. For example you could have placeholders in the form of {{NAME}}. This would make the pattern replacement simpler, generic (usable not only with date strings but with anything), and also reduce the risk of unintended matches. Exiting with error I'm wondering what you expected the exit code to be here: if [ "$#" -ne 2 ]; then echo "Illegal number of arguments. Program expects two date strings (YYYY-mm-dd)." exit $? $? stores the exit code of the last executed command, in this case the echo, which practically always succeeds. I suggest replacing this with exit 1 instead. Same thing at one more place in the code. Always enclose variables in double-quotes used on the command line This loop aims to validate the date variables: for date in $START_DATE $END_DATE do format="^[0-9]{4}-[0-9]{2}-[0-9]{2}$" if ! [[ $date =~ $format ]] then echo "Date $date is incorrectly formatted (not YYYY-mm-dd)." exit $? fi done
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql If one of $START_DATE and $END_DATE is empty, the loop body will not run for it, and validation will be skipped. If both are missing, the script will crash with a syntax error. Use a validator function Instead of looping over $START_DATE and $END_DATE, a validator function would be better: validate_date() { # ... } validate_date "$START_DATE" validate_date "$END_DATE" Not only does this give a name to the validation logic, it would catch an invalid date even if you missed correctly double-quoting the variables, unlike when using a loop. Reduce repeated overwriting of files The other answer already recommended using the -e flag to pass multiple expressions to the same sed command. Another advantage of doing that is to reduce the repeated overwriting of the files. This might not make much difference in practice in this example; it's good to do anyway as a good practice. And to make it really easy to read, I would format like this: sed -i -E \ -e "s/\('.{4}-.{2}-.{2}', DATE_SUB\('.{4}-.{2}-.{2}',/\('$START_DATE', DATE_SUB\('$END_DATE',/g" \ -e "s/>= '.{4}-.{2}-.{2}'/>= '$START_DATE'/g" \ -e "s/< '.{4}-.{2}-.{2}'/< '$END_DATE'/g" \ "${arr[$i]}" That is, each line here does either a single thing, or something easy to understand, and the file that will be affected is also easy to see because it stands out as the only thing on the line. Use descriptive variable names My main objection is about the first two elements of the array. ${arr[0]} and ${arr[1]} are not used in a loop, and I don't see a good reason to have these in the array. It would be better to give them descriptive names. Also note that if arr contains only the names to use in the loop, then you can use a simpler classic iterating loop instead of a counting loop: for name in "${arr[@]}"; do And of course, it would be good to use a descriptive name instead of arr, for example sql_files or even just sqls. Use brace expansion Instead of repeating the ${QUERIES} prefix multiple times:
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
sql, bash, nosql arr=( "${QUERIES}/leads.flux" "${QUERIES}/subs.flux" "${QUERIES}/gads.sql" "${QUERIES}/ms.sql" "${QUERIES}/li.sql" ) You could use brace expansion to reduce duplication: arr=("${QUERIES}"/{leads.flux,subs.flux,gads.sql,ms.sql,li.sql}) Braces can also be nested, but beware to not overdo and hurt readability: arr=("${QUERIES}"/{{leads,subs}.flux,{gads,ms,li}.sql})
{ "domain": "codereview.stackexchange", "id": 43728, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, bash, nosql", "url": null }
java, beginner, random, serialization Title: Simple ID Generator Question: Task Write a program that can generate and manage collections of IDs. The user should determine how long the IDs have to be and what symbols they are composed of. Design choices made by me The program functionalities are used via command line arguments A configuration file determines which scheme the IDs correspond to and where they are to be stored. It should be possible to manage several ID collections if the user wants it. Misuse should be intercepted, but the program does not have to be foolproof. (You can find usage information by just calling java Main, or have a look at Main.printHelp().) Example Usage C:\Programs> java Main help Usage: java appname config:special/config/file <operation> operations: new, show, del:<id>, custom:<custom_id>, help If you do not provide a path to a config file, standard.config will be used. You can only do one operation per program call. C:\Programs> java Main new RK9CE C:\Programs> java Main new KOZJO C:\Programs> java Main new 8N23M C:\Programs> java Main show KOZJO, RTBXU, 8N23M C:\Programs> java Main custom:bliblablub Error: To long. C:\Programs> java Main custom:blibl Error: Your id contains forbidden symbols. C:\Programs> java Main custom:BLIBL Success. C:\Programs> java Main del:BLIBL Success.
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization Question What do you think of my design choices? Did I manage to implement them elegantly? Are there design flaws in my source code? Source code and config-file Main.java public class Main { private static String configFile = "standard.config"; public static void main(String[] args) { int argIndex = 0; if (args.length > 0 && args.length <= 2) { boolean continueArgParsing = false; do { // check if user wants to provide a non-default config if (args[argIndex].startsWith("config:")) { configFile = args[argIndex].split(":")[1]; if (args.length < 2) { System.out.println("Please also tell me what you want to do."); System.exit(0); } continueArgParsing = true; argIndex++; continue; } IdManager man = IdManager.init(configFile); if (man == null) return; // check what user actually wants to do if (equalsOneOf(args[argIndex].toLowerCase(), "h", "-h", "/h", "help", "-help", "/help", "info")) { printHelp(); } else if (args[argIndex].equalsIgnoreCase("new")) { System.out.println(man.createNewId()); } else if (args[argIndex].startsWith("del:")) { String idToDelete = args[argIndex].split(":")[1]; if (man.deleteId(idToDelete)) { System.out.println("Success."); } else { System.out.println("Error: There is no such id."); } } else if (args[argIndex].equalsIgnoreCase("show")) { System.out.println(man.getIds());
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization System.out.println(man.getIds()); } else if (args[argIndex].startsWith("custom:")) { String customId = args[argIndex].split(":")[1]; String errorMessage = man.addCustomId(customId); if (errorMessage == null) { System.out.println("Success."); } else { System.out.println(errorMessage); } } continueArgParsing = false; } while (continueArgParsing); } else { printHelp(); } } private static void printHelp() { System.out.println("Usage: java appname config:special/config/file <operation>"); System.out.println("operations: new, show, del:<id>, custom:<custom_id>, help"); System.out.println("If you do not provide a path to a config file, standard.config will be used."); System.out.println("You can only do one operation per program call."); } // missing in java standard library private static boolean equalsOneOf(String string, String... values) { for (String value : values) { if (string.equals(value)) return true; } return false; } }
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization IdManager.java import java.util.Set; import java.util.HashSet; import java.util.Properties; import java.util.Random; import java.io.File; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.IOException;
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization public class IdManager { private static final Random random = new Random(); private String saveFile; private Set<String> ids; private String allowedSymbols; private int minLength; private int maxLength; private IdManager (String saveFile, String allowedSymbols, int minLength, int maxLength) { this.saveFile = saveFile; // remove all whitespace from allowedSymbols this.allowedSymbols = allowedSymbols.replaceAll("\\s", ""); this.minLength = minLength; this.maxLength = maxLength; ids = new HashSet<String>(); loadIdsFromFile(); } public static IdManager init(String configFile) { try (FileInputStream fis = new FileInputStream(configFile)) { Properties properties = new Properties(); properties.load(fis); String saveFile = properties.getProperty("saveFile"); String allowedSymbols = properties.getProperty("allowedSymbols"); int minLength = Integer.parseInt(properties.getProperty("minLength")); int maxLength = Integer.parseInt(properties.getProperty("maxLength")); return new IdManager(saveFile, allowedSymbols, minLength, maxLength); } catch (IOException e) { System.out.println("Error: Could not read config file."); return null; } } private void loadIdsFromFile() { File file = new File(saveFile); if (!file.exists()) return; try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { ids = (HashSet<String>) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void saveIds() { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(saveFile))) { oos.writeObject(ids);
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization oos.writeObject(ids); } catch (IOException e) { e.printStackTrace(); } } public String getIds() { return String.join(", " , ids); } public String createNewId() { // determine length int length = 0; if (maxLength == minLength) length = maxLength; else length = random.nextInt(maxLength - minLength + 1) + minLength; // repeat until new unique id is found String newId = ""; while (true) { for (int i = 0; i < length; i++) { char symbolChar = allowedSymbols.charAt(random.nextInt(allowedSymbols.length())); String symbol = Character.toString(symbolChar); newId = newId + symbol; } if (ids.add(newId)) break; else newId = ""; } saveIds(); return newId; } // returns an error message if something went wrong // returns null when everything is fine public String addCustomId(String customId) { // check if length meets requirements if (customId.length() < minLength) return "Error: To short."; if (customId.length() > maxLength) return "Error: To long."; // check if only allowed symbols are in custom ids for (int i = 0; i < customId.length(); i++) { if (allowedSymbols.indexOf(customId.charAt(i)) == -1) return "Error: Your id contains forbidden symbols."; } // check if id is already in use if (!ids.add(customId)) return "Error: Id is already in use."; saveIds(); return null; } // returns false if there is no such id public boolean deleteId(String id) { boolean returnValue = ids.remove(id); saveIds(); return returnValue; } }
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization standard.config allowedSymbols = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 minLength = 5 maxLength = 5 saveFile = ids.data Answer: Single responsibility principle Your IdManager class has multiple responsibilities. It needs to know How to generate an ID. How to create an IdManager from a configuration file. How to load IDs from a file. How to save IDs to a file. How to display a human readable String of the IDs. What the properties of the IdManager are. Now, we can lump these responsibilities together as all relating to IDs. But there are better abstractions. What if we break this into multiple classes? IdGenerator IdManagerFromConfig SetLoader<T> SetStorer<T> And leave the last two in IdManager. Now, only IdGenerator needs Random. Only IdManagerFromConfig needs Properties. Only IdManagerFromConfig and SetLoader<T> need FileInputStream. Only SetLoader<T> needs ObjectInputStream. Only SetStorer<T> needs ObjectOutputStream and FileOutputStream. Only SetLoader<T> needs HashSet. IOException and Set are the only imports needed by more than two classes. Don't catch what you can't handle } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); What happens after this code? Does your application simply not work? Does it die somewhere with no data? What would happen if this code did not exist? I'm guessing that the exception would bubble to the top, your program would end, and it would display a stack trace. Why are you replacing that with a manually displayed stack trace and a (presumably) non-functional program? Until you are ready to do something with the exception, you should not catch it. Instead, change the method to throws whatever exception. Just printing a stack trace is useless behavior in a catch block. You can get that by just ignoring the exception. Simplify if you can
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization int length = 0; if (maxLength == minLength) length = maxLength; else length = random.nextInt(maxLength - minLength + 1) + minLength; You can write this more simply as int length = minLength; if (maxLength != minLength) { length += random.nextInt(maxLength - minLength + 1); } This will break if maxLength is less than minLength, as does your code. It might be better to check for that case in the constructor or init rather than waiting until here to die. This uses the block form of the if, as that is highly recommended. I don't want to dwell on this if you've already thought through the consequences. But I would prefer code on which I'm working to always use the block form. If you haven't taken the time to read the arguments against the statement form yet, you may find it useful to do so. Since both branches of the if start with minLength while one adds to it, we can simply start with minLength. Then we don't do the never used initialization to 0 and we only need one branch. As a general rule, if code doesn't actually do anything, it makes sense to remove it. Otherwise, people can find themselves wasting time trying to figure out what the code does. Minimize scope String newId = ""; while (true) { for (int i = 0; i < length; i++) { char symbolChar = allowedSymbols.charAt(random.nextInt(allowedSymbols.length())); String symbol = Character.toString(symbolChar); newId = newId + symbol; } if (ids.add(newId)) break; else newId = ""; } saveIds(); return newId;
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
java, beginner, random, serialization You can reduce the scope of newId, since you don't need it after the return and do need to reset it between invocations. Consider PrimitiveIterator.OfInt indexes = random.ints(0, allowedSymbols.length).iterator(); while (true) { StringBuilder newId = new StringBuilder(length); while (newId.length() < length) { newId.append(allowedSymbols[indexes.nextInt()]); } if (ids.add(newId.toString())) { saveIds(); return newId.toString(); } } Now it resets automatically. This generates a random IntStream rather than repeatedly calling nextInt. Mostly this saves having to specify allowedSymbols.length each time. It may also allow some optimizations. Note that Random is not cryptographically secure. You should use a different implementation if randomness really matters. E.g. SecureRandom. But if true randomness is not important, Random is faster. You might allow callers to pass a Random into the constructor so that they can specify whether security or speed is more important for their application. This changes allowedSymbols to a character array for simpler access. Note that you can still pass a String into the constructor. Then just do this.allowedSymbols = allowedSymbols.replaceAll("\\s", "").toCharArray(); When building a string, StringBuilder is what you want to use. The compiler would probably have done this for you, but now you don't have to worry about it. Alternately, you could have done this with a character array as well. Since you already know the length at this point. Moving the return into the loop is the last piece needed to reduce the scope of newId.
{ "domain": "codereview.stackexchange", "id": 43729, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, random, serialization", "url": null }
php, mysql, mysqli, wrapper, crud Title: Functions in PHP to run basic MySQL crud Question: I wrote a list of functions in PHP that I want to use in my pet project as an autoloaded file for all parts of the app. The purpose of these function is to shorten the code you write for MySQL queries in PHP using MySQLi. It also uses prepared statements to make it secure. Is this code alright? What improvements can I do to it? <?php // Insert function function insert_db($table, $columns, $values, $return_id = false) { global $db; $question_marks = ""; $type_strings = ""; for ($i = 0; $i < count($columns); $i++) { if ($i == count($columns) - 1) { $question_marks .= "?"; } else { $question_marks .= "?,"; } $type_strings .= "s"; } $columns_string = implode(",", $columns); $sql = "INSERT INTO `$table` ($columns_string) VALUES ($question_marks)"; $stmt = $db->prepare($sql); $stmt->bind_param("$type_strings", ...$values); $stmt->execute(); if ($return_id === true) { return $db->insert_id; $stmt->close(); } else { $stmt->close(); } } // Read function function read_db($table, $columns, $where, $type_strings, $values) { global $db; $data = []; $complete_data = []; $columns_string = implode(",", $columns); $sql = "SELECT $columns_string FROM `$table` $where"; $stmt = $db->prepare($sql); if (is_array($values)) { $stmt->bind_param("$type_strings", ...$values); } $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { array_push($data, $row ); } $complete_data = [$data, $result->num_rows, $stmt->affected_rows]; return $complete_data; } // Update function function update_db($table, $columns, $values, $where, $where_values, $type_strings) { global $db; $sql = "UPDATE `$table` SET "; $question_marks = ""; $type_length = strlen($type_strings);
{ "domain": "codereview.stackexchange", "id": 43730, "lm_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, mysqli, wrapper, crud", "url": null }
php, mysql, mysqli, wrapper, crud $question_marks = ""; $type_length = strlen($type_strings); for ($i = 0; $i < $type_length; $i++) { if ($i == ($type_length - 1)) { $question_marks .= "?"; } else { $question_marks .= "?,"; } } for ($i = 0; $i < count($columns); $i++) { if ($i == (count($columns) - 1)) { $sql .= "$columns[$i]=? $where;"; } else { $sql .= "$columns[$i]=?,"; } } $data = array_merge($values, $where_values); $stmt = $db->prepare($sql); $stmt->bind_param("$type_strings", ...$data); $stmt->execute(); } // Delete function function delete_db($table, $where, $values, $type_strings) { global $db; $sql = "DELETE FROM `$table` $where"; $stmt = $db->prepare($sql); $stmt->bind_param("$type_strings", ...$values); $stmt->execute(); } // It technically became IRUD instead of CRUD, but for function naming create_db would confuse developers so I chose this :P ?> Edit: I am also including some test cases for the functions, $admissions_data = read_db("admission_records", ["*"], "WHERE organization_id = ? AND branch_id = ? AND admission_id = ?", "sss", [$organization_id, $branch_id, $record_id]); insert_db("products", ['product_name', 'product_url', 'product_proof', 'company_id'], [$product_name, $product_url, $product_proof, $products_data[0][0]['company_id']]); You get the idea now. Answer: The code is decent - simple to read, though the comments above the functions don't add much. It is a good idea to follow the PHP Standards Recommendations - and there is currently a draft for the PHPDoc Standard. Instead of a single line comment above functions it would be more informative to have a Multiline DocComment listing parameters with types, return type, etc. Instead of simply // Insert function function insert_db($table, $columns, $values, $return_id = false)
{ "domain": "codereview.stackexchange", "id": 43730, "lm_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, mysqli, wrapper, crud", "url": null }
php, mysql, mysqli, wrapper, crud // Insert function function insert_db($table, $columns, $values, $return_id = false) It would be more helpful for anyone reading the code to see something more descriptive: /** * Insert data into the database * * @param string $table * @param array $columns * @param array $values * @param bool $return_id * * @return integer|void */ function insert_db($table, $columns, $values, $return_id = false) One major advantage is that many IDEs will index those docblocks and provide suggestions based on them during code development. The closing PHP tag can be omitted when the file only contains PHP - e.g. no HTML exists outside the PHP code. This is supported by PSR-12. As I explained near the beginning of this review the loops used to create the placeholders can typically be simplified using the built-in PHP functions implode() and array_fill(). Then there is no need to have conditional logic to append separators like commas.
{ "domain": "codereview.stackexchange", "id": 43730, "lm_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, mysqli, wrapper, crud", "url": null }
python, python-3.x, object-oriented, file-system, pdf Title: Attempting an OOP approach for PDF Paranoia - Automate the Boring Stuff CH 15 Question: This exercise is called PDF Paranoia and it comes from CH 15 of the book Automate the Boring Stuff With Python - second edition. There are two parts to the exercise, which I've separated into two Python files. The code I've provided uses Python 3.10 and PyPDF2 v. 2.10.0. The instructions are as follows: Using the os.walk() function from Chapter 10, write a script that will go through every PDF in a folder (and its subfolders) and encrypt the PDFs using a password provided on the command line. Save each encrypted PDF with an _encrypted.pdf suffix added to the original filename. Before deleting the original file, have the program attempt to read and decrypt the file to ensure that it was encrypted correctly. Then, write a program that finds all encrypted PDFs in a folder (and its subfolders) and creates a decrypted copy of the PDF using a provided password. If the password is incorrect, the program should print a message to the user and continue to the next PDF. My three main goals with the code are: Use an object-oriented approach Write useful docstrings / comments Write Pythonic code
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf Use an object-oriented approach Write useful docstrings / comments Write Pythonic code I also implemented storing functions as a callable (without the "()") in order to reuse the code. If there is a better approach for this or if there is something I have missed, I would love to know. First file, stored as pdfparanoia.py: #!python3 # pdfparanoia.py - Walk through a directory and its subdirectories, and encrypt # every PDF file. Provide the encryption password via command # line and the filepath to search through. Check to see if # encryption succeeded by attempting to read and decrypt the # files. Prompt the user to delete the older unencrypted files. # # USAGE: sys.argv[1] = password # sys.argv[2] = filepath to search for PDFs # Using Python 3.10 and PyPDF2 v2.10.0 import os import sys import PyPDF2 from typing import Callable class EncryptPDFs: def __init__(self): self.password = sys.argv[1] self.dir_to_search = sys.argv[2] self.encryption_call = self.encrypt_pdf # store as callable self.delete_call = self.delete_file # store as callable self.encryption_check_call = self.encryption_checker # store as callable @staticmethod def search_for_pdf(dir_to_search: str, function_call: Callable) -> None: """ :param dir_to_search: input directory tree to walk through :param function_call: Input callable as argument and pass it the file variable. Callable argument acts on all PDF files in the given directory tree. """ print(f"Searching for .pdf files in: {dir_to_search}") for folder, sub_folders, file_list in os.walk(dir_to_search): for file in file_list: if file.split(".")[-1].lower() == "pdf": function_call(file)
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf def encrypt_pdf(self, pdf_file: str) -> None: """ :param file: Input PDF file name from the calling function (search_for_pdf()). If the PDF is not encrypted, create a PDFFileWriter object to encrypt and save it as a new file. Encrypted files will be skipped. """ file_object = open(pdf_file, "rb") reader = PyPDF2.PdfFileReader(file_object) if not reader.isEncrypted: print(f"Encrypting {pdf_file}") writer = PyPDF2.PdfFileWriter() for page_num in range(reader.numPages): writer.addPage(reader.getPage(page_num)) writer.encrypt(self.password) result_pdf = open(pdf_file.split(".")[0] + "_encrypted.pdf", "wb") writer.write(result_pdf) result_pdf.close() file_object.close() def encryption_checker(self, pdf_file: str) -> None: """Check to see if encryption succeeded by reading and decrypting the files.""" file_object = open(pdf_file, "rb") reader = PyPDF2.PdfFileReader(file_object) try: reader.getPage(0) except PyPDF2.errors.FileNotDecryptedError: print(f"Encryption check 1: {pdf_file} is encrypted and cannot be read.") if reader.isEncrypted: print( f"Encryption check 2: isEncrypted() method returns True when called on {pdf_file}." ) print(f"{pdf_file} is encrypted.\n") reader.decrypt(self.password) file_object.close() def delete_file(self, pdf_file: str) -> None: """Optionally delete unencrypted files after encryption check.""" file_object = open(pdf_file, "rb") reader = PyPDF2.PdfFileReader(file_object) if not reader.isEncrypted: file_object.close() os.remove(pdf_file)
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf def main(self) -> None: """ Search for PDF files, prompt user to enter encryption password, then encrypt the files. Attempt to read / decrypt the files to ensure encryption succeeded, then prompt user to delete unencrypted files and exit. """ self.search_for_pdf(self.dir_to_search, self.encryption_call) print("\nSearching for encrypted files to check.\n") self.search_for_pdf(self.dir_to_search, self.encryption_check_call) while True: choice = input("\nDo you wish to delete all unencrypted files? Y/N\n") if choice.upper() == "Y": self.search_for_pdf(self.dir_to_search, self.delete_call) sys.exit() elif choice.upper() == "N": sys.exit() else: continue if __name__ == "__main__": EncryptPDFs().main() Second file, stored as decrypt_pdf_file.py This file imports the first file in order to call the search_for_pdf() function: #!python3 # decrypt_pdf_file.py - Walk through a directory and its subdirectories, and prompt # the user to input a password to decrypt the files. # # USAGE: sys.argv[1] = filepath to search for PDFs import sys import PyPDF2 from pdfparanoia import EncryptPDFs dir_to_search = sys.argv[1]
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf import sys import PyPDF2 from pdfparanoia import EncryptPDFs dir_to_search = sys.argv[1] def decrypt_pdf_file(file: str) -> None: """ :param file: input PDF file from calling function. Create a PdfFileReader object to determine if the PDF is encrypted. If the PDF is encrypted, prompt the user for the encryption password. If the password is correct, decrypt it the file and save it. If the password is incorrect, warn the user and continue. """ file_object = open(file, 'rb') reader = PyPDF2.PdfFileReader(file_object) if reader.isEncrypted: password = input(f'Please enter the password to decrypt {file}\n') if reader.decrypt(password) == 0: print(f'Password invalid. {file} was not decrypted\n') elif reader.decrypt(password) == 1: print(f'Decrypting {file}') writer = PyPDF2.PdfFileWriter() for page_num in range(reader.numPages): writer.addPage(reader.getPage(page_num)) result_pdf = open(file.split('.')[0] + '_decrypted.pdf', 'wb') writer.write(result_pdf) result_pdf.close() print(f'{file} has been decrypted and saved.') file_object.close() DECRYPTION_CALL = decrypt_pdf_file # store function as Callable if __name__ == "__main__": EncryptPDFs.search_for_pdf(dir_to_search, DECRYPTION_CALL)
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf if __name__ == "__main__": EncryptPDFs.search_for_pdf(dir_to_search, DECRYPTION_CALL) Answer: Object oriented code means that you have objects, and methods for interacting with those objects, you can then very easily reuse / compose those objects to do different things. In this case you've created a god class (https://en.wikipedia.org/wiki/God_object) which does several different things (reading arguments from the command line; finding PDFs; encrypting / decrypting PDFs; deleting PDFs). Ideally each of those concerns should be a separate entity in code (https://en.wikipedia.org/wiki/Separation_of_concerns). In traditional OO languages that would mean either separate strategy classes (normally used when you have multiple related behaviours which are tightly coupled, like encrypting and decrypting) or through using 'template methods' for those parts which can be overridden through inheritance (used to change one step). In python you generally don't use template methods, for many reasons, instead you pass in function objects to override specific steps in an algorithm. You've kind of done that here, but you've gotten confused over how variables work in python: self.delete_call = self.delete_file # store as callable ^ This code doesn't store anything, or achieve anything really. Variables in python are just labels, you've just added an alias to 'self.delete_file'. It would be better to just pass in 'self.delete_file' directly where it's used. Also, OO code still normally has a high level main function which kicks everything off. In pure OO languages like Java this is a static method of a class, but that's not needed in python, you can just write a function, writing staticmethods is very much 'not pythonic'. When you have to do something, and then clean it up at the end (i.e. opening and closing files in your code) - the pythonic way of doing that is to use a context manager. That is, instead of: file_object = open(file, 'rb') # Code here file_object.close()
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf You would do: with open(file, 'rb') as file_object: # Code here This is neater, but also more robust, the closing of the file will happen now even if your code crashes. Although, in this case it's also not completely necessary, the library you're using supports creating readers / writers from strings directly, and supports using them as context managers. In addition, it supports iterating over pages directly, which will also be more efficient and more pythonic: def encrypt_pdf(self, pdf_file: str) -> None: """ :param file: Input PDF file name from the calling function (search_for_pdf()). If the PDF is not encrypted, create a PDFFileWriter object to encrypt and save it as a new file. Encrypted files will be skipped. """ with PyPDF2.PdfFileReader(pdf_file) as reader: if not reader.isEncrypted: print(f"Encrypting {pdf_file}") with PyPDF2.PdfFileWriter(pdf_file.split('.')[0] + '_encrypted.pdf') as writer: for page in reader.pages: writer.addPage(page) writer.encrypt(self.password) Some of your methods do too much. Your method for finding PDFs should really just find PDFs, and leave doing stuff to them for something else. I.e, not this: @staticmethod def search_for_pdf(dir_to_search: str, function_call: Callable) -> None: """ :param dir_to_search: input directory tree to walk through :param function_call: Input callable as argument and pass it the file variable. Callable argument acts on all PDF files in the given directory tree. """ print(f"Searching for .pdf files in: {dir_to_search}") for folder, sub_folders, file_list in os.walk(dir_to_search): for file in file_list: if file.split(".")[-1].lower() == "pdf": function_call(file) ... self.search_for_pdf(self.dir_to_search, self.encryption_call)
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf ... self.search_for_pdf(self.dir_to_search, self.encryption_call) Rather, this: def search_for_pdf(dir_to_search: str) -> None: """ :param dir_to_search: input directory tree to walk through :param function_call: Input callable as argument and pass it the file variable. Callable argument acts on all PDF files in the given directory tree. """ print(f"Searching for .pdf files in: {dir_to_search}") for folder, sub_folders, file_list in os.walk(dir_to_search): for file in file_list: if file.split(".")[-1].lower() == "pdf": yield file ... for pdf in search_for_pdf(self.dir_to_search): encrypt(pdf) As there isn't much logic here, you could quite comfortably handle the whole thing without any classes at all, and indeed that would probably be better in this case. Object-oriented is useful when you have multiple strategies that you want to apply and the strategies are complex enough to need multiple methods. Here you can just really just use functions. That said, to give you what you want, let's try splitting our four concerns into 3 functions and a class: import os import sys import PyPDF2
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf class PdfEncryptor: def __init__(self, password: str): self._password = password def encrypt(self, pdf_writer): pdf_writer.encrypt(self._password) def decrypt(self, pdf_reader): pdf_reader.decrypt(self._password) def encrypt_path(self, pdf_path): with PyPDF2.PdfFileReader(pdf_path) as reader: if not reader.isEncrypted: print(f"Encrypting {pdf_path}") with PyPDF2.PdfFileWriter(pdf_path.split('.')[0] + '_encrypted.pdf') as writer: for page in reader.pages: writer.addPage(page) self.encrypt(writer) def check_can_decrypt(self, pdf_path): """Check to see if encryption succeeded by reading and decrypting the files.""" with PyPDF2.PdfFileReader(pdf_path) as reader: try: reader.getPage(0) except PyPDF2.errors.FileNotDecryptedError: print(f"Encryption check 1: {pdf_file} is encrypted and cannot be read.") if reader.isEncrypted: print( f"Encryption check 2: isEncrypted() method returns True when called on {pdf_file}." ) print(f"{pdf_file} is encrypted.\n") self.decrypt(reader) def search_for_pdf(dir_to_search: str) -> None: """ :param dir_to_search: input directory tree to walk through :param function_call: Input callable as argument and pass it the file variable. Callable argument acts on all PDF files in the given directory tree. """ print(f"Searching for .pdf files in: {dir_to_search}") for folder, sub_folders, file_list in os.walk(dir_to_search): for file in file_list: if file.split(".")[-1].lower() == "pdf": yield file
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf def delete_file(pdf_file: str): """Optionally delete unencrypted files after encryption check.""" with PyPDF2.PdfFileReader(pdf_file) as reader: encryped = reader.isEncrypted if not encrypted: os.remove(pdf_file) def main(): """ Search for PDF files, prompt user to enter encryption password, then encrypt the files. Attempt to read / decrypt the files to ensure encryption succeeded, then prompt user to delete unencrypted files and exit. """ password = sys.argv[1] encryptor = PdfEncryptor(password) dir_to_search = sys.argv[2] for pdf in search_for_pdf(dir_to_search): encryptor.encrypt_path(pdf) print("\nSearching for encrypted files to check.\n") for pdf in search_for_pdf(dir_to_search): encryptor.check_can_decrypt(pdf) while True: choice = input("\nDo you wish to delete all unencrypted files? Y/N\n") if choice.upper() == "Y": for pdf in search_for_pdf(dir_to_search): delete_file(pdf) sys.exit() elif choice.upper() == "N": sys.exit() else: continue And now we can reuse the PDF finding logic (which is the only thing being reused) in your second script: import sys import PyPDF2 from pdfparanoia import search_for_pdf
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, python-3.x, object-oriented, file-system, pdf def decrypt_pdf_file(file: str) -> None: """ :param file: input PDF file from calling function. Create a PdfFileReader object to determine if the PDF is encrypted. If the PDF is encrypted, prompt the user for the encryption password. If the password is correct, decrypt it the file and save it. If the password is incorrect, warn the user and continue. """ with PyPDF2.PdfFileReader(file) as reader: if reader.isEncrypted: password = input(f'Please enter the password to decrypt {file}\n') if reader.decrypt(password) == 0: print(f'Password invalid. {file} was not decrypted\n') elif reader.decrypt(password) == 1: print(f'Decrypting {file}') with PyPDF2.PdfFileWriter(file.split('.')[0] + '_decrypted.pdf') as writer: writer = PyPDF2.PdfFileWriter() for page in reader.pages: writer.addPage(page) print(f'{file} has been decrypted and saved.') if __name__ == "__main__": dir_to_search = sys.argv[1] for pdf in search_for_pdf(dir_to_search): decrypt_pdf_file(pdf)
{ "domain": "codereview.stackexchange", "id": 43731, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, file-system, pdf", "url": null }
python, algorithm Title: Maze generator (backtracking algorithm) Question: Task. To generate random mazes using backtracking algorithm. User inputs how many vertical and horizontal pathes the maze should have and then the script uses this information to generate a maze. Evaluation criterion. Maze creation speed. The script should be fast enough to randomly generate huge mazes as fast as possible. The current algorithm creates: A 300x300 maze is gererated in ~4.52 seconds, 400x400 in ~9.75, 500x500 in ~13.5, 600x600 in ~21.4 What I tried to increase the efficiency of the algorithm. I tried to store deadends somewhere so the algorithm never visit (backtrack) those cells again. But it turned out to be a bad decision since storing deadends in a special array or changing a "deadend" property of a cell is expensive. Also checking the status of a cell or searching for a specific cell in a "deadends" array is expensive. from PIL import Image import numpy as np import time import random def dig(r, c): pixels[r, c] = 255 maze_width = int(input("Width: ")) maze_height = int(input("Height: ")) width = maze_width * 2 + 1 height = maze_height * 2 + 1 pixels = np.zeros((height, width), dtype=np.uint8) paths = [] all_positions = maze_width * maze_height start = time.time() row = random.randrange(1, height-1, 2) col = random.randrange(1, width-1, 2) dig(row, col) paths.append([row, col, 0]) directions = ['up', 'down', 'left', 'right'] iterations = 0 in_deadend = 0 direction_to_coords = { 'up': {'y':-2, 'half': 1}, 'down': {'y': 2, 'half': -1}, 'left': { 'x': -2, 'half': 1}, 'right': { 'x': 2, 'half': -1} } visited = 1 while visited < all_positions: iterations += 1 if len(directions) == 0: in_deadend += 1 row, col, deadend = random.choice(paths) directions = ['up', 'down', 'left', 'right'] else: direction = random.choice(directions) direction_action = direction_to_coords[direction]
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm direction_action = direction_to_coords[direction] if 'y' in direction_action: if 0 < row + direction_action['y'] <= height - 2 and pixels[row + direction_action['y'], col] != 255: row += direction_action['y'] dig(row + direction_action['half'], col) dig(row, col) directions = ['up', 'down', 'left', 'right'] visited += 1 paths.append([row, col, 0]) else: directions.remove(direction) else: if 0 < col + direction_action['x'] <= width - 2 and pixels[row, col + direction_action['x']] != 255: col += direction_action['x'] dig(row, col + direction_action['half']) dig(row, col) directions = ['up', 'down', 'left', 'right'] visited += 1 paths.append([row, col, 0]) else: directions.remove(direction) print('iterations: ', iterations) print('been in deadend: ', in_deadend ) pixels[0, random.randrange(1, width-1, 2)] = 255 pixels[height-1, random.randrange(1, width-1, 2)] = 255 print("\ncreated in %.5f" % (time.time() - start)) size = int(width * 10), int(height * 10) img = Image.fromarray(pixels) img = img.resize(size, Image.NEAREST) img.save('maze.png') img.show()
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm img = Image.fromarray(pixels) img = img.resize(size, Image.NEAREST) img.save('maze.png') img.show() Answer: Claim You claim to be using a 'backtracking' algorithm. I would disagree. You are using repeated random walks, starting at random positions from previous walks; I see no evidence of "backtracking". Dictionaries Dictionaries are fast; their look up operations are \$O(1)\$. But they are not FAST. The input key must be converted to a hash value, then the hash value is converted to a bin number, then the bin is searched for a key that exactly matches the given key, and if found the corresponding value is returned. Overusing dictionaries will result in slower code, and you are doing that here. Double Indirection You have a dictionary mapping direction names to direction values, and then you randomly select a direction name from a list of available directions, and look up the corresponding direction value. You are not using the direction name for anything other than the lookup. It is a middle-value. Consider instead a list of direction values. Let's remove the direction_to_coords dictionary and instead define the four directions as constants, and initialize directions to those instead: UP = {'y': -2, 'half': 1} DOWN = {'y': 2, 'half': -1}, LEFT = {'x': -2, 'half': 1}, RIGHT = {'x': 2, 'half': -1} directions = [UP, DOWN, LEFT, RIGHT] Now, instead of choosing a random direction name and looking up the "action", we can just pick a random "action". direction_action = random.choice(directions) If the way is blocked, you remove the direction_action from the possibilities: directions.remove(direction_action)
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm Heterogeneous dictionaries Your direction actions are different animals. While they all have a 'half' key, only some have an 'x' key, while the others have a 'y' key. This means after selecting a random action, you have to check if 'y' in direction_action to determine which kind of animal you have. Instead, you want to store the same kind of thing. For example: UP = {'full': (0, -2), 'half': (0, 1)} DOWN = {'full': (0, 2), 'half': (0, -1)} LEFT = {'full': (-2, 0), 'half': (1, 0)} RIGHT = {'full': (2, 0), 'half': (-1, 0)} The 'full' and 'half' attributes contain the change in both row and col for that direction, even if the change is zero for that dimension. There is no longer a need to check if 'y' in direction_action because the same code will execute for the horizontal and vertical directions. direction = random.choice(directions) dc, dr = direction['full'] if 0 < row + dr < height and 0 < col + dc < width and pixels[row + dr, col + dc] != 255: row += dr col += dc dig(row, col) dc, dr = direction['half'] dig(row + dr, col + dc) directions = [UP, DOWN, LEFT, RIGHT] visited += 1 paths.append([row, col, 0]) else: directions.remove(direction) 22 lines has been reduced to 13, an if/if/else/else/if/else has become just an if/else, and a dictionary indirection lookup has been removed. Note: The variable names like dc and dr come from calculus, where a change in a variable x is often written as \$\Delta x\$, pronounced "delta-x", and later \$\delta x\$, or simply \$dx\$. Choose more descriptive names if you are not comfortable with these. Two Steps Forward, One Step Back Those 'full' and 'half' dictionary keys are yet another unnecessary dictionary lookup. We simply need a pairs of direction vectors; a tuple of tuples: UP = (0, -2), (0, 1) DOWN = (0, 2), (0, -1) LEFT = (-2, 0), (1, 0) RIGHT = (2, 0), (-1, 0) ...
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm ... direction = random.choice(directions) (dc, dr), (hc, hr) = direction if 0 < row + dr < height and 0 < col + dc < width and pixels[row + dr, col + dc] != 255: row += dr col += dc dig(row, col) dig(row + hr, col + hc) directions = [UP, DOWN, LEFT, RIGHT] visited += 1 paths.append([row, col, 0]) else: directions.remove(direction) Two steps forward You really don't need the "half" vectors at all; they are a -0.5 scale version of the forward vector. Let's get rid of them. UP = (0, -2) DOWN = (0, 2) LEFT = (-2, 0) RIGHT = (2, 0) ... direction = random.choice(directions) dc, dr = direction if 0 < row + dr < height and 0 < col + dc < width and pixels[row + dr, col + dc] != 255: row += dr col += dc dig(row, col) dig(row - dr // 2, col - d // 2) directions = [UP, DOWN, LEFT, RIGHT] visited += 1 paths.append([row, col, 0]) else: directions.remove(direction) Flotsam and Jetsam You tried to track "dead ends" in your paths, but decided it was too expensive. However, you are still paying a cost for the attempt, by extracting a deadend variable that is never used from a paths entry, and constructing an array with a useless 0 at the end: row, col, deadend = random.choice(paths) ... paths.append([row, col, 0])
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm ... paths.append([row, col, 0]) Remove the , deadend and the , 0. Possible Algorithmic Improvement As the maze fills up, your paths list will fill with many, many positions where it is impossible to move from. It is easy to imagine a case where due to an unfortunate turn in the random walk, one spot is left unvisited. Your code will execute row, col = random.choice(paths) to select a random point to start walking from, try walking in the 4 directions, and then repeat with a new random choice. Consider the 600x600 maze, with a total of 360,000 positions. With one unvisited location, paths will contain 359,999 visited locations, but at most 4 of those will be beside the unvisited spot. The odds of selecting one of those 4 spots is low: 0.001%! On average, it will take about 45,000 iterations, with 1,800,000 walk direction attempts, to randomly select one of those 4 spots necessary to finish the generation. Unfortunately, it can take many, many more. It is not even guaranteed to every finish. Before you execute random.choice(paths), you are sitting at a row, col which you are unable to move from. You randomly selected this location, you would know it is impossible to move from it. There is no point in keeping this location in paths to be selected. You could remove it, so it can never be selected again: paths.remove([row, col]) row, col = random.choice(paths)
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
python, algorithm With this change, the paths list will grow as the maze is initially built, and then start to shrink as the maze approaches completion, ensuring the maze generation will complete. Unfortunately, paths.remove([row, col]) is an \$O(n)\$ operation. It will search for the value from the start of the list, and once it finds it, it would have to move all values in the list after it forward by one position. Removing items from a set is an \$O(1)\$ operation. Since you are not concerned with the order of elements in paths, turning it into a set of (row, col) tuples (because [row, col] lists are not hashable) may provide a speedup. paths = set() ... paths.add((row, col)) ... if len(directions) == 0: in_deadend += 1 paths.discard((row, col)) row, col = random.choice(list(paths)) ... Because sets are not indexable, we need to convert it into a list to use random.choice(). Due to this back-and-forth, you'll need to profile to determine if this change is actually an improvement. Backtracking Profiling shows the set / tuple / paths.discard() change made things slower. Let's try actual backtracking. This will change the appearance of the generated maze, since the new segments will start further along the previous path. Instead of the "Possible Algorithmic Improvement", make the following change. Replace: row, col = random.choice(paths) with: row, col = paths.pop() My generation time for a 500x500 maze dropped in half, but note these are once again incomparable as the maze is being generated in a different fashion and produces a substantially different maze.
{ "domain": "codereview.stackexchange", "id": 43732, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm", "url": null }
c++, c++11, multithreading Title: Parallel factorial algorithm using std::thread Question: This code calculates the factorial of a number on multiple threads. My issue: it is only a little bit faster than the sequential version of it (and I think I know why, I just can't find a way to solve this). I use boost::multiprecision::cpp_int so the limits of default integers are not a problem, the size of integers is only limited by memory. Only showing the relevant parts: // ... other includes ... #include <boost/multiprecision/cpp_int.hpp> #define THREAD_COUNT 4 std::atomic<int> thread_num(1); // global variable // stuff... void threaded_factorial(unsigned long long int num, boost::multiprecision::cpp_int& bigInt) { int threadid = thread_num++; // thread_num is atomic, so this is safe boost::multiprecision::cpp_int N = 1; for (unsigned long long int i = threadid; i <= num; i = i + THREAD_COUNT) { N *=(i); } std::lock_guard<std::mutex> lock(mu); // race condition --> mutex needed bigInt *= N; } // more stuff ... And the call of the function: // ... boost::multiprecision::cpp_int result = 1; std::thread workers[THREAD_COUNT]; for (int i = 0; i < THREAD_COUNT; ++i) { workers[i] = std::thread(threaded_factorial, num, std::ref(result)); } for (int i = 0; i < THREAD_COUNT; ++i) { workers[i].join(); } // ... The results seem correct, but as I said, this is not much faster than sequential code. For example. The calculation of the factorial of 325253 took 67586 ms on 4 threads 76226 ms on a single thread
{ "domain": "codereview.stackexchange", "id": 43733, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, multithreading", "url": null }
c++, c++11, multithreading 67586 ms on 4 threads 76226 ms on a single thread That is some really poor performance. The reason, I think is that the for cycle in the threaded_factorial function roughly takes the same amount of time for each thread to complete, so when the std::mutex mu is locked, (THREAD_COUNT-1) threads have to wait for the one which locked the mutex. This way, most of the work (by far the largest multiplications) is happening in a sequential manner, so the algorithm is really slow. How can I work around this issue and make this work efficiently? Answer: Firstly, some issues with API usage. Using raw std::threads is generally not the way you want to go with this sort of thing: prefer to use std::async. This also means you don't need to pass in by reference for updates, as it can return a value. The other big win from this is that you don't need to lock and perform an update in the thread that is running the calculation; this can be done independently. Firstly, let's modify the threaded_factorial function: constexpr static auto threads = 4U; constexpr static auto test = 325253U; namespace mp = boost::multiprecision; mp::cpp_int thread_fact(unsigned num, int start) { mp::cpp_int n = start; for (auto i = start + threads; i <= num; i += threads) { n *= i; } return n; } To call this, we setup some arrays for the std::futures that will be returned, as well as an array of partial results. std::array<std::future<mp::cpp_int>, threads> futures; std::array<mp::cpp_int, threads> results; for (auto i = 1; i <= threads; ++i) { futures[i - 1] = std::async(std::launch::async, thread_fact, test, i); } for (auto i = 0; i < threads; ++i) { results[i] = futures[i].get(); }
{ "domain": "codereview.stackexchange", "id": 43733, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, multithreading", "url": null }
c++, c++11, multithreading Now, the step where you combine these is actually pretty expensive. Multiplying two numbers that are of this magnitude will be time consuming; let's launch the multiplications in separate threads as well: std::future<mp::cpp_int> x = std::async([&results]() -> mp::cpp_int { return results[0] * results[1]; }); std::future<mp::cpp_int> y = std::async([&results]() -> mp::cpp_int { return results[2] * results[3]; }); auto x_val = x.get(); auto y_val = y.get(); auto z = x_val * y_val; Making these changes, this runs in a bit under 10 seconds for me. In fact, from the profile graph, most of that time is spent doing the combining. Others have pointed out that further algorithmic improvements are possible if you need more speed.
{ "domain": "codereview.stackexchange", "id": 43733, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, multithreading", "url": null }
beginner, python-3.x, classes Title: Equation calculator Question: Function Calculates values for user defined equations. Just a concept right now. I plan to add many more equations. Equations in code Density: $$ p = \frac{m}{v} $$ Speed: $$ s = u + a \cdot t $$ class Equations: def __init__(self) -> None: self.p = lambda m, v: m / v self.m = lambda p, v: m * v self.v = lambda p, m: m / p self.s = lambda u, a, t: u + a * t def calculate() -> None: density = Equations() answer = density.p(1.23, 1.66) print(f'density: {answer:.2f}') speed = Equations() answer = speed.s(3, 4, 5) print(f'speed: {answer:.2f}') if __name__ == '__main__': calculate() Output: density: 0.74 speed: 23.00 Notes I am a beginner so I’m definitely doing things wrong here, suggestions welcome. Is this OOP and classes done right? Background I asked a similar question like this and the answer I got was from a very kind user and was very elegant, however it works for 1 equation, and this users suggestion to make it work for multiple equations went over my head: Other question https://codereview.stackexchange.com/questions/276177/class-to-calculate-values-of-equation-ρ-m-v/276181?noredirect=1#comment547477_276181 Answer: Your use case is quite simple. You said that you wanted to use Sympy, but you're not sure how to generalise to multiple equations. You also want real number assumptions in Sympy (mind you this is different from validation). Your existing class doesn't offer much - it's basically a collection of functions saved as members, which you should not do. Instead consider a class that parses expressions for the sides of an equation; one instance per equation. Suggested import sympy from sympy import Equality, solve, Symbol, Expr def parse_real(expr_str: str) -> tuple[Expr, dict[str, Symbol]]: symbols_expr = sympy.S(expr_str)
{ "domain": "codereview.stackexchange", "id": 43734, "lm_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, python-3.x, classes", "url": null }
beginner, python-3.x, classes symbols = { s.name: Symbol( s.name, real=True, finite=True, nonnegative=True, ) for s in symbols_expr.free_symbols } expr = sympy.parse_expr(expr_str, symbols) return expr, symbols class EqnSystem: def __init__(self, left: str, right: str) -> None: left_expr, left_syms = parse_real(left) right_expr, right_syms = parse_real(right) self.equation = Equality(left_expr, right_expr) self.symbols = left_syms | right_syms def solve(self, **kwargs: float) -> float: unknown, = self.symbols.keys() - kwargs.keys() solved, = solve(self.equation, self.symbols[unknown]) value = solved.subs({ self.symbols[k]: known for k, known in kwargs.items() }) return float(value) DENSITY = EqnSystem('p', 'm/v') SPEED = EqnSystem('s', 'u + a*t') def test() -> None: p = DENSITY.solve(m=1.23, v=1.66) print(f'density: {p:.2f}') s = SPEED.solve(u=3, a=4, t=5) print(f'speed: {s:.2f}') if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 43734, "lm_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, python-3.x, classes", "url": null }
python, pandas, matplotlib, data-visualization Title: Create charts after querying database Question: I'm at the end of the IBM Data Analyst course, and I wanted to ask for a rating of a piece of code I wrote as a solution to its exercises from the final chapter. I know I could write it on the forum of the course, but I will finish it very soon and have no access to the forum before anyone will answer. Exercises: Create a stacked chart of median WorkWeekHrs and CodeRevHrs for the age group 30 to 35. query = "SELECT WorkWeekHrs, CodeRevHrs FROM master WHERE Age BETWEEN 30 AND 35;" dejtafrejm = pd.read_sql_query(query, conn) newframe = pd.DataFrame() newframe['WorkWeekHrs'] = dejtafrejm[['WorkWeekHrs']].median() newframe['CodeRevHrs'] = dejtafrejm['CodeRevHrs'].median() ax = newframe.plot(kind='bar', color=['Blue', 'Yellow'], stacked=True, figsize=(5, 4)) for container in ax.containers: ax.bar_label(container, label_type='center') plt.xticks([]) Create a horizontal bar chart using column MainBranch. query = 'SELECT MainBranch FROM master' df = pd.read_sql_query(query, conn) df[['Total']] = 1 newdf = dief.groupby('MainBranch', axis=0).sum().transpose() ax = newdf.plot(kind='barh', figsize=(15, 6)) for container in ax.containers: ax.bar_label(container) Answer: You haven't indicated what kind of database you're connected to, but: the most important change here is for you to move your aggregation from Pandas into your SQL query. This applies to your median and group sum operations. This is needed for the queries to be scalable, otherwise you're carrying a potentially huge amount of data into application memory that you don't actually need.
{ "domain": "codereview.stackexchange", "id": 43735, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, matplotlib, data-visualization", "url": null }
python, python-3.x, game, wordle Title: Wordle Game clone Question: I am a beginner programmer and have recently finished coding a clone of the game Wordle. I want to know if the way I programmed this game is efficient, solid, and overall good code. I also want to know how I can know whether my code in the future is good or not. Here is my code: (by the way, the opened txt file is a text file with almost 6000 5-letter words from the English dictionary I found online) import random lines = open("5_letter_words.txt", "r").read().splitlines() word = random.choice(lines) word = word.upper() board = { 6 : ["_", "_", "_", "_", "_"], 5 : ["_", "_", "_", "_", "_"], 4 : ["_", "_", "_", "_", "_"], 3 : ["_", "_", "_", "_", "_"], 2 : ["_", "_", "_", "_", "_"], 1 : ["_", "_", "_", "_", "_"] } colorList = { 6 : [39, 39, 39, 39, 39], 5 : [39, 39, 39, 39, 39], 4 : [39, 39, 39, 39, 39], 3 : [39, 39, 39, 39, 39], 2 : [39, 39, 39, 39, 39], 1 : [39, 39, 39, 39, 39] } def boardprint(): global board, colorList final = [] for x in range(len(board)): spots = [f"\033[{col}m{board[x+1][idx]}\33[0m" for idx, col in enumerate(colorList[x+1])] l = ' '.join(spots) final.append(f"| {l} |") print('\n'.join(final)) return colorList guess = "" result = {} def checkRight(guess, word, row): global board, colorList GuessCheckDouble = {i:guess.count(i) for i in guess} WordCheckDouble = {i:word.count(i) for i in word} result = {key: GuessCheckDouble[key] - WordCheckDouble.get(key, 0) for key in GuessCheckDouble.keys()} updateRow = [] colorRow = [] for x in range(len(word)): if guess[x].upper() == word[x]: # green letter = guess[x] updateRow.append(letter) colorRow.append(32)
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle elif guess[x].upper() in word and result[guess[x]] == 0: # yellow letter = guess[x] updateRow.append(letter) colorRow.append(33) else: # grey letter = guess[x] updateRow.append(letter) colorRow.append(30) board.update({row : [updateRow[0], updateRow[1], updateRow[2], updateRow[3], updateRow[4]]}) colorList.update({row : [colorRow[0], colorRow[1], colorRow[2], colorRow[3], colorRow[4]]}) winRow = [32, 32, 32, 32, 32] if colorRow == winRow: boardprint() print("YOU WON!") exit() return board word = word.upper() word = list(word) print("hello! welcome to \033[32;1mWORDLE\033[0m") print("\tTry to guess a 5-letter word in 6 guesses or less.\n\t\tIf a letter is \033[32mgreen\033[0m, then it is in the right place,\n\t\tIf a letter is \033[33myellow\033[0m, then it is in the wrong place, \n\t\tif a letter is \033[30mgrey\033[0m, then it is the wrong letter. \nREMEMBER\n\t - \033[1mNO\033[0m proper nouns, \n\t - \033[1mNO\033[0m punctuation, hyphens, or accent marks.") print() boardprint() print() numList = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"] z = 0 while z < 6: print() guess = input(f"{numList[z]} GUESS > ") guess = guess.upper() guessL = guess.lower() guess = list(guess) if len(guess) == 5 and guessL in lines: checkRight(guess, word, z+1) boardprint() z += 1 else: print("Please enter a valid word.") print() boardprint() if z == 6: wordStr = "".join(("".join(item) for item in word)) print("\tYou \033[1mLOST\033[0m lol! The word was", wordStr.lower(), "... (Loser)") exit() Answer: I appreciate you came here as a beginner and you're asking on how to improve. Not every developer wants to get feedback.
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle I want to know if the way I programmed this game is efficient IMHO there is no need to worry about efficiency in this program. The main delay/bottleneck is the input of the user. Do not confuse efficiency with effectiveness. Efficiency is about stuff done per time. Effectiveness is whether the firework pops and makes an effect. You can have many fireworks done per time, but if it does not pop, nobody is impressed. As a beginner, always go for effectiveness. Premature optimization is the root of all evil, Donald Knuth said. [...] solid, and overall good code. I assume that you are learning at free will, which is the best. So I will do as thorough of a review as I can, so that you can make progress faster. Main method I wanted to do a top down review, starting at the highest level possible, so I was looking for a main() method - but did not find one. For me as a reader of the code, I'd like to see the if __name__ == "__main__": pattern somewhere. That's typically easy to spot and somewhat expected in Python programs. Instead, some code is at the top of the file and some code is between methods and some code is at the bottom of the file. Well, so let me start reading from beginning to end instead... Naming You have a variable called lines which reads a file called words. Is each line a word? If so, you can call the variable words instead. Hint: use an IDE that has Refactoring features, like PyCharm (go to the name and press Shift+F6). Consistency From line 101 (if len(guess) == 5 and guessL in lines:) I see that it's expected that the file contains all words in lower case letters. Otherwise the in check will not work. In line 5 (word = word.upper()) and line 98 (guess = guess.upper()) you make the words upper case. To me, this adds unnecessary complexity. IMHO, Worlde games are upper case, so just stick to upper case and things will be easier. words = open("5_letter_words.txt", "r").read().upper().splitlines() word = random.choice(words) # upper is here ----^
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle Pattern initialization The initialization of the board pattern and colorList pattern seems to violate the DRY principle of clean code. You can try a dictionary comprehension. I also found it strange to see the patterns begin at 6 and then decrement. The order in a dictionary is irrelevant, so starting at 1 seems more natural. Programmers might find it even more natural to start at 0. If you start at 0, you might even get rid of the dictionary and make it a list instead (I can't tell at this stage whether it will be beneficial). Your code essentially becomes a one-liner: board = {n+1: ["_"]*5 for n in range(6)} colorList = {n+1: [39]*5 for n in range(6)} print(board) print(colorList) Warning: be aware of unwanted side effects when multiplying lists. Globals The globals in line 27 (global board, colorList) impose an unnecessary dependency between your main code (outside of boardprint()) and the method. You can never use boardprint() for anything else than printing exactly board with colorList. Make these two parameters to the function. def boardprint(board, colorList): Complex list comprehension In line 31, you have a list comprehension, but it interleaves with other complex code, like the color formatting. Yes, before I have told you to use list comprehension to avoid duplication. This time I want you to not use list comprehension because of separation of concerns. This line of code has 2 purposes: formatting in color and looping. Separate them. for idx, col in enumerate(colorList[x + 1]): spots += f"\033[{col}m{board[x + 1][idx]}\33[0m" Mixture of loop with list comprehension In boardprint() I can only see a single for loop. For a 2D board, I expected to see a nested loop, looping over x and y. So, convert the list comprehension into a loop: for idx, col in enumerate(colorList[x + 1]): spots += f"\033[{col}m{board[x + 1][idx]}\33[0m"
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle Wait... that's the same code as before! So you have 2 reasons to do it! Unused return value boardprint() has a return value in line 36, but it's never used. Remove it. Type hints The method definition in line 43 (def checkRight(guess, word, row):) leaves it open what the type of the parameters are. Is guess the number of the guess (guess 1, 2, 3 ...) i.e. an integer or is it the guessed word, i.e. a string? Type hints will help the reader understand what it might be. def checkRight(guess: str, word: str, row: int): Naming (again) Even when knowing the type, the method signature is still not clear to me: def checkRight(guess: str, word: str, row: int): Better names would be guessedWord and correctWord. At this time in the review, I have no clue what row is good for. Hopefully I'll find a better name for that as well. Method doing more than one thing. Line 44 (global board, colorList) makes use of globals once more. Make it parameters as well. But it's starting to be many parameters already. Maybe this method is doing too many things. checkRight is from line 44 to 80. That's too long. It's another indicator that the method does too much. Let's see... It seems to me that the method should decide whether characters become grey, yellow or green. However, it's not only doing that, but also updating the board and updating the colors and deciding whether the game is over Split this method into 4 smaller methods and it'll be much simpler to read, understand and debug. Magic numbers checkRight() has a few constants that are related to colors. We call such numbers "magic numbers", because they appear out of nothing with no semantics. The color comment is far from the usage (at least 4 lines). We typically give them names. Since they are constants, we agree to make them upper case: GREEN = 32 YELLOW = 33 GREY = 30
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle Likewise you can do that for the initial color (whatever color 39 is). The number 6 in line 8 (initialization of board), line 17 (initialization of colorList), line 95 (while z < 6) and line 110 (if z == 6:) seems to have a special meaning as well. Either replace it by a constant as well, or perhaps by an expression instead (e.g. len(board)). Very long line Line 88 is more than 300 characters long. It's quite hard to figure out what will be printed. Take advantage of multiline strings like print( """ \tTry to guess a 5-letter word in 6 guesses or less.\n \t\tIf a letter is \033[32mgreen\033[0m, then it is in the right place,\n \t\tIf a letter is \033[33myellow\033[0m, then it is in the wrong place, \n \t\tif a letter is \033[30mgrey\033[0m, then it is the wrong letter. \n REMEMBER\n\t - \033[1mNO\033[0m proper nouns, \n \t - \033[1mNO\033[0m punctuation, hyphens, or accent marks. """ ) That way it will be immediately obvious what will be printed. Move code into methods The welcome message and instructions could make a new method called instructions() or so. Start indexing at 0 Lines 93 to 95 use 0-based indexing: numList = ["FIRST", "SECOND", "THIRD", "FOURTH", "FIFTH", "SIXTH"] z = 0 while z < 6: But before we had 1-based indexing for board and colorList. So, a 1-based index does not seem to be a general style here. Therefore I tend to start at 0. This will also simplify line 31 (enumerate(colorList[x + 1])) and that part of the code gets rid of the magic 1. Value the user In real software development, the user will pay for the software. Try to value him. A statement like LOST lol! The word was ... (Loser)
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle LOST lol! The word was ... (Loser) may be the trigger that this customer never buys something from you again. Perhaps the user is only 8 years old and does not know many words yet. Perhaps the user is 93 and has made best efforts on solving the puzzle while having Alzheimer. No need to laugh at them or make fun of them. Some more stuff I found while doing the refactoring myself... I noticed that there is an unnecessary word = word.upper() in line 83 Converting the word into a list of characters in line 84 (word = list(word)) is confusing. Just let it be a string. You can already iterate over a string. This also saves you from converting it back into a string in line 111 (where the join is done twice, for some reason): wordStr = "".join(("".join(item) for item in word)) 4. There are 4 places where printboard() is called. Once the code is sorted a bit, you hopefully see that it's easy to reduce that to 2 (or even 1). I'm not a native speaker, but I renamed numList to ordinals, because it's not a list of numbers, but a list of counted numbers. guess = "" is unnecessary, because it's assigned at input() anyway result = {} can be removed, because it's not used. if guess == word: is a more trivial way to check for a win instead of comparing colors winRow = [32, 32, 32, 32, 32] if colorRow == winRow: The length check if len(guess) == 5 is redundant as long as all words in your word list have 5 characters. In checkRight(), all paths of the if/else contain the same code, so you can put these lines out of the if/else: letter = guess[x] updateRow.append(letter) guess[x].upper() within checkRight(): the upper() is redundant, since the user input has already been converted to upper case. guess[x] is equivalent to letter after point 10. Instead of having updateRow in checkRight() and later update board by updateRow, update board directly. Same for colorRow.
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
python, python-3.x, game, wordle Same for colorRow. Oof... Well, that was a lot, wasn't it? Actually I don't exactly know how your code looks like, after you apply all suggestions. Is it worth the effort? Certainly! Go through the code, make it better and compare the new code to the old code. I went from 113 lines to 74, which is 35% reduction of code. It's also much easier to make changes to it. Is the code perfect? Not yet. You might want to keep on learning and get feedback again. At some point, you may want to learn about classes and objects, which can give you a totally new programming style. But that would be too much for now. Object oriented programming will allow you to combine board and colorList into a single unit, so that it's impossible to make them different of sizes. The board might be able to print itself, etc.
{ "domain": "codereview.stackexchange", "id": 43736, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game, wordle", "url": null }
mysql, bash, email Title: Weekly MySQL database backup Question: I haven't used Unix, etc. for 40 years, so I am a bit rusty. I need to back up the databases on my website(s) once a week and then retrieve them automatically from my development machine. So this is step one and is working fine as a crontab job on Apache. It emails me a message with status/error. I am creating a folder with the date as name and keeping 14 backups. I am not using a loop for the databases, because each one has a different user/pwd combination. I don't see it dangerous to have the username and passwords here. If someone has root access, they can access the database anyway. The file size is returned as well. The start time and finish time are returned, so I can calculate how long the job took. How can make it more generic, or faster, or safer? Am I catching all the errors? #!/usr/bin/bash TIMESTAMP=$(date +"%F") BACKUP_DIR=backup MYSQLDUMP=/usr/bin/mysqldump STAT=/usr/bin/stat EMAIL=*** KEEP="+14" MSG=tmp/backup_msg echo "Date: $(date)" > $MSG echo "Hostname: $(hostname)" >> $MSG echo " " >> $MSG echo " " >> $MSG mkdir -p "$BACKUP_DIR/$TIMESTAMP" 2>> $MSG DB=xxx_directory BKP=$BACKUP_DIR/$TIMESTAMP/db_biz_directory.sql echo "Backing up '$DB' to '$BKP'" >> $MSG $MYSQLDUMP -u username -ppassword $DB > $BKP 2>> $MSG SIZE=$($STAT -c%s $BKP) 2>> $MSG echo "Filesize: $SIZE" >> $MSG echo " " >> $MSG DB=xxx_software BKP=$BACKUP_DIR/$TIMESTAMP/db_swr_software.sql echo "Backing up '$DB' to '$BKP'" >> $MSG $MYSQLDUMP -u username -ppassword $DB > $BKP 2>> $MSG SIZE=$($STAT -c%s $BKP) 2>> $MSG echo "Filesize: $SIZE" >> $MSG echo " " >> $MSG echo "Removing excess backups" >> $MSG find $BACKUP_DIR* -mtime $KEEP -exec rm {} \; >> $MSG 2>> $MSG echo "Finished: $(date)" >> $MSG mail -s "MySQL Backup script has run" "$EMAIL" <$MSG rm -f $MSG
{ "domain": "codereview.stackexchange", "id": 43737, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql, bash, email", "url": null }
mysql, bash, email echo "Finished: $(date)" >> $MSG mail -s "MySQL Backup script has run" "$EMAIL" <$MSG rm -f $MSG Answer: Overall This is totally decent code and not too difficult to maintain. Your variable names make sense and you've made some effort at not repeating yourself, other than the lack of a loop which you own up to in your question. There are definitely some ways to make this better, but you'll have to decide how much it is worth it. High-level suggestions
{ "domain": "codereview.stackexchange", "id": 43737, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql, bash, email", "url": null }
mysql, bash, email Two major things stick out here - the use of plain text passwords and the repeated code that that leads to. Let's tackle the passwords first. MySQL provides a more secure way to store your passwords. If your MySQL isn't that new, you can always go back to the ~/.my.cnf style of configuration and create a config file specific to each database. Either way, your username and password are stored in a place that will work for running the mysql client interactively as well as for mysqldump. Once you've got it so your passwords are not causing your code to need to be different for handling each database you can build the loop you mentioned. This will be handy later if you ever add more databases. I'd recommend making this into a shell function so your code can more self-explanatory and reusable. Another function that would be wise to build is one for appending to your $MSG file. You asked about other error conditions that you can check. The biggest one that comes to mind is filling up the disk. It is a good idea to check to make sure you haven't filled up the drive and ended up with truncated backups. Another thing to check is that your mysqldump is giving you a reasonably sized file. If it is less than 1k you probably have a problem to dig into. You are outputting this information, but it would be good to highlight if there is an issue without expecting the person reading the email to pay attention to all of these details. Humans get tired and aren't great at being so vigilant for many years. And you're already half-way there since you're using stat to get the file size. If you're really keen on making this fault-tolerant, then there's a chance that you're not able to make the directory. There's no point in continuing if that fails. You can do something like mkdir ... || echo "mkdir failed" >> "$MSG" && exit 1. Best practices suggestions.
{ "domain": "codereview.stackexchange", "id": 43737, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql, bash, email", "url": null }
mysql, bash, email Best practices suggestions. It is a good practice to quote your variable substitutions. echo " " looks a bit weird to me: you can get rid of the space in the quotes and still get a blank in our $MSG file. If you ever wanted to run your script in parallel you would have conflicts over the $MSG file. Using mktemp would give you unique names for each process. Check out shellcheck. It can also be run locally.
{ "domain": "codereview.stackexchange", "id": 43737, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "mysql, bash, email", "url": null }