Code comment:

static long factorial(int num){
    long factorial = num;
    for (int forBlockvar = num; forBlockvar > 1; forBlockvar--) {
        factorial = factorial * forBlockvar;
    }
    return factorial / num;
}

You are starting your factorial = num, then multiplying it by num in the first iteration of the loop, then dividing by num at the end.  Starting with factorial = 1, or starting  forBlockvar = num - 1 (I prefer the second) will remove the need to divide at the end.  You can also return 1 if the input is less than 2.

static long factorial(int num){
    if(num < 2) {
        return 1;
    }
    long factorial = num;
    for (int forBlockvar = num - 1; forBlockvar > 1; forBlockvar--) {
        factorial = factorial * forBlockvar;
    }
    return factorial;
}

You could also implement this function recursively.

static long factorial(int num){
    if(num < 2) {
        return 1;
    }
    return num * factorial(num - 1);
}

General:

What do you mean by finding the permutations of 2 numbers?  There are 2 permutations of 2 numbers [x, y]: [x, y] and [y, x].

EDIT

I think I know what you are trying to do now... You want to know how many permutations are available by selecting r objects out of a total of n.

The basic formula for that is n! / (n-r)!.  However, this means calculating the factorial of (n-r) twice (in our example, we have 8*7*6*5*4*3*2*1 / 2*1, but with a lower r the overlap will be greater).

Instead of calculating the complete factorial for both numerator and denominator, there is a way to calculate the value of the numerator such that the denominator is always going to be 1.  That means we eliminate one factorial calculation, and reduce the other.  I'm going to let you think about it a bit before just giving the answer.

EDIT 2

Since you have figured out what I was hinting at, I'll explain it further.

n! can be represented as n*(n-1)*(n-2)*(n-3)...(2)*(1).  When r is less than n and greater than 0, n! can be then be represented as n*(n-1)*(n-2)...(n-r+1)*(n-r)*(n-r-1)*(n-r-2)...(2)*(1).

(n-r)! is (n-r)*(n-r-1)*(n-r-2)...(2)*(1).

Therefore, our numerator is n*(n-1)*(n-2)...(n-r+1)*(n-r)*(n-r-1)*(n-r-2)...(2)*(1), and our denominator is (n-r)*(n-r-1)*(n-r-2)...(2)*(1).  Cancelling like terms, we have n!/(n-r)! = n*(n-1)*(n-2)...(n-r+1).

static long permute(int totalItems, int numToPick) {
    long permutations = totalItems;
    while (--numToPick > 0) {
        permutations *= --totalItems;
    }
    return permutations;
}

You should ensure that 0 < numToPick <= totalItems, and totalItems > 0.


Faster solution for data grouping to determine highest frequency than iteration with for loops

I have recast your loop, and the code is below.  I will discuss a couple of points.

pandas.Dataframe.groupby() allows working with specific groups at a time

Your current code is working with the entire dataframe for each region.  Pandas has the groupby to allow you to work with a specific regions data at one time.  I don't know if it is any faster, but to my eye is easier to read.

desired_cols = [region_col, main_dish_col, main_dish_prep_col]
for region, group in df[desired_cols].groupby('US Region'):
    ....

Using pandas.Series

A pandas.Series is a data structure that is basically two vectors.  One vector is the data, the other is the Index. In this code:

main_dish[is_in_region].value_counts().keys().tolist()[0]

.value_counts() returns a Series.  You then ask for the keys(), turn that into a list and the take the first element.  This is more naturally done by just taking the first elment of the index like:

.value_counts().index[0]

Main Loop Code:

df = pd.read_csv('thanksgiving-2015-poll-data.csv', encoding="Latin-1")
region_col = 'US Region'
main_dish_col = 'What is typically the main dish at your Thanksgiving dinner?'
main_dish_prep_col = 'How is the main dish typically cooked?'
desired_cols = [region_col, main_dish_col, main_dish_prep_col]

regional_entire_meal_data_rows = []
for region, group in df[desired_cols].groupby('US Region'):
    main_dish = group[main_dish_col]
    main_dish_prep = group[main_dish_prep_col]

    most_common_dish = main_dish.value_counts().index[0]
    prep_types = main_dish_prep[main_dish == most_common_dish]
    most_common_prep_type = prep_types.value_counts().index[0]
    regional_entire_meal_data_rows.append(
        (region, most_common_dish, most_common_prep_type))


Chain of Responsibility pattern (hereby "CORP") includes two things: iteration and "handling".
IMO, the iteration part, at least in modern programming languages such as Python and Java, can be easily "extracted" to an external iteration. So eventually the code could look like:
result = None
for handler in handlers:
  temp_result = handler.handle(request)
  if temp_result is not None:
    result = temp_result
    break
if result is not None:
  # handled!

I think this approach is simpler than maintaining the inner chain, and it has the same impact.
In CORP, once a handler was found, and it can handle the input, no additional handlers should be executed. It's quite similar to filtering.
However, I think that the code we have in your question tries to execute as many handlers as it can (as it tries to enrich a wider context). So maybe CORP is not really needed here.
Perhaps you can have enriching classes, that have a method enrich that accepts a request and a context, so that every enriching class could either change the state of the context object, or leave it as is:
class BaseEnricher:
  def enrich(request, store):
    pass


Python has some neat features, some of which might seem familiar from C++ and some not. The Python standard library is also very powerful. These comments are meant to be complementary to the answer by @Reinderlein, I will not repeat the useful advice given there.

You can compare multiple things: MINIMUM_SIZE < x.size < MAXIMUM_SIZE.
The itertools module:

from itertools import chain
files = list(chain.from_iterable(
    get_files(x, lambda x: MINIMUM_SIZE < x.size < MAXIMUM_SIZE)) for x in args.dirs))

Decorators, which makes code involving getters easy with property, which you are already using, but not to it's full potential:

@property
def part_hash(self):
    if self._part_hash is None:
        h = hashlib.sha1()
        with open(self.name, 'rb') as f:
            h.update(f.read(self.part_hash_size))
        self._part_hash = h.hexdigest()
    return self._part_hash

Note that self.part_hash_size is the same as MyFile.part_hash_size, unless you overwrite it in the instance (and be careful of mutating mutable objects). This gives you additional flexibility.
(Python 3.6+) Format strings, which utilize the format syntax and make it even better:

def __str__(self):
    return f"{self.name} is {self.size}"

def __repr__(self):
    return f"<{self.__class__.__name__} {self.name}:{self.size}>"

(Python 3.8+) Assignment expressions, which allow you to shorten some while loops:

@property
def full_hash(self):
    if self._full_hash is None:
        h = hashlib.sha256()
        with open(self.name, 'rb') as f:
            while buf := f.read(self.part_hash_size):
                h.update(buf)
            self._full_hash = h.hexdigest()
    return self._full_hash

Truthiness of non-empty containers: if l is the same as if len(l) > 0 for any container in the standard library (and should also be the same for any custom classes you create).
Modules are automatically in their own namespace. No need to come up with names like MyFile, just call it File. You should avoid overwriting built-in names, but everything else is fair game, since you can always import them from another module and prefix them with the module name.
List comprehensions are nice, but sometimes the functions in operator give you more readability. Not really in this case, but as a demonstration:

from operator import attrgetter
a = [x.name for x in dup]              # in your code
b = [getattr(x, "name") for x in dup]  # if the attribute name is a variable
c = map(attrgetter("name"), dup)       # using operator instead
assert a == b == list(c)

Generators allow you to get rid of storing the full result in a list only to then operate on every item of the list. Instead, generate the next item whenever you are done processing the previous one:

def recursive_dir(dir, pattern, filter):
    for root, dirs, files in os.walk(dir):
        for file in files:
            if fnmatch.fnmatch(file, pattern):
                if filter(f := File(os.path.join(root, file))):
                    yield f

Or, with a generator expression added and using the yield from keyword:

def recursive_dir(dir, pattern, filter):
    for root, dirs, files in os.walk(dir):
        yield from (f for file in files
                    if fnmatch.fnmatch(file, pattern)
                    and filter(f := File(os.path.join(root, file))))

As to your actual algorithm, you want to group together "equal" items, for some measure of equality. Currently you are comparing each file against each other file, so your algorithm is \$\mathcal{O}(n^2)\$. Instead, just define how two files compare and what the hash should be:

def __eq__(self, other):
    if not isinstance(other, self.__class__):
        return False
    return self.part_hash == other.part_hash and self.full_hash == other.full_hash

def __hash__(self):
    return int(self.part_hash, base=16)

Then you can just put them into a dictionary, which is \$\mathcal{O}(n)\$, because you only need to iterate over the files once:

from collections import defaultdict

def groupby_hash(files):
    duplicates = defaultdict(list)
    for f in files:
        duplicates[f].append(f)
    return duplicates

def files_with_duplicates(files):
    groups = groupby_hash(files).values()
    return list(filter(lambda x: len(x) > 1, groups))

This uses the fact that when putting a hashable object into a dictionary, it is not just put into a slot according to its hash. If two objects have the same hash, they are also compared by equality. This way only the part_hash should be used if there are no duplicates of it and the full_hash is used to make sure they are actually full duplicates. Sometimes the full_hash will still be calculated anyway because of regular collisions. You can test that this is the case for example like this:

files = list(recursive_dir(".", "*", lambda f: os.path.isfile(f.name)))
len(files)
# 1448
d = groupby_hash(files)

# There are files which are unique and their `full_hash` has never been computed
sum(map(lambda f: f._full_hash is None and len(d[f]) == 1, files)))
# 759

# The `full_hash` has been computed for all files with duplicates
sum(map(lambda f: f._full_hash is not None and len(d[f]) > 1, files))
# 93
sum(map(lambda f: f._full_hash is None and len(d[f]) > 1, files))
# 0

# But there are some files without duplicates, whose `full_hash` has been computed
sum(map(lambda f: f._full_hash is not None and len(d[f]) == 1, files))
# 596


Extract html content based on tags, specifically headers

Currently, you are matching a single h1 tag only, but, from what I understand, you want to catch all the "header" elements. There are multiple ways to do that.

One is with a regular expression:

headers = soup.find_all(re.compile(r"^h"))

Or, with a lambda function:

headers = soup.find_all(lambda tag: tag and tag.name.startswith("h"))

Or, with a list of explicitly specified tags:

headers = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5'])

