What is the idiomatic way to assoc several keys/values in a nested map in Clojure?

Here are a couple of ways. user> (update-in person [:name] assoc :first-name “Bob” :last-name “Doe”) {:name {:middle-name “Michael”, :last-name “Doe”, :first-name “Bob”}} user> (update-in person [:name] merge {:first-name “Bob” :last-name “Doe”}) {:name {:middle-name “Michael”, :last-name “Doe”, :first-name “Bob”}} user> (update-in person [:name] into {:first-name “Bob” :last-name “Doe”}) {:name {:middle-name “Michael”, :last-name “Doe”, :first-name “Bob”}} user> … Read more

Rails idiom to avoid duplicates in has_many :through

As long as the appended role is an ActiveRecord object, what you are doing: user.roles << role Should de-duplicate automatically for :has_many associations. For has_many :through, try: class User has_many :roles, :through => :user_roles do def <<(new_item) super( Array(new_item) – proxy_association.owner.roles ) end end end if super doesn’t work, you may need to set up … Read more

Read a file and get an array of strings

DK.’s answer is quite right and has great explanation. However, you stated: Read a file and get an array of strings Rust arrays have a fixed length, known at compile time, so I assume you really mean “vector”. I would write it like this: use std::{ fs::File, io::{prelude::*, BufReader}, path::Path, }; fn lines_from_file(filename: impl AsRef<Path>) … Read more

What C++ idioms should C++ programmers use? [closed]

By far the single most important “pattern” to learn and know that’s (nearly) unique to C++ is RAII (Resource Acquisition Is Initialization). Edit: (To answer extra question edited into the question). You use RAII primarily to (semi-)automate resource management. The most obvious use is freeing resources owned by objects when the owning objects go out … Read more

C++ code for state machine

I was thinking in a more OO approach, using the State Pattern: The Machine: // machine.h #pragma once #include “MachineStates.h” class AbstractState; class Machine { friend class AbstractState; public: Machine(unsigned int _stock); void sell(unsigned int quantity); void refill(unsigned int quantity); unsigned int getStock(); ~Machine(); private: unsigned int stock; AbstractState *state; }; // ——– // machine.cpp … Read more

Idiomatic use of std::rel_ops

The way operator overloads for user defined classes was meant to work is via argument dependent lookup. ADL allows programs and libraries to avoid cluttering up the global namespace with operator overloads, but still allow convenient use of the operators; That is, without explicit namespace qualification, which is not possible to do with the infix … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)