Note that in order to get the header texts, you would use .get_text() method:

[header.get_text() for header in headers]

Other notes:

if every item returned from tqdm(data) consists of two items, you can unpack them in a for loop:

for html, url in tqdm(data):

Then, you can use html instead of x[0] and url instead of x[1].
if you are going to go with a regular expression approach to match the headers, you should pre-compile the expression - define it as a constant:

HEADER_PATTERN = re.compile(r"^h")

you can use json.load() to read JSON from a file directly, replace:

data = json.loads(open(local_path).read())

with:

with open(local_path) as input_file:
    data = json.load(input_file)

If performance matters:

you can use a faster JSON parser: ujson instead of json
use lxml instead of html.parser as a BeautifulSoup underlying parser
you can parse header elements only with SoupStrainer ignoring all other elements - this should boost HTML parsing performance as well

Improved code (with some of the suggestions applied):

import re

from bs4 import BeautifulSoup, SoupStrainer
from tqdm import tqdm
import ujson

HEADER_PATTERN = re.compile(r"^h")

def get_headers_from_json(local_path):
    """
    The function takes a json file with html_body and returns a list of headers.
    It parses the headers, based on tags starting with 'h'.
    It also parses urls and return them in a tuple: (headers, url)
    """
    with open(local_path) as input_file:
        data = ujson.load(input_file)

    parse_only = SoupStrainer(HEADER_PATTERN)
    return [
        ([header.get_text() for header in BeautifulSoup(html, 'lxml', parse_only=parse_only)(HEADER_PATTERN)], url)
        for html, url in tqdm(data)
    ]


Project Euler 3: Getting the largest prime factor of a number

There's nothing really wrong with your code but here's a slight rewrite using pattern matching which is arguably a more functional style than if ... then ... else. I also rearranged the args to eliminate the unnecessary n parameter on the outer function.

let primeFactors =
    let rec recPrimeFactors primes i = function
        | n when 2L*i > n -> n::primes
        | n -> match n % i with
               | 0L -> recPrimeFactors (i::primes) 2L (n / i)
               | _ -> recPrimeFactors primes (i + 1L) n
    recPrimeFactors [] 2L

600851475143L |> primeFactors |> List.head |> printfn "%d"


Neither printf() nor bool would cause a significant performance impact.  One reason could be that you're looping through a huge number which, depending on the system, could be as low as 18446744073709551615.  Doing so in serial would likely take a long time for such a range, and you can always consider adding parallelization where feasible.

Beyond that, any slowdown would be in is_prime().  Not only are there are a few conditionals, which could involve slowdown from branch prediction, but there's another loop that could take a while.  You may consider looking for pre-existing prime algorithms elsewhere, which could be faster than yours.  That should help improve runtime considerably.


Are these try/catch blocks cluttering the code?

Your convert function should be pure.

convert should be doing one thing and one thing only, and that is to convert the given string to int. All those checks you do are not useful because they can easily be performed in the function that calls convert.

int convert(const std::string& text) {
    return std::stoi(text);
}

Your convert function is not needed.

Seeing as after changing it to a pure function, it is now acting as a wrapper to another function call, you don't need it anymore, and it can now be replaced by the function it calls, std::stoi.

Move convert logic elsewhere

Move all the logic from within the convert method to your overloaded function, std::istream& operator >> (std::istream& is, Grid_row& grid_row).

std::istream& operator >> (std::istream& is, Grid_row& grid_row) {
    std::size_t fin;
    int val;

    for (std::string term; is >> term; ) {
        try {
            val = std::stoi(term, &fin);
            if (fin != term.size()) {
                std::cerr << "Could not fully convert " + text + " to integer. Value was converted to " + text.substr(0, fin) + "." << '\n';
            }
        } catch(const std::exception& e) {
            std::cerr << "Due to error: \"" + std::string{e.what()} +"\"; Could not convert " + text + " to integer. Value was converted to 0." << '\n';
        }

        grid_row.push_back(val);

    }
    return is;
}

Now all you have is one try-catch, which is really all that is needed


Split an array into m subarrays such that the largest subarray sum is minimized

(Sort of) Unnecessary OOP

A lot of things like LeetCode will require that the solution is in a class for likely submission reasons, but if we concern ourselves with only the task at hand, I would recommend you get rid of the class and just use functions for this. (And if get rid of the unnecessary class, you'll shorten the code, although, I wouldn't encourage you to be preoccupied with shortening your code.)

Also, if you had to keep the class (for whatever reason), observe:

def __init__(self, nums, m):
    self.nums = nums
    self.m = m

When you pass parameters like this, you can reuse them over and over again. They are sort of like pseudo-global variables. So you would need to do:

def is_valid(self, nums, m, n):

it would just be:

def is_valid(self):

and (in general) you would access self.m and self.n.

Iterate over the iterables, not over the len of the iterable.

Unless you are mutating nums (which I don't believe you are) the more idiomatic way of doing this is iterating through the iterable so:

for i in range(len(nums)):

becomes:

for num in nums:

and instances of nums[i] are replaced by num, for example if nums[i] > n: becomes if num > n:.

Side note: if you were to need the value i and nums[i], you might want to consider utilizing enumerate if you need both.


Simple PHP image upload with error handling

Rather than generate the full array of elements that pathinfo() generously offers only to access one value, use the PATHINFO_EXTENSION flag/option (the second parameter) to only ask for what you need.
For best efficiency, don't perform any  unnecessary processes for disquaified incoming data.
If you are going to declare errors at the start as an empty array, you won't need to call empty() which checks if the variable does not exist or if it is empty/falsey/null/zeroish.  You can more simply use !$errors.  Alternatively, don't declare the empty errors array and then use empty to perform the double check.
I assume that there is no point to generating a filename for an invalid submission, so I don't think that I'll support passing it with errors.
I try to avoid declaring single-use and temporary variable where possible.  In this case, I'd avoid temporary variable by always dealing with the array to be returned at the end.

How my recommendations boil down...

function upload_image($path, $file) {
    if ($file["size"] > 2000000) {
        $outcome['errors'][] = "The image cannot be greater than 2MB";
    }

    $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION)); // force lowercase for uniformity

    if (!in_array($ext, ["jpg", "jpeg", "png"])) {
        $outcome['errors'][] = "The image can only be in .jpg, .jpeg or .png format.";
    }

    if (empty($outcome['errors'])) {
         // for the record, randomness does not guarantee uniqueness
        $outcome['name'] = uniqid() . '.' . $ext;
        move_uploaded_file($file["tmp_name"], $path . $outcome['name']);
    }

    return $outcome;
}

If you like rabbit holes, here's a good read regarding the security aspects of your task: https://stackoverflow.com/q/6484307/2943403


It seems difficult to comment on the meaningfulness of your proposed solution. You are the one to decide on that since you know the context around your problem. With that being said, I'm afraid there is not much to go on here.
Nevertheless, one observation I make about your code is that the checks use .loc to locate rows that receive a "non-OK", and finally, after all checks, you use a fill to turn nans into "OK". To make your code more concise and likely faster, consider using np.where. So for instance, your check_1 would be turned into:
df["check_1"] = np.where(
   (df['Amount decided'] == 0) | (df['Amount decided'].isna()),
   "Amount decided is 0 or NaN", "OK")

Also, I would rename check_N into something that actually means a little more, like amount_check for check_1 and so on.


Using Pythagoras' Theorem to Check Point Distance

There are several reasons why the code does not work.

Here's the body of the first loop for generating points, in pseudo-code:

Pick a random point (x, y)
for t in tileSet:
    Compute distance between (x, y) and t
    while distance is wrong:
        Pick another random point (x, y)
        Recompute distance between (x, y) and t

The problem here is that when you pick another random point (x, y), you only test it to see if it has the wrong distance from the particular point t. But if (x, y) has the wrong distance from one of the previous points in tileSet, you'll never find out because that will never be tested.
The second loop has the same problem. Again, in pseudo-code:

for t1 in tileSet:
    for t2 in tileSet:
        Compute distance between t1 and t2
        while distance is wrong:
            Pick another random point t1
            Recompute distance between t1 and t2

The new random point t1 might be the wrong distance from one of the previous points in tileSet, but that will never be tested.
Additionally, after picking the new random point t1, the code doesn't update tileSet to replace the old point with the new one.


Closure handling in javascript / jquery ajax

It doesn't look like your class has any data, so I must question what's the point. Any instance of the class
would be equal to each other.

Your constructor is also doing a lot of real work, constructors should just initialize the object.

You can also do what you are doing without manual closure plumbing by using jQuery's proxy:

function ConfigViewer() {
    this.createUIComponents();
    this.ajaxLoadData("/adminData").then($.proxy(this.successHandler, this));
}

ConfigViewer.prototype.successHandler = function( data ) {
     this.populateUICoponents(data);
};

ConfigViewer.prototype.ajaxLoadData = function(url) {
    return $.ajax({
       url : url
    });
};


Find whether a given number is a perfect square or not

Presentation

I have re-indented your code, I do not know how your code is on your side but you should definitly indent it properly.
Also, you should remove useless lines.

Naming

check is not a good function name. isPerfectSquare would probably be easier for everyone to understand.

Documentation

Is it a good habit to add some documentation telling what your code is supposed to do. In your case, it could be nice to also tell the reader how it works.

  The expression for the nth square number is n2. This is also equal to the sum of the first n odd numbers.

Types

You can use the bool type in C++.


The best thing you could do is let EF do what it's good at... You don't need to save every single time you add an entity - let EF track the changes in its DbSets repositories and then save the changes in the
DbContext unit of work.

As a more general point - why aren't you saving the whole DomainModel at once? I'd expect to just be able to do:

context.DomainModels.Add(someDomainModel);
await context.SaveChanges();

I've hinted at it but I'll say it outright - you get very little to no benefit in writing Repositorys wrapping the db context. It's just not worth it.

I'm not going to comment on the bad naming because I'm guessing that this is actually just an example of your working code.


Listening for values changed by the memory

Having a private property is quite unusual. It's especially weird since you only use it once in TimerElapsed. I would probably just use the field directly and call RaisePropertyChanged() manually when necessary.
Why is the initial value passed in the constructor? I think the class should retrieve the initial value by itself.
PropertyChanged should be raised for a property that's readable from the outside and the name in the event args should be the same as the name of that property.
Your code is a prime candidate for making it more generic: you could change ValueChange to ValueChange<T> and int _val to T _val. (But if you do this, be careful with equality, !object.Equals(_val, newValue) is probably the simplest way to do it correctly.)

Also, Blah.GetMemoryValue should be configurable by the caller. You could achieve this by accepting a Func<T> delegate in the constructor. Something like:

private readonly Func<T> _getValue;

public ValueChange(double polingInterval, Func<T> getValue)
{
    _getValue = getValue;

     …
}

private void TimerElapsed(object sender, ElapsedEventArgs e)
{
    var newValue = _getValue();

    …
}

I like to avoid null checks on events by making sure there always is at least one subscriber:

public event PropertyChangedEventHandler PropertyChanged = delegate { };

But this is not really a common technique.
Creating multiple timers is okay, they execute on thread pool threads. This means that if several timers tick at the same time, they will be (most likely) executed concurrently by different threads.
In general, polling like this is not ideal. It would be better if you could get a notification whenever the value actually changes. But it seems like this is not possible in your case.
You shouldn't shorten the names of your variables. So, _value is better than just _val.


Retrieving list of flight numbers from flight path

If I understand this, you have a directed graph that consists of a series of flight segments. You are given a series of flight segments, say, A -> B -> C, that makes up a flight path.

In addition, you have a group of flight numbers. The flight numbers correspond to paths. Flight number 1 will be tagged as [A,B,1], for example. Time is not an issue, all flights are assumed to be available at all times.

Can you, in less than \$O(n^3)\$ time, figure out what flight numbers can take you from one segment to the next?

Well, on approach might be to go through the array exactly once in order to separate out all the flights that depart from your first departure gate, your second departure gate, and so forth. That's order n.

Then go through each of those lists (once) and remove all the flights that don't have the right destination gate. That's order n again.

At that point, you're pretty much done.

So think your big mistake here is going through your big loop (the flights) INSIDE your little loop (your flight path). You'd be much better off going through the small loop inside the big loop and breaking if you find a match. This loop only nests once, also, instead of twice. If you really really wanted to, you could check each departure as you find it to see if it matches an arrival.

In psuedo-code:

for (i in each flight) do
    for (j in each pathpoint except the last one) do
        if flight[i][departure][i] == pathpoint[j] then
            if flight[j][arrival] == pathpoint[j+1]
                put flight in the good flights vector
            end if
        end if
    end for
end for

That's \$O(n*m)\$, where \$m\$ is the length of the path and n is the number of flights. This should be, in any reasonable world, \$O(n)\$.


As mentioned in the comments, there's not much to review.

Don't abuse using namespace std

Putting using namespace std within your program is generally a bad habit that you'd do well to avoid.

Factor out common code

In this case, the code gets a lock, does something, and releases the lock.  That could easily be isolated to a common function:

class Locker
{
     pthread_mutex_t&   mutex;
     bool               ok;
   public:
     operator bool() const {return ok;}

     Locker(pthread_mutex_t& mutex)
         : mutex(mutex)
         , ok(true)
     {
         if(pthread_mutex_lock(&mutex) != 0) {
             cerr << "failed to lock output" << endl;
             ok = false;
         }
     }
     ~Locker()
     {
         if (ok) {
             if(pthread_mutex_unlock(&mutex) != 0) {
                 cerr << "failed to unlock output" << endl;
             }
         }
     }
};
void report(Vehicle *v, const char *msg)
{
    Locker    lock(okToOutput);
    if (lock) {
        cout << "Vehicle " << v->licencePlate << msg << dirToStr(v->direction) << endl;
    }
}

To do this correctly, a failure to lock should exit the routine and not attempt to send output data.

Avoid C-style casts

Instead of (Vehicle *)arg use static_cast<Vehicle *>(arg).  It makes much more clear to humans reading your code what you're doing.


Testing an action returns a View with a ViewModel using xUnit and Moq

Let's review each code segment one by one:

public class UserController : Controller
{
    private readonly ILogger<UserController> _logger;
    private readonly IViewModelService _vmService;

    public UserController(ILogger<UserController> logger, IViewModelService vmService)
    {
        _logger = logger;
        _vmService = vmService;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _vmService.GetIndexVM());
    }
}

I would generally recommend to avoid code like this:

return View(await _vmService.GetIndexVM());

It is hard to add proper error handling, add transformation logic, add conditional branching, etc. A better approach would be to separate these two operations:

var indexViewModel = await _vmService.GetIndexVM();
return View(indexViewModel);

public async Task<UserListVM> GetIndexVM()
{
    return new UserListVM()
    {
        UserList = await _userRepo.GetUserList()
    };
}

First of all the same applies here as above, do not mix object creation logic and async calls.

Secondly, in this simple code you have repeated four times the underlying collection type, which is an implementation detail. If you need to change that implementation detail in the lower layer that would propagate through several layers. Remember that hiding implementation details will help you minimize the scope of a change. A better approach would be:

public async Task<UsersVM> GetIndexVM()
{
    return new UsersVM()
    {
        User = await _userRepo.GetUsers()
    };
}

There is another thing, this service now has two responsibilities:
1) Retrieve data via a lower layer
2) Transform data to the presentation layer

In other words, this layer is an adapter between your presentation layer and repository layer. Generally speaking the service layer is the place where your business logic should reside. Because there is no business logic here, that's why it acts as an adapter.

I have seen the following two approaches regarding object mapping:

Each layer transforms its objects to the lower layer's object
model
Each layer accepts upper layer's object model and it
transforms it into its own model

The first one fits nicely into the n-layer architecture model where each layer only knows about that layer, which is directly beneath it. So, presentation layer knows about service layer. Service layer knows about repository layer.

The second approach violates this rule. Service layer knows about repository layer and knows about presentation layer's domain model. It is not bad, but the first approach (in my opinion) separates the concerns better.

public class UserListVM
{
    public IQueryable<DimUser> UserList { get; set; }
}

Here your naming and data type is not matching. With this name you are stating that it should contain a List, which implies that you could use such operators like Add, Remove, etc. IQueryable does not provide such API.

IQueryable is a type, which is used for deferred execution. In other words it indicates that this is just a query not the materialised form of the query. The problem with this is that it will execute the query when you somehow iterate through it (via foreach or calling .Count, etc.) If you do this in your view then your repository's datacontext might already be disposed.

A better approach would be to expose it like this:

public class UsersVM
{
    public IList<DimUser> Users{ get; set; }
}

Your test's Arrange part looks good, so I will spend some thought on the rest:

// Act
var result = await userController.Index();
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsType<UserListVM>(viewResult.ViewData.Model);

// Assert
Assert.IsType<UserListVM>(model);

Your Act section should consist only of the call of the Index function of the userController. The assertions should go the under the Assert section.

I would also consider to use IsAssignableForm<T> instead of IsType<T>, because the former supports inheritance as well.


Removing synchronization from an agent for a trading system

You may be able reduce the amount of synchronisation, but you cannot eliminate it entirely. CAS or Fetch-And-Add are lower level operations that are abstracted away by Java so you cannot use them directly.

Firstly, some observations: due to the mechanisms of how the lock is acquired, your synchronization of handle will cause a random caller to be selected when multiple are waiting. This could cause a situation where trades are handled out of order, which would be evidenced in the timestamps. If this isn't desired, you should use a queue to ensure trades are processed fairly (although what constitutes fair is a matter of debate).

You shouldn't use your CheckException as a convenient way to skip past a bunch of code. Have creditCheck(...) return a boolean and use proper flow control, otherwise your code appears to accept a trade even if the credit check fails.

Some of your preconditions to a trade may allow you to reject a trade before entering the synchronisation block. If the CounterParty doesn't match, you will always reject a trade. If  a trade is above the daily limit, you will reject the trade outright. If a trade is above the trading limit, you can run the credit check without synchronising and reject it if it fails. It also appears that you only ever increment utilisedDailyLimit so if any trade's value would exceed the daily limit (and assuming trade values cannot be negative) you may reject it with an unsynchronised check against the daily limit.

Once you've checked all these preconditions, you have to worry about concurrency. You will have to check the daily limit again, but if this is done on a single-threaded consumer thread, you do not have to synchronise at all because there is no concurrent access and you know the value cannot change. With this approach, may also wish to submit the eventListener.accepted(...) call to a thread pool to execute separately as this may also slow down execution calling the listener inline.

A BlockingQueue would be ideal for this kind of design.


I think you need a mix of lookup object(s) and regular if statements; there are clearly direct matches, matches on the prefix and the rest. Also, to write else if is pointless since you return anyway in previous if checks, so you can simply use

if(condition){
  return value
}
if(condition2){ // <- no else here
  return value2
}

All that together you could consider something like this:

var formatTitleDirectMapping = {
  'total' : 'title',
  'type' : label_documenttype,
  'dokumenttype' : label_documenttype,
  'km_type' : label_documenttype,
  'spesfikasjon' : label_theme,
}

var formatTitlePrefixMapping = {
  'tema_' : label_theme,
  'prosess_' : label_process,
  'dokumenttype' : label_documenttype,
  'km_type' : label_documenttype,
}

function formatTitle(input) {
  var lower = input.toLowerCase();
  //Is there a straight forward conversion? Then get out
  if( formatTitleDirectMapping[lower] )
    return formatTitleDirectMapping[lower];
  //Is there a straight forward conversion for the prefix? Then get out
  var prefix = lower.split("_")[0];
  if( formatTitlePrefixMapping[prefix] )
    return formatTitlePrefixMapping[prefix];
  //Put the conversions that dont lend themselves to lookup structures here
  if( prefix == "sm") {
    return input.substr(3);
  }
  //Catch all
  return input.charAt(0).toUpperCase() + input.slice(1)
}


As the comments have said, writing a login systems securely is really hard. I would strongly recommend using an existing framework like one of the ones KIKO Software has put in his comment. With that disclaimer out of the way, let's have a look at the code.

<?php
session_start();
if(isset($_SESSION["userid"]))
{
 header("location:index.php");
}

Any time you use a redirect, it should be immediately followed by an exit(). If you don't do this the rest of the code will still be executed, and if the user's browser ignores the Location header they can still view the rest of the page. Not so bad here, but can lead to nasty access control issues. HTTP headers are normally capitalised with a space after the colon like Location: /index.php but I don't think there any (common) browser that would complain about this.

if(isset($_POST["login"]))
{
 if(!empty($_POST["member_name"]) && !empty($_POST["member_password"]))

A user could submit an array here for the username or password, rather than a string, which you probably don't want, as some PHP functions do strange things with arrays. If you only want a string, you should check for it here.

 {
  $name = mysqli_real_escape_string($conn, $_POST["member_name"]);
  $password = mysqli_real_escape_string($conn, $_POST["member_password"]);

The mysql_real_escape_string() function has some issues with certain character sets, so you need to be careful with it. But since you're using prepared statements, you don't need to escape these, and in fact if you escape them and they have certain characters like single quotes, you'll end up with the wrong values.

$stmt_check = $conn->prepare("SELECT * FROM userz WHERE email =? AND pass = ? AND active ='1'");

Is active a string? I'd expect that to be an integer (or even boolean), but you have single quotes around the 1, so it's being treated as a string by MySQL.

Doing SELECT * is normally a bad sign - you should only select the columns you actually need (which doesn't look like any in this case, you could probably get away with a count).

As mentioned in the comments, storing plaintext passwords is a really bad idea. You should be using a secure hashing function like bcrypt/scrypt/PBKDF2 to store passwords.

$stmt_check->bind_param("ss", $name, $password);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrows = $stmt_check->num_rows;
if(($numberofrows) > 0){

Could the number of rows returned ever by more than 1? That would mean that you have duplicate users in your database, which would be a sign something has gone badly wrong. Unless there's something very strange in the database, it'd be better to check that exactly 1 row has been returned.

setcookie ("member_login",$name,time()+ (10 * 365 * 24 * 60 * 60));
setcookie ("member_password",$password,time()+ (10 * 365 * 24 * 60 * 60));

Storing the plaintext password (or any password) in a cookie is a very bad idea, especially when it's going to be stored for a ten years. Any cookies you're creating should also be marked as HttpOnly, Secure (assuming you're using SSL, which you really should be), and optionally SameSite.

$_SESSION["userid"] = $name;

It's good to be consistent internally with your variable names. So far the same information has been called member_name, name, email and userid

header("location:index.php");

See comments on previous header() usage.

} else {
  $message = "Invalid Login OR Email not Verified";
}

$stmt_check->close();

This could have been closed earlier, immediately after you get the number of rows.

As KIKO Software mentioned in his first comment, there are also some other security features that are lacking:

Account lockout
CAPTCHA or other brute-force protection
Session hijacking

Writing authentication code is really, really difficult, and if you solve all of these issues, there are still all kinds of other complexities like timing attacks, user enumeration, etc. You're much better off letting someone else deal with that pain.


Managing rendering targets in XNA using IDisposable

An approach itself is fine IMO, but the API is misleading. Why would SetXXX method ever return something, let alone return an IDisposable? Maybe come up with a better name.


Here are some comments related to your code:

Strange place to initialise the Random() – This should either be in within the generateColor() function, or some static initialisation. As it stands now, it looks strange that you need to include the random generator to as a parameter to your function. You are better of using a static initialization
Strange magic number, 16777215 – What is this number? It is not very clear that this is actually the 0xFFFFFF denoting the maximum color number. Also note that nextInt(n) returns a number in the range 0 up to n, but not including n. In other words, you should use 0x1000000
Tricking into being 6 characters – If you add 0x1000000 to the number before converting to hexadecimal you are ensured six digits, and don't need the trick for 6 characters, and can return a substring (instead of using a while loop)

Applying this and your code looks something like this:

package generacolorrgb;

import java.util.Random;

public class GeneracolorRGB {

    static Random randomGenerator;

    static {
        randomGenerator = new Random();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(generateColor());
        }
    }

    private static String generateColor() {
        int newColor = 0x1000000 + randomGenerator.nextInt(0x1000000);
        return "#" + Integer.toHexString(newColor).substring(1, 7);
    }
}

Added: An even nicer variant would be:

    private static String generateColor() {
        int newColor = randomGenerator.nextInt(0x1000000);
        return String.format("#%06X", newColor);
    }

Here we let the Formatter handle the formatting issue, and it does indeed look nicer! And we don't need to make sure the random number is above the legal range, as the formatter handles it.


In an interview it usually doesn't matter if you actually solve the problem. What is most important is the way you (try to) solve it. If they don't tell you it should be the possibly fastest solution ever you should not optimize it prematurely but instead show that you know how to write SOLID code like encapsulate propertly, make the code testable etc. show that you know the techniques.

Here you could split the logic up into multiple methods for example you could have one generating the alternating sequence [1, -3, 5, -7, 9, -11, ...] that you can validate with a test:

public static IEnumerable<int> AlternatingSequence()
{
    var i = 1;
    yield return i;
    var b = false;
    while (true) yield return ((b = !b) ? -1 : 1) * (i = i + 2);
}

then you can work on the PI itself and use it for the actual calculation which is then as simple as a LINQ expression:

public static double EstimatePI(int sumLength)
{
    return (4 * AlternatingSequence().Take(sumLength).Sum(x => 1.0 / x));
}

var pi = EstimatePI(500_000).Dump(); // 3,14159065358969

There's all kind of stuff you can show you are familiar with in this simple task like DI or strategy pattern:

public static double EstimatePI(int sumLength, IEnumerable<int> sequenceGenerator)
{
    return (4 * sequenceGenerator.Take(sumLength).Sum(x => 1.0 / x));
}

var pi = EstimatePI(500_000, AlternatingSequence);

or even more advanced DI and encapsulation

class PiCalculator
{
    private readonly IEnumerable<int> _sequenceGenerator;

    public PiCalculator(IEnumerable<int> sequenceGenerator)
    {
        _sequenceGenerator = sequenceGenerator;
    }

    public double EstimatePi(int sumLength)
    {
        ...
    }
}

or you can add an interface to show you know what abstraction means:

interface IPiCalculator
{
    double EstimatePi(int sumLength);
}

Is this an overkill? It might be but it shows me that you are able to write modular and testable code. Writing short code is a good thing too but if you write only five lines inside a Main in a job interview, you'll go home without any prospects of getting the job. Again, in an inteview you should sell your coding skills and not show how smart you are in solving something with a fewest possible lines of code that no one can verify.


How to set state of multiple properties in one event handler (React)

I find it fine as it is, but if you really want to keep a single method, you can parametrize it by the name of the key to set:

handleChange = (keyName, e) => { this.setState({ [keyName]: e.target.value }); }

and call it like handleChange('content', event) or handleChange('author', event).

Problem is, now, to call it properly when creating your components. You could write things like:

<input onChange={(e) => this.handleChange('content', e)} value={this.state.content} type="text" placeholder="comment" />

But this syntax creates a new function each time the component is rendered, potentially triggering child re-render as well. React recommends to bind functions in the constructor instead:

import React, { Component } from 'react';

class AddComment extends Component {
    constructor(props) {
        super(props);
        this.state = { author: '', content: '' };
        this.handleAuthorChange = this.handleChange.bind(this, 'author');
        this.handleContentChange = this.handleChange.bind(this, 'content');
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(keyName, e) {
        this.setState({ [keyName]: e.target.value });
    }

    handleSubmit(e) {
        e.preventDefault();
        this.props.addComment(this.state);
        this.setState({ author: '', content: '' });
    }

    render() {
        return (

                <form onSubmit={this.handleSubmit} className="card hoverable p-bottom">

ADD COMMENT

                    <input onChange={this.handleContentChange} value={this.state.content} type="text" placeholder="comment" />
                    <input id="name" onChange={this.handleAuthorChange} value={this.state.author} type="text" placeholder="name" />
                    <input value="submit" type="submit"/>
                </form>

        );
    }
};

export default AddComment;


I'm pretty new at Clojure myself, and haven't studied the collection algorithms very much yet, so this may not address your performance concerns, but I did find a few things that could be improved.

Potential problem with "real" document input
As I started going through your functions and how they work together, I noticed that your logic makes the assumption that all input will always just be words separated by spaces. Perhaps your data set is already preprocessed before it enters your termdocmatrix function? Unless that is the case, any text from actual documents written by humans will have many artifacts like punctuation marks and such that you should probably account for.
I ran these to illustrate what happens with more "natural" document text:

(def docs-punc ["this is, a cat" "this is a dog." "woof: and a meow" "woof; woof woof! meow? meow words"])
(whitesplit docs-punc)
; => ([this is, a cat] [this is a dog.] [woof: and a meow] [woof; woof woof! meow? meow words])
(termdocmatrix docs-punc)
; => [[:cat :dog. :is :this :woof: :is, :words :meow? :woof! :and :meow :woof; :woof :a] [1 0 0 1 0 1 0 0 0 0 0 0 0 1] [0 1 1 1 0 0 0 0 0 0 0 0 0 1] [0 0 0 0 1 0 0 0 0 1 1 0 0 1] [0 0 0 0 0 0 1 1 1 0 1 1 1 0]]

That totally messed up the results as you can see. I added a strip-punc function at the top (I made punc-to-remove its own form for readability, personal preference), and a helper function to apply it to a vector of strings:
(defn strip-punc
  "remove punctuation marks in string using `punc-to-remove` capture pattern and replacing them with empty string"
  [str]
  (def punc-to-remove #"[.,;:!?$%&\*()]")
  (str/replace str punc-to-remove ""))

(defn vec-strip-punc
  "applies strip-punc to a vector of strings"
  [vec]
  (map #(strip-punc %) vec))

Then change your bigmap function accordingly to call it before you split the strings:
  (let [docs-no-punc (vec-strip-punc docs)
        stringvecs (whitesplit docs-no-punc)] ; etc.

Or alternatively inline style:
(let [stringvecs (whitesplit (vec-strip-punc docs))]

This will take care of pretty much all your general punctuation cases, and you can easily tweak the regex pattern as needed:

(def docs-punc ["this is, a cat%" "this $is a dog." "woof: and [a] meow*" "woof; (woof woof!) meow? meow words"])
(termdocmatrix docs-punc)
; => [[:cat :is :this :words :dog :and :meow :woof :a] [1 1 1 0 0 0 0 0 1] [0 1 1 0 1 0 0 0 1] [0 0 0 0 0 1 1 1 1] [0 0 0 1 0 0 2 3 0]]

Naming
Your names don't follow typical Lisp naming convention. According to Wikipedia on naming conventions (programming):

Common practice in most Lisp dialects is to use dashes to separate words in identifiers, as in with-open-file and make-hash-table. Global variable names conventionally start and end with asterisks: *map-walls*. Constants names are marked by plus signs: +map-size+.

Also since most/all your functions actually transform your data structure, I would suggest naming them in a way that suggests that. Perhaps also using an acronym consistently, let's say td (or even TD) for term-document, that would make it read better without being really verbose.
termdocmatrix -> TD-matrix-from-docs
terdocmmap -> TD-map-from-docs
tdseqs -> TD-seqs-from-TD-map

bigmap I don't think is a descriptive name. What is "big" in this context? In truth it reminds me of a Cartesian product, since each document entry in the docs vector will return its own map of all possible words, e.g., {this 1, is 1, a 1, cat 1, dog 0, woof 0, and 0, meow 0, words 0}. I would be tempted to call it something like cartesian-product-map or perhaps just cartesian-map.
I would also suggest to perhaps change whitesplit to space-split, since that is really what it is doing (it is not splitting other whitespace like \r \n \t. Or if you want to make it a true whitespace-split, then you should change #" " to the #"\s" special character which includes "all whitespace". Here is an article on RegexOne about it.


Avoiding dynamic RegEx creation in JavaScript

You can store the regex as part of the smily metadata.

var replaceTextSmilies = function() {
    var smiliesShortcut = {};
    smiliesShortcut[':)'] = {
        img : 'smile.png'
    };
    /* adding much more */

    var smiliesWordy = {};
    smiliesWordy[':angry'] = {
        img : 'angry.png'
    };
    /* adding much more */

    addRegex(smiliesShortcut);
    addRegex(smiliesWordy);

    function escapeRegExp(str) {
        return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }

    function addRegex(smilies) {
        Object.keys(smilies).forEach(function(smily) {
            smilies[smily].regex = new RegExp('(' + escapeRegExp(smily) + ')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');
        });
    }

    function replace(text, smilies) {
        Object.keys(smilies).forEach(function(entry) {
            var image = '<img src="img/smilies/' + smilies[entry].img + '"/>';

            if (text.indexOf(entry) !== -1) {
                text = text.replace(smilies[entry].regex, image);
            }
        });
        return text;
    }

    return function(text) {
        text = replace(text, smiliesWordy);
        text = replace(text, smiliesShortcut);
        return text;
    };
}();

Demo: Fiddle

Note: You can make it even better if you can manually create the regex and assign them instead of using addRegex() like

    smiliesShortcut[':)'] = {
        img : 'smile.png',
        regex: /<the regex>/
    };


Reduce a string using grammar-like rules

n is unused.

You write to it here:

        n = Integer.parseInt(textStr[0]);

But you don't do anything with it.


Building complex sentences based on a data structure

Remove the last item

You are not going to avoid the stepping over each item at least once. However the replace and be avoided by removing the last item.

One iteration

Use a for loop,  building the string as you step over each item. Before the loop pop the last item, then after the loop push it back to keep the array intact.  You can then add the last item after the conjunction.

I will use options rather than alternatives as in the bottom example it is more semantically fitting.

function toHumanReadable(options) {
    const toStr = opt => `"${Array.isArray(opt) ? `${opt[0]}" with "${opt[1]}` : opt}"`;
    const last = options.pop();
    var res = 'Consider using ';
    for (const opt of options) { res += toStr(opt) + ', ' }
    options.push(last);
    return res + `or ${toStr(last)} instead.`;
}
const alt1 = [ "flex", "float" , ["background-size", "background-image" ] ];
const readable = toHumanReadable(alt1);

or you can make options an argument array, and don't need to push the last item back onto the array. It does mean an extra iteration.

function toHumanReadable(...options) {
    const toStr = opt => `"${Array.isArray(opt) ? `${opt[0]}" with "${opt[1]}` : opt}"`;
    const last = options.pop();
    var res = 'Consider using ';
    for (const opt of options) { res += toStr(opt) + ', ' }
    return res + `or ${toStr(last)} instead.`;
}

const alt1 = [ "flex", "float" , ["background-size", "background-image" ] ];
const readable = toHumanReadable(...alt1);

Reusable

I am guessing this is just one of a many similar human readable strings. To make the function reusable you can add some arguments

The next version requires two iterations, but does not need the replace. This time the last item is popped from a copy of the options array and the conjunction is added via joining the joined options and the last option.

function toHumanReadable(options, open, close, conjunction) {
    options = options.map(opt => Array.isArray(opt) ? opt.join('" with "') : opt);
    const last = options.pop();
    return `${open} "${[options.join('", "'), last].join(`", ${conjunction} "`)}" ${close}`;
}

const alt1 = [ "flex", "float" , ["background-size", "background-image" ] ];
const readable = toHumanReadable(alt1, "Consider using", "instead.", "or");

Example usage

setTimeout(()=> { // just for snippet to put relevant code at top

  const alt1 = [ "flex", "float" , ["background-size", "background-image" ] ];
  const alt2 = [ "foo", ["bar","poo"], ["min-width", "max-height" ] ];
  log(toHumanReadable(alt1, sentenceTypes.anyOf));
  log(toHumanReadable(alt2, sentenceTypes.oneOf));
  log(toHumanReadable(alt1, sentenceTypes.allOf));
},0);

function toHumanReadable(options, {open, close, conjunction}) {
    options = options.map(opt => Array.isArray(opt) ? opt.join('" with "') : opt);
    const last = options.pop();
    return `${open} "${[options.join('", "'), last].join(`", ${conjunction} "`)}" ${close}`;
}

const sentenceTypes = {
   create(name, open, close, conjunction) { this[name] = {open, close, conjunction} }
};
sentenceTypes.create("anyOf", "Consider using", "instead.", "or");
sentenceTypes.create("oneOf", "Use any one of", "to stay consistent.", "or");
sentenceTypes.create("allOf", "All the following", "are required.", "and");
function log(t){txt.appendChild(Object.assign(document.createElement("div"),{textContent:t}))}
body {
font-family: arial;
font-size: small;
}


If you wanted to retain any event handlers that were already attached to your elements, you could change the first piece of code like this an avoid one of the dangers of setting innerHTML on an element that already has a bunch of HTML in it:

// add iframes to page
var normal_sortables = document.getElementById('normal-sortables');
// create container div
var newDiv = document.createElement("div");
newDiv.className = "postbox";
// put content into container div
newDiv.innerHTML = '';
// add container div to the sortables
normal_sortables.appendChild(newDiv);


Program that generates random IQ numbers and multiplies them by a user-entered multiplier

You don't need comments explaining the standard library headers - credit your readers with enough knowledge to know what those lines are for.

Most of the other comments could be removed (in some cases, we can use better names for variables such as y, a and m to communicate the meaning instead).

There's nothing to stop overrun of the name variable - prefer to use std::string instead, as it will automatically resize as required.

Avoid using namespace std - importing all names of a namespace is a bad habit to get into, and can cause surprise when names like begin and size are in the global namespace.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

IC doesn't need to be a global variable - it can be a local to main().

IQ scores are usually defined as a Normal distribution of mean 100 and standard deviation 15.  You can use a std::normal_distribution (from <random>) to generate values that fit.


Measuring the clock rate of an Intel CPU in C++

There are a number of things that you might employ to improve your program.

Accuracy

  Is there any reason the strategy used and described below won't produce accurate results?

Yes!  There are many reasons, which are each enumerated separately in items below, followed by more general information about code style and structure.

Understand System Management Mode

The code currently does not account for the possibilty of the processor entering System Management Mode (SMM).  One simple way of putting the machine into SMM is to have it go into standby.  My laptop is configured to go into standby when I close the lid and come back out when I open it again, so when I did that when running this program, I got this result:

  CPU MHz: 2365092677585.790

While it would be lovely to actually have a processor that fast, my laptop does not, so this result is incorrect.

Understand sleep_for

What std::this_thread::sleep_for(delay) does is to sleep for at least delay but it may be longer, depending on what else the operating system and the underlying hardware are doing at the moment.  This means that there is a variability in the results of the program.  An example of one thousand runs of the program is shown plotted below.

While in this case, most of the results were around the correct value of 2494.225 MHz, the results vary.  The alternate way to do this would be to use a hardware-based timer instead and run the timing code as part of the kernel with interrupts disabled.

Understand out-of-order execution and cache effects

The variability of this program as it currently stands is such that it doesn't matter, but when attempting to do precise timing using the RDTSC instruction, it's important to understand that the processor does out-of-order execution.  This means that instructions preceding or following the RDTSC instruction may actually be part of the duration of the event you're trying to measure unless precautions are taken.  What is generally used is a serializing instruction such as CPUID to eliminate such effects.  Intel has a useful whitepaper that describes this in detail and how to apply it.

General advice

What follows is more general advice about the coding style and structure.

Avoid global variables

The program_name and start_time variables are global variables.  It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable.  If they must be globals (which is not the case here), then make them static.

Be careful with size assumptions

The code currently has these three lines:

unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;

It's not wrong as it is, but I'd probably write that using explicit uint32_t sizes for hi and lo to eliminate the possibility of a compiler with a 16-bit unsigned int.

Isolate code to a function

Right now, the timing is done in main.  I'd probably rewrite that to contain the timing code in a function:

double approx_CPU_MHz(unsigned sleeptime) {
    using namespace std::chrono_literals;
    uint64_t cycles_start = get_cycles();
    double time_start = age();
    std::this_thread::sleep_for(sleeptime * 1ms);
    uint64_t elapsed_cycles = get_cycles() - cycles_start;
    double elapsed_time = age() - time_start;
    return elapsed_cycles / elapsed_time / 1000000.0;
}

Think of the user

The PrintUsage routine looks like this:

void PrintUsage()
{
    printf("Usage:\n");
    printf("%s [measurment duration]\n", program_name);
}

There are three problems with that from the user's point of view.  First, it doesn't tell the user the unit of measure for the measurement duration.  Is it seconds?  Minutes?  Microseconds?  The user would have to look at the source code to answer that question.  Second, it could reasonably be interpreted to be two arguments, both of which are optional.  Putting an underscore instead of a space would fix that.  Third, the word "measurement" is misspelled.

Use iostream

It's not wrong to use printf but using iostreams is both more C++-like and can actually save some runtime processing.  To evaluate printf, the computer has to interpret the format string first, while using << means that the compiler has already evaluated the argument type at compile-time.


You do not use file_list
Emptiness of container (as in PEP8) is usually checked by if not container.
For path operations os.path is preferred. Let's change 'final' to os.path.dirname and building path to os.path.join. Avoid os-specific solutions.
Let's reduce indentation by using continue statement.
IMHO using comprehensions is not preferable here. Pythonic means 'obvious' and 'simple' way, and this is very simple way.
I introduced explanatory variable and tweaked naming a little bit.
Consider separating building file list with writing it to file. Separating responsibilities is usually great idea. If you do that maybe you'll be able to find good place to use comprehensions.

Improved code (without separating) below:

import os
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders:
            continue
        for fil in files:
            if not fil.endswith('img'):
                continue
            dir_name = os.path.basename(fil)
            full_path = os.path.join(root, fil)
            fp.write("{0} {1}\n".format(full_path, dir_name))


Get ProductCode from MSI File using DTF in C#

Almost all objects you work with here are disposable so wrapping them with the using would be a good start.
The msiDB variable is not necessary.
It is not necessary now to define the result above the query. Variables should be defined as close to their usage as possible.
We use the _ usually only for private fields not for local variables.
You might consider the implicit type var. It would make your code less verbose.

After applaying this we get:

public static string GetMSIProductCode(string msiFile)
{
    var productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
    using(var product = Installer.OpenPackage(msiFile, true))
    using(var msiView = product.Database.OpenView(productCodeQuery))
    {
        msiView.Execute();
        using (var record = msiView.Fetch())
        {
            return record.GetString(2);
        }
    }
}


Writing a class for common block of code used in many other classes

Is it good programming standard to write separate classes for common blocks of code used in many other classes?

Yes, it is. Not repeating code over and over again is an important principle of programming.

The alternative to creating a separate class would be to create a Base activity which contains this method (in cases that you feel a separate class would be overkill). You could even call this method in the onCreate method of the Base activity, thus automatically using it each time.

In this case it's really a matter of taste. I would probably put it in a method in the Base activity, because your current GoogleAnalyticsCode class doesn't really contain any logic. It just calls EasyTracker:send().

Coding Style

Just a quick side-point concerning your coding style: You should try to be consistent with the position of your opening curly bracket, your indentation, and your spacing.


Create a random string with a set prefix

When you do rand()%n you will get a random number in the range [0, n-1] but the distribution will not be uniform. Some values will be more likely than others. This is more easily illustrated if we drop the number of random bits from 32 to 4, i.e. RAND_MAX=15. And we want a number between 0 and 10 so we do rand()%11. Now for returns values of 0-10 from rand() well get the wanted values, but what about the rest of the range? Well from 11 to RAND_MAX well also get 0-4... This means that values 0-4 are twice as likely to occur as values 5-10, this isn't what we wanted!
I explain this in another answer here: https://codereview.stackexchange.com/a/159760/36120


Python webscrape Amazon Music, generate tracklist

Whenever you find yourself writing long (or sometimes even short) comments explaining a single line/a block of lines, you should ask yourself if this was not better placed in a function. Functions can be given a meaningful name and you can add a docstring to them (which can be considerably longer than a comment practically can). It also give you one obvious place to change if, for example, the Amazon Music website is changed at some point.

IMO, here the function names should already be self-explanatory enough, so I did not add any docstrings.

import requests
from bs4 import BeautifulSoup
from itertools import count

def get_soup(url):
    r = requests.get(url)
    r.raise_for_status()
    return BeautifulSoup(r.text, 'lxml')

def track_titles(soup):
    attrs = {'class': 'a-link-normal a-color-base TitleLink a-text-bold'}
    return [a.text for a in soup.find_all('a', attrs=attrs)[::2]]

def track_durations(soup):
    attrs = {'class': 'a-text-right a-align-center'}
    return [td.text.strip() for td in soup.find_all('td', attrs=attrs)]

def track_artist(soup):
    return soup.find('a', attrs={'id':'ProductInfoArtistLink'}).text

if __name__ == "__main__":
    url = input("Please enter an Amazon music url:")
    soup = get_soup(url)

    titles = track_titles(soup)
    durations = track_durations(soup)
    artist = track_artist(soup)

    for i, title, duration in zip(count(1), titles, durations):
        print(f"{i}. {title} - {artist} ({duration})")

Other things I changed:

Added a if __name__ == "__main__": guard to ensure you can import this module from another script.
Used the fact that input already returns a string (in Python 3).
Added r.raise_for_status() so that the code raises an exception if the request does not succeed.
Consistently followed Python's official style-guide, PEP8.
Used the usually faster lxml parser.
Iterate over the elements instead of the indices.
Used the recently introduced f-string to make the formatting easier.
Used str.strip instead of hardcoding indices for the duration.
Made the functions do all the cleanup.


This is little neater IMO.

// User can be part of many groups
const user = {
  groups: ["group2"]
};

// Roles can have many groups
// What you see here is the output or 2 different data source
// Thats why we have group duplication inside different role
const roles = [{
  name: "role1",
  groups: [{
    id: "group1"
  }]
}, {
  name: "role2",
  groups: [{
    id: "group1"
  }, {
    id: "group2"
  }]
}];

const result = roles.filter(role => role.groups.find(group => user.groups.includes(group.id)));
console.log(result);


WPF - Run an async Task with DispatcherTimer

Async void should be avoided, but they are acceptable when in an EventHandler so it's fine.

Why are you copying the keys of the dictionary into a list? Do you want a snapshot at a random point in time?

If you have potentially race conditions, I would change the Dictionary to a ConcurrentDictionary.

public partial class MainWindow : Window
{

    // Dictionary to hold info
    private readonly Dictionary<string, string> _dataHolder = new Dictionary<string, string>
    {
        {"status_code", "" },
        {"memory", "" },
        {"process", "" }
    };

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void StartBtn_Click(object sender, RoutedEventArgs e)
    {
        StartBtn.IsEnabled = false;

        while (true) // Your exit condition instead of the true.
        {
            await LoadInfo();

            foreach (var entry in _dataHolder)
            {
                // Display in the UI
            }

            await Task.Delay(TimeSpan.FromMinutes(5));

            //StartBtn.IsEnabled = true;
        }
    }

    private async Task LoadInfo()
    {
        const int page = 1;

        var keys = new List<string>(_dataHolder.Keys);

        foreach (var key in keys)
        {
            _dataHolder[key] = "";
            //await asyncCall(key, page);
        }

        // Better asynchronously and in parallel
        await Task.WhenAll(keys.Select(key => AsyncCall(key, page)));
    }

    private static async Task AsyncCall(string key, int page)
    {
        var htClient = new HttpClient();
        // code to retrieve data...
    }


Custom MySQLi statement function for binding variables

An obligatory suggestion: you can greatly improve any mysqli code by switching to PDO. So your function would be three times shorter

function db ($query, $parameters = false)
{
    global $db;
    if(!isset($db))
    {
        $options = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => FALSE,
        );
        $dsn = 'mysql:host=localhost;dbname=db;charset=utf8';
        $db = new PDO($dsn, "username", "password", $options);
    }

    if (!$parameters)
    {
        return $db->query($query);
    } else {
        $stmt = $db->prepare($query);
        $stmt->execute($parameters);
        return $stmt;
    }
}

note that PDO has much better equivalent of your db_fetch() function, letting you to get the data simpler and in more formats than your awkward $results / $fetch combination:

$row = db("SELECT * FROM t WHERE id=?", [$id])->fetch();
$count = db("SELECT count(*) FROM t")->fetchColumn();
$data = db("SELECT name, id FROM t")->fetchAll(PDO::FETCH_KEY_PAIR);

compare these explicit calls where you always can tell what does your code return with your

 $data = db("SELECT name, id FROM t", true, true);

show this code to someone and ask what's in $data. Or look at this code after a couple of months and try to tell it yourself without confusing all these true ans false parameters.


as it probably hits a database, i would call userExists from outside the validate function.
So, registration method first checks the input. Then calls userService.Register(User user, Errors errors). Register detects that username already exists and throws. And validation does not need to know about usernames and that they are unique or non-unique.


Lower the volume of my computer over time in Python

"I feel like there should be a cleaner way to deal with default values of optional arguments"

Yes, there is. Per the documentation of ArgParse, you can specify a keyword argument default and give it the value you want.

parser.add_argument("-d", "--delay", help="Delay in minutes until starting mute", type=int, default=0)

Documentation here
Tutorial here


About naming:

intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.

A first simple optimization is that you can avoid the check if intK has reached the end:

  a.Length - 1 == intK ?

Instead you can just iterate up to a.Length - 1 and then append temp at the end:

public static int[] rotLeft(int[] a, int d)
{
  for (int intI = 0; intI < d; intI++)
  {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
      a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
    }

    a[a.Length - 1] = temp;
  }

  return a;
}

Next step is to consider the math:

a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK

and in the same way:

a.Length - (a.Length - (intK + 1)) = intK + 1

So you could write:

public static int[] rotLeft(int[] a, int d)
{
  for (int intI = 0; intI < d; intI++)
  {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
      a[intK] = a[intK + 1];
    }

    a[a.Length - 1] = temp;
  }

  return a;
}

But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:

public static int[] rotLeft(int[] a, int d)
{
  int[] temp = new int[d];

  for (int i = 0; i < d; i++)
    temp[i] = a[i];

  for (int i = d; i < a.Length; i++)
  {
    a[i - d] = a[i];
  }

  for (int i = 0; i < d; i++)
    a[a.Length - d + i] = temp[i];

  return a;
}

Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":

public static int[] rotLeft(int[] a, int d)
{
  int[] result = new int[a.Length];

  for (int i = d; i < a.Length; i++)
  {
    result[i - d] = a[i];
  }

  for (int j = 0; j < d; j++)
  {
    result[a.Length - d + j] = a[j];
  }

  return result;
}

If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.


Python uses a surprisingly large amount of memory when reading files, often 3-4 times the actual file size. You never close each file after you open it, so all of that memory is still in use later in the program.

Try changing the flow of your program to

Open a file
Compute a histogram for that file
Close the file
Merge it with a "global" histogram
Repeat until there are no files left.

Something like

u = []
for f in filenames:
    with open(f) as file:
        # process individual file contents
        contents = file.read()
        data = json.loads(contents)
        for obj in data:
            s = obj['key_1']
            t1 = 60 * int(s[11:13]) + int(s[14:16])
            u.append(t1)

# make the global histogram
plt.hist(u, bins = (max(u) - min(u)))
plt.show()

with open as automatically closes files when you're done, and handles cases where the file can't be read or there are other errors.


I removed your comments and inserted mine.

# Documentation goes to POD.

=item comparer

Compare a sequence with the reference frequency of hexamers.

First argument the file of to analyse, second argument the file of reference

=cut

sub comparer {
    my ($seq, $ref_seq) = @_; # I like arguments being processed as the first step in the sub. No need to shift twice.

    my %score;
    my %freq_ref = hexamer_freq({ read_fasta($$ref_seq) });
    my %seqs = read_fasta($seq);

    while (my ($id,  $sequen) = each %seqs) {
        my @id_seq = split ' ', $id;
        my @id_name = split /\./, $id_seq[0];
        my ($max, $min);
        for my $i (0 .. 2) {  # No need for a C-style for.
            last if length $sequen <= $i;

            my $sequ = substr $sequen, $i;
            next unless defined $sequ;

            my $rev_sequ = reverse $sequ;
            my @seqs = ($sequ, $rev_sequ);

            for my $j (0 .. $#seqs) {  # C-style eliminated again.
                my %freq_seq = hexamer_freq({ $id_name[0] => $seqs[$j] }); # Anonymous hash.

                if (keys %freq_seq == 0) {
                    print STDERR log_time(), "Unable to calculate the Hexamer score of $id_name[0]\n";
                    next
                }

                my $score = 0;
                my $n_hexamers = keys %freq_seq; # "scalar" not needed in scalar context.
                for my $hex (keys %freq_seq){
                    if (defined $freq_ref{$hex}){
                        $score += log2($freq_seq{$hex} / $freq_ref{$hex});
                    }
                }

                if (! defined $max || $score / $n_hexamers > $max) {
                    $max = $score / $n_hexamers;
                }
                if (!defined $min || $score / $n_hexamers <= $min) {
                    $min = $score / $n_hexamers
                }

                my $key = $id_name[0] . " frame: $i";
                $key .= (' FWD', ' REV')[$j] if $j < 2;  # Poor man's "switch".
                $score{$key} = [$max, $min];
            }
        }
    }
    return %score
}

There's no need to call subroutines with the & prepended.
Semicolons after blocks are not needed.
To avoid guessing the minimum, just use undef and check for that in the condition. You could also try 'INF', but it's not portable.
Why is the subroutine's second parameter a scalar reference? Is it a very long string?


Producing all possible combinations of a list

It is possible that I'm misunderstanding the problem, but based on your description, I would expect the type of createGroups to be [a] -> [(a, a)] (A flat list, not a list of lists.)

I believe there is bug in your code. Take a look:

> createGroups [1..3]
[[(1,2),(1,3)],[(2,2),(2,3)],[(3,2),(3,3)]]

This result is not what I would expect based on your problem description. Given a list of [1, 2, 3], I would expect the output to be [(1,2),(1,3),(2,3)].

One way to achieve this output is the following:

createGroups :: [a] -> [(a, a)]
createGroups [] = []
createGroups (x:xs) = map ((,) x) xs ++ createGroups xs

> createGroups [1..3]
[(1,2),(1,3),(2,3)

Here is another function that outputs a "flat list" containing the same pairs as your original function, however it's been rewritten to use list comprehension:

createGroups :: [a] -> [(a, a)]
createGroups ls @ (_ : xs) = [(x, pair) | x <- ls, pair <- xs]

> createGroups [1..3]
[(1,2),(1,3),(2,2),(2,3),(3,2),(3,3)]

Lastly, here is a function that produces output identical to yours, rewritten using the monad instance of list:

createGroups :: [a] -> [[(a, a)]]
createGroups li@(x : xs) = do
  first <- li
  return (getPairs first xs)
  where
    getPairs item pairings = do
      pair <- pairings
      return (item, pair)

> createGroups [1..3]
[[(1,2),(1,3)],[(2,2),(2,3)],[(3,2),(3,3)]]

Hopefully this gives you some ideas of different ways to write your function.


Creating a dictionary with a path name and SHA-256 hash

In your code, you show two ways to create your dictionary, but both are somewhat flawed:

diction will be a list of dictionaries, each holding just one entry
dic2 will get overwritten in each iteration of the loop, and will finally hold only one dictionary, again with only one element.

Instead, try this:

diction = dict([ (fname, hashlib.sha256(open(fname, 'rb').read()).digest())
                 for fname in fnamelst ])

Or shorter, for Python 2.7 or later:

diction = { fname: hashlib.sha256(open(fname, 'rb').read()).digest()
                 for fname in fnamelst }

The first one uses a list comprehension to create a list of key-value tuples, and then uses the dict function to create a single dictionary from that list. The second one does the same, using a dict comprehension.


Using "split" is an option as other people have mentioned.  However, using a regex has the added benefit of validating the input data while parsing, so is still worth considering depending on your use-case.

A regex is better used in loop here since we're matching the same pattern repeatedly.  And you should use non-capturing parentheses for the bits you're not interested in capturing. E.g. changing nothing else your code would look like this:

$naNumberGroup = qr/(N\/A|(?:([0-9]{1,3}(?:,[0-9]{3})*) \(([0-9]{1,2}\.[0-9])\%\)))/;
my @outFields;
while ($line =~ m/\s\s+$naNumberGroup/g) {
    if("N/A" eq $1) {
        push @outFields, 'NA', 'NA';
    } else {
        push @outFields, $2, $3;
    }
}
print join(',', @outfields),"\n";

It's worth noting that your code as-is would preserve any commas in the input, therefore breaking your output.  And "100.0%" isn't handled.

If you're wanting to improve readability and maintainability of your regexes, here are some additional things worth changing:

Use the /x modifier to improve readability/maintainability.
Use more intermediate variables to build your regexes.
Avoid having to escape slashes by using qr{...} instead of qr/.../

E.g.

my $numberGroup = qr{
    (?<number> [0-9,]+ )                # Number with optional commas
    [ ]                                 # Single space
    \( (?<percent> [0-9]+\.[0-9] ) %\) # Percentage in parens
}x;
my $naNumberGroup = qr{
    [ ]{2,}                             # Two or more spaces
    (?: $numberGroup | N/A )            # No need to capture "N/A"
}x;
my @outFields;
while ($line =~ m/$naNumberGroup/xg) {
    my $number  = $+{number}  // 'NA';
    my $percent = $+{percent} // 'NA';
    $number =~ tr/,//d;             # Strip commas
    push @outFields, $number, $percent;
}
if (scalar @outFields == 8) {
    print join(',', @outFields),"\n";
} else {
    # Description line, or invalid line.  You may be able to use
    # another regex to determine which.
}


Print Bitcoin price by getting JSON data using CoinDesk API

In general you should be more especific on the management of the exceptions, my only contribution will be to be more specific on them on the requests component. For example your code on:

def get_api_data(url):
    try:
        response = rq.get(url)
        response.raise_for_status()
        ...
    except Exception as e:
        logger.debug("Exception occurred.", exc_info=True)

With more specific exception management

def get_api_data(url):
    try:
        response = rq.get(url)
        response.raise_for_status()
        ...
    except requests.exceptions.RequestException as _:
        logger.debug("Exception occurred on request.", exc_info=True)
    except json.decoder.JSONDecodeError as _:
        logger.debug("Exception occurred on json decoder.", exc_info=True)


Solve 6 simultaneous equations for 8 variables puzzle with Java

If willing to mix the solution checking logic into the candidate generation logic, we can do better if we drop the requirement that we brute force the entire answer.

private static void findAndPrintSolutions(int from, int to) {
    for (int a = from; a < to; a++) {
        // if a + b - 9 == 4, then
        int b = 13 - a;
        if (from > b || b > to) {
            continue;
        }

        for (int c = from; c < to; c++) {
            // if (a + c) / f == 4
            int f = (a + c) / 4;
            if (from > f || f > to) {
                continue;
            }

            for (int d = from; d < to; d++) {
                if (c == d || b == d) {
                    // these cause divide by zero errors later, so skip them
                    continue;
                }

                // if (c - d) * e == 4
                int e = 4 / (c - d);
                if (from > e || e > to) {
                    continue;
                }

                // if (b - d) * g == 4
                int g = 4 / (b - d);
                if (from > g || g > to) {
                    continue;
                }

                // if 9 - e - h == 4
                int h = 5 - e;
                if (from > h || h > to) {
                    continue;
                }

                if (isSolution(a, b, c, d, e, f, g, h)) {
                    printSolution(new int[] { a, b, c, d, e, f, g, h });
                }
            }
        }
    }
}

This would drop us from 25,600,000,000 iterations of the innermost loop to 8000 with a modest increase in complexity per iteration.  This works because the equations in the solution checker tell us constraints that we can use to determine some of the variables if we have others (comments in the code with more specific explanations).  With sufficient algebra you might eliminate one of the remaining three loops as well.  Note that we have an additional equation that we are not using (f + g - h == 4).

Added logic to verify that the calculated variables are within the from/to range.  This doesn't seem to have been necessary for this particular problem, but that seems likely to have been just luck.  I think that you could probably demonstrate that by setting from to 1 and to to 6.


A simple Dice Game Using only Static methods

Here's my list of points (don't be discouraged by it):

You have multiple functions which appear to do similar things with only minute differences. For example, getFirstNumberInput() and getSecondNumberInput() appear to be the same, however one uses the word "first" in its print and the other uses "second". So that you avoid repeating your code, I would create a single function which can handle both operations. Either you pass in the text "first" or "second" as an input to that function, or you reword the print to make those words unnecessary to state (for example "Enter a number from 1 to 6").
Don't forget to close your scanners when you're done with them.
Not sure if this was an issue you faced when copying your code into the question, but if it isn't then you should also sort out your indentations by having indentation before closing braces line up with the indentation of the line where the matching opening brace was.
Your code uses recursion for the validation - I would recommend changing it so that the input is not accepted until a valid value is provided, rather than sending your program into a potentially infinite stack of function calls. This means that you should use an until loop to check if input is valid before moving out of the loop and setting the input value.
Your code uses class variables when it doesn't need to - the scope of the variables should be restricted to main and then the functions should return values which will be assigned to the variable, so rather than what you currently have you end up with int firstInput = getInput(). I would never personally have the function itself assign a value, but rather it should always return a value which the main method can handle.
Variable naming is important. Whilst this is quite a small program, and a programmer would easily be able to look at the code to see how your variables are being used, it would be much clearer for someone to see a variable called "firstInput" rather than "first". Concise variable names are important.
Despite the fact that you call validateSecondNumber as part of the main method, you call it within the validateFirstNumber method as well. Not only does that mean that the method runs more times than it needs to, but you shouldn't really be calling validateSecondNumber from validateFirstNumber. Each method should only do the task it is set - therefore, validateFirstNumber should only validate the first number. It should not also validate the second number.
Due to the way your validateSecondNumber program logic is handled, if you enter a value above 6 multiple times then it will be accepted as a valid input after a few tries.
You should validate inputs as you receive them, so there is no confusion for the user, rather than getting both inputs and then validating them.
A minor point at this stage, but it builds off of what I said about a method only handling what it is designed to. Many of the methods here use prints to tell the user of a mistake that has been made. Instead (in the case of validation routines), you should simply make the main method aware of the mistake made, such as inputting a value that is below zero, and having the main method handle it. This can be in the form of throwing a relevant exception and allowing the main method to catch that and handle it.
You ask for a value inclusively between 1 and 6, but also seem to accept 0 as a valid input. This is because you check if the input < 0 instead of <= 0.
In your last routine, you typed same+++. Instead, I would increment the variable on a separate line to avoid confusion due to multiple plus signs.
\n isn't always enough to present a new line, depending on the environment which the program is running in. Use \r\n for more certainty that it will work on all platforms. The best thing to do would be to get the line.separator property and use that in place of \n.
Unless you have been given a task which specifically says to use only static methods, I would avoid that approach in the future.


strategy pattern, good practices on how to switch between classes

You are probably looking for factory method pattern, instead of strategy pattern.

The CustomItemSender class is a good indicator of this.
Whenever you extend a class to only override the constructor, you probably need a factory instead. It means you need somewhat more complex way of constructing the object and that implies creational pattern. Strategy is a behavioral pattern (and in fact, your code does not implement this pattern).

The EnvironmentInterface is basicaly a data structure, it is immutable which is good, but it has no behaviour, which is not so good. It is just a tuple. Maybe you don't really need this structure and stay with tripplet of arguments.

Polymorphism only makes sense to abstract varying behaviour, not data. Anyway polymorphism won't help you avoid ifs/switches entirely. It will help you reduce the amount of them to minimum. You might still need some ifs in the creational part, but once a polymorhic object is created, it no longer repeats those ifs because it encapsulates the beforehand chosen branch.

Sometimes ifs/switches can be replaced by key-value maps though (such a map could be owned by a factory...).

Getting config values from a file using global function like yours getFromConfigFile(string $key) is not very wise btw. Because it either loads the file again on every request for a key. Or it loads it only once but stores the loaded data to a global variable thus having side effects on globle state which is a bad practice. You might want to load all config from the file to lets say array (possibly encapsulated in an objet) and serve the individual config values from it. And btw the function knows the location of the config file globally/magically and that is also not very good. You might need a factory for the config object, which will load the config from a given a file.

function loadConfigFromJsonFile(string $filename): array
{
  // add error handling
  return json_decode(file_get_contents($filename), true);
}

class SenderFactory
{

  private string $endpoint;
  private string $user;
  private string $password;

  public function __construct(string $endpoint, string $user, string $password)
  {
    $this->endpoint = $endpoint;
    $this->user = $user;
    $this->password = $password;
  }

  public function createOrderSender(): OrderSender
  {
     return new OrderSender($this->endpoint, $this->user, $this->password);
  }

  public function createItemSender(): ItemSender
  {
     return new ItemSender($this->endpoint, $this->user, $this->password);
  }
}

function createSenderFactory(string $env, array $config): SenderFactory
{
  // the if has to go somewhere anyway
  // add some error handling too (missing config keys, unknown $env, etc.)
  if ($env === 'testing') {
    return new SenderFactory($config['API_ENDPOINT_TESTING'], 'testing', 'testing');
  } else {
    return new SenderFactory($config['API_ENDPOINT_PRODUCTION'], 'production', 'production');
  }
}

// ...

$config = loadConfigFromJsonFile($configPath);
$factory = createSenderFactory($env, $config);
$orderSender = $factory->createOrderSender();
$itemSender = $factory->createItemSender();
```


l is a terrible name for anything. Depending on the font used, it may be indistinguishable from the number one. It's generally recommended to avoid using the letter "l" for anything. (In some languages this recommendation is part of the official style guide.)

log would be better, still short, and with a more obvious meaning than just "l".


using namespace std; Never do this
Prefer using \n over std::endl as the latter flushes the buffer which is rarely needed and can be detrimental to performance.
const your arguments whenever possible. More about const correctness
* and & are considered to be part of the type in C++ so prefer writing int& foo instead of int &foo. Likewise for *.
Never omit optional braces as doing so will lead to bugs eventually.
Reaching the end of main will automatically return 0 so you can remove the trailing return 0
Don't initialize more than one variable per line.
I like that you use the prefix operator. Your naming is pretty good too so why are you doing this?

// Close the file
file.close();

or this

// Loop through arguments
for (int i = 0; i < argc; ++i)

Your comments are completely superfluous and can all be removed.
What is this?

// Free the memory
token = nullptr;
delim = nullptr;
delete token;
delete delim;

delete is only used after a matching new. It feels like you misunderstood something in regard to memory managment. Read up on this again.
new
delete
memory managment

BinarySearchTree *tree = new BinarySearchTree();

I don't know how this is implemented but a line like that looks like something from Java. Do you really need to put this on the heap?

Personally I think the word splitting could be done rather elegantly in regex. However many people are quite opposed to using regex. I've also read that in the past regex performance in C++ was rather poor but it might be worth measuring to see if it's within acceptable limits for your use-case.

Regex example:

std::regex rx{R"(([^ .,?!:;/\"\'\n\t]+))"};
auto data_begin = std::sregex_iterator(data.begin(), data.end(), rx);
auto data_end = std::sregex_iterator();
for (std::sregex_iterator it = data_begin; it != data_end; ++it) {
    // do something with words here
}


The concurrency looks bug-free to me, which is rare!

Some nits on C++ idioms:

It is extremely unusual to take a function pointer as a template parameter. This drastically limits the reusability of your class template. A more traditional, "STL-ish" interface would be

template<class Buffer, class Produce, class Consume>
class triple_buffer {
    explicit triple_buffer(Buffer bufs[3]);
    explicit triple_buffer(Buffer bufs[3], Produce produce, Consume consume);
    // ...
};

Or, since produce and consume are used only inside the constructor — it immediately wraps them up in lambdas and passes them off to std::thread — you don't even need them to be template parameters of the whole class. They can be template parameters of the constructor itself. Something like this:

template<class Buffer>
class triple_buffer {
    template<class P, class C>
    explicit triple_buffer(Buffer bufs[3], P produce, C consume) {
        // ...
        produce(present_.load());
        producer_thread_ = std::thread([&, produce]() {
            while (!stop_.load()) {
                produce(inprogress_.load());
                inprogress_ = ready_.exchange(inprogress_);
                stale_.store(false);
            }
        });
        // ...
    }
};

(In C++14 you can capture produce as [&, produce = std::move(produce)] to avoid making a copy of it.)

Notice the CamelCase template parameter names.

I also recommend sigilling the names of your member variables — ready_ rather than ready, and so on. (Some coding style guides prefer m_ready or d_ready. No big deal.)

These two naming conventions, together, will help to alleviate some of your confusingly similar naming. Right now you've got a template parameter named produce and a member function named producer (and your test harness has a global function named produce). Of course, I just "fixed" that naming issue by getting rid of the producer member function altogether!

You use both atomic<bool> stop and atomic_flag stale. There's no significant difference between atomic<bool> and atomic_flag; you should pick one and stick to it. I recommend atomic<bool> because it's one fewer thing for your coworkers to look up on cppreference.

inprogress = ready.exchange(inprogress);

This line is correct, but I really strongly encourage you to rewrite it as two lines anyway. "One side-effect per source line" is a good rule of thumb for concurrent code. And there really are two side-effects happening here.

Buffer *p = ready.exchange(inprogress);
inprogress.store(p);

Splitting it up this way makes it clear what's going on — in particular that the swap is not being effected atomically — and incidentally makes the code easier to stress-test (by adding instrumentation between each pair of lines) and debug (because now it's possible to pause the debugger between the two side-effects).

while (stale.test_and_set())

If you switch to consistently using atomic<bool>, this line would become

while (stale.exchange(true))

consumer_thread = std::move(std::thread([this] { consumer(); }));

This line is overengineered. You don't need to std::move a prvalue. And personally, I'd capture [&] unless I had a special reason not to. So:

consumer_thread = std::thread([&]{ consumer(); });

Stylistically, I wonder why triple_buffer takes a pointer to an array of three Buffer objects, as opposed to either

taking three pointers to Buffer objects (which then needn't be adjacent in memory), or
giving triple_buffer three member variables of type Buffer.


I would agree that defining pb as an object is a code smell and should be eliminated.

Either in addition or instead of having Cars and Trucks inherit from ProductsBase(of T) it should implement an interface.

Suggested Interface:

Public Interface IProducts

    Sub DeleteRows()
    Sub Parse()

End Interface

Then you would declare pb as IProducts. Add any other public properties that will be used by all the derived classes of ProductsBase.

I'd also suggest creating a class or modules that contains factory methods to generate the new objects.

Suggested Factory Class:

Public Class ProductsFactory

    Public Shared Function CreateTruck(fileLocation as string) As IProducts
         Return New Truck(fileLocation)
    End Function

    Public Shared Function CreateCar(fileLocation as string) As IProducts
         Return New Car(fileLocation)
    End Function

End Class

The final code would look like this:

  Dim pb As IProducts

  If radCars.Checked = True Then
     pb = ProductsFactory.CreateCar(fileLocation)
  ElseIf radTrucks.Checked = True Then
     pb = ProductsFactory.CreateTruck(fileLocation)
  End If

  pb.Parse()
  pb.AddRows()