I would focus on the following improvements:

avoid code duplication - for instance, you have the User-Agent string specified twice - extract it as a constant and re-use. GetPageData also has duplicated code
some of your locators are layout-oriented which makes them less reliable and less readable - Bootstrap classes like col-lg-12 or col-md-11 have a layout/design meaning and have a high probability of change. row businessCapsule--title can become businessCapsule--title; col-sm-10 col-md-11 col-lg-12 businessCapsule--address would become businessCapsule--address.


TCP client reconnection logic running on 30 machines

catch (Exception)
{
  Reconnect();
}

The same pattern can be found in almost every method. Are you not interested in what happened? No logging or anything? Just ignore the exception?

_pingTimer = new Timer { Interval = 2000 };
Thread.Sleep(500);

Hardcoded numbers? No settings? What if this won't work and you have to tune it? You'll have to update all instances!

Enum.TryParse(messageParts[0], out MessageType messagetype);

Why isn't this inside an if?

if (messagetype == MessageType.UpdateContentType)

This is the next line following the TryParse but this can go sideways if the UpdateContentType is the first value of the enum it might be returned as a default value and the flow will enter the if even if the massage part wasn't in the correct format.

private void TcpClientOnDataReceived(object sender, Message message)

You have try/catches for everything but this method. If something goes wrong here the application will crash.

  60 instances of this program are supposed to run on 30 machines, meaning there are 2 instances of it running on each machine. It is used to keep all the client instances (running this code) connected to the controller that gives them updates when needed.

This sounds like too much. Why can't the client check for updates by itself?

  Once the software is deployed, I will most likely not be able to make any changes anymore.

If you are not able to update it later then you should start writing all kinds of unit and integration tests to make sure it's bullet-proof but even then there will still be a bug somewhere... Not being able to deploy new versions is a terrible plan.


I would do this using an interface and polymorphism to represent this:

public interface ISession
{
    void DoSomething();

    // Add your properties / method definitions
}

public class ServerSession : ISession
{
     private readonly string _serverName;

     public ServerSession(string serverName)
     {
         _serverName = serverName;
     }

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}

public class OtherSession : ISession
{

     public void DoSomething()
     {
         // Some Code
     }

     // Implement interface contracts
}

Then you would use it something like this:

public DoSomethingWithSession(ISession session)
{
     session.DoSomething();
}

foo.DoSomethingWithSession(new ServerSession());

If there is commonality between ISession implementations, you could base class that out, then inherit from that.


Simpler version of capitalizing each word in a string

You can use String#replace with a regexp:

function titleCase(str) {
  return str.toLowerCase() // change the string to lowercase
    .replace(/\S+/g, function(s) { // get all non space characters sequences
      return s.charAt(0).toUpperCase() + s.substring(1); // uppercase the 1st letter and combine with the rest of the string
    });
}

console.log(titleCase("I'm a little tea pot"));


Add Field To PDF with Options for Multiple Pages

The code on your case statements is not that different.
You could consider to group all cases that add many fields and those who only add one.

Another thing that is worth mentioning is that unless the option is
Pages.Last you always start with PdfFirstPageNumber or that +1.

Let's give a shot to reimplement the method based on this:

private void AddFieldToPdf(Field field,
    iTextSharp.text.pdf.PdfStamper pdfStamper, int numberOfPages)
{
    var parentField = iTextSharp.text.pdf.PdfFormField.CreateTextField(
        pdfStamper.Writer, false, false, 0);
    parentField.FieldName = field.Title;
    int pageNumber = field.Pages == Pages.Last ? numberOfPages : PdfFirstPageNumber;
    switch (field.Pages)
    {
        case Pages.All:
        case Pages.Odd:
        case Pages.Even:
            int increment = field.Pages == Pages.All ? 1 : 2;
            if(field.Pages == Pages.Even){
                pageNumber += 1;
            }
            for (;pageNumber <= numberOfPages; pageNumber += increment)
            {
                AddFieldToPage(field, pageNumber, pdfStamper,
                    parentField);
            }
            break;
        case Pages.First:
        case Pages.Last:
            AddFieldToPage(field, pageNumber, pdfStamper,
                parentField);
            break;
    }
    pdfStamper.AddAnnotation(parentField, 1);
}

EDIT Continuing improvements we can now see that we have two major branches, so maybe an if fits better:

 private void AddFieldToPdf(Field field,
    iTextSharp.text.pdf.PdfStamper pdfStamper, int numberOfPages)
{
    var parentField = iTextSharp.text.pdf.PdfFormField.CreateTextField(
        pdfStamper.Writer, false, false, 0);
    parentField.FieldName = field.Title;
    int pageNumber = field.Pages == Pages.Last ? numberOfPages : PdfFirstPageNumber;

    if(field.Pages == Pages.First || field.Pages  == Pages.Last){
        AddFieldToPage(field, pageNumber, pdfStamper, parentField);
    }else{
        int increment = field.Pages == Pages.All ? 1 : 2;
        if(field.Pages == Pages.Even){
            pageNumber += 1;
        }
        for (;pageNumber <= numberOfPages; pageNumber += increment)
        {
            AddFieldToPage(field, pageNumber, pdfStamper, parentField);
        }
    }
    pdfStamper.AddAnnotation(parentField, 1);
}

There is actually a way to transform that switch statement into a Linq code.

Now I am not saying this code is more clear than yours, that may depend on who is maintaining it.
But if you like Linqand would to give it a shot it works as follows:

var query = Enum.Range(PdfFirstPageNumber, numberOfPages);
if(field.Pages == Pages.Odd || field.Pages == Pages.Even){
    int parity = field.Pages == Pages.Odd ? 1 : 0;
    query = query.Where(p => p%2 == parity);
}else if(field.Pages == Pages.First){
    query = query.Take(1);
}else if(field.Pages == Pages.Last){
    query = query.Reverse().Take(1);
}
foreach(var page in query){
    AddFieldToPage(field, page, pdfStamper, parentField);
}


Find index of an object with a specific value stored in an array

I think the best way of doing that would be using the new ES6 function Array.prototype.findIndex:

data.findIndex(function(obj) { return obj[where] === what; })

If you don't have that function, there are good polyfills at MDN and NPM.

(if you do have full ES6, you apparently could also do

data.findIndex(obj => obj[where] === what)

but i'm still learning how that syntax works so i may be wrong there)


.htaccess using public folder and SEO friendly URL

Redundant RewriteEngine declarations
Unused match group in (public)
Escaping (using \) is not needed in the new URLs
A personal touch, but I prefer to keep the core directives at the top, and put module specific directives inside <IfModule> body, so that I won't receive errors if the modules are disabled.
Multiple declarations for ErrorDocument 500

Options +FollowSymLinks -MultiViews

ErrorDocument 401 /subscription/how_to_subscribe.html# Turn mod_rewrite on
ErrorDocument 404 /errors/not_found.html
ErrorDocument 500 http://error.example.com/server_error.html

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    RewriteCond %{REQUEST_URI} !^/(public)
    RewriteRule ^ /%1%{REQUEST_URI}

    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteCond %{REQUEST_URI} !/$
    RewriteRule ^(.*)$ $1.php [L]
</IfModule>


Human readable display of a list of things

It's often more readable to write trait bounds (e.g. T: Display) in a where clause rather than directly next to the declaration. Also, there are some types of bounds that cannot be written with the angle brackets and must instead be written in a where clause (there are examples below). When you have a where clause, put all the bounds here; don't put bounds in both places, because then it's easy for someone reading the code to miss the bounds in the angle brackets.
You don't need the T type parameter on your function; you can write the bound I::Item: Display to get the same effect.
The if it.peek().is_some() is unnecessary; if that expression returns false, the program wouldn't enter the while let loop anyway, and that loop is the only statement in the if.
By using DoubleEndedIterator::next_back, we can extract the last item from the iterator. This lets us remove the peeks to determine whether you should use a comma or "and" as the separator. However, this restricts the types of iterators that the function accepts, because the iterator must now implement DoubleEndedIterator. In order to write this requirement, we must write the bound I::IntoIter: DoubleEndedIterator in a where clause; we can't write this within the angle brackets.

fn enumerate<I>(it: I) -> String
where
    I: IntoIterator,
    I::Item: Display,
    I::IntoIter: DoubleEndedIterator,
{
    let mut it = it.into_iter();
    let mut result = String::new();

    if let Some(first) = it.next() {
        write!(result, "{}", first).unwrap();

        if let Some(last) = it.next_back() {
            while let Some(item) = it.next() {
                write!(result, ", {}", item).unwrap();
            }

            write!(result, " and {}", last).unwrap();
        }
    }

    result
}

  I wonder if this is possible to write the function in a more functional manner?

Building upon the code above, we can replace the while let loop with a fold.

fn enumerate<I>(it: I) -> String
where
    I: IntoIterator,
    I::Item: Display,
    I::IntoIter: DoubleEndedIterator,
{
    let mut it = it.into_iter();
    let mut result = String::new();

    if let Some(first) = it.next() {
        write!(result, "{}", first).unwrap();

        if let Some(last) = it.next_back() {
            result = it.fold(result, |mut result, item| {
                write!(result, ", {}", item).unwrap();
                result
            });

            write!(result, " and {}", last).unwrap();
        }
    }

    result
}

write! doesn't "feel" functional, though, because it mutates its operand rather than returning a new value. Therefore, in this case, I don't think the version with fold is really more readable than the version with while let.

By using itertools, a third-party crate published on crates.io, we can simplify the code a bit and give it a more functional feel by using its join adapter. Its implementation is more or less what we were doing before.

extern crate itertools;

use std::fmt::{Display, Write};
use std::iter;

use itertools::Itertools;

fn enumerate<I>(it: I) -> String
where
    I: IntoIterator,
    I::Item: Display,
    I::IntoIter: DoubleEndedIterator,
{
    let mut it = it.into_iter();

    if let Some(first) = it.next() {
        if let Some(last) = it.next_back() {
            let mut result = iter::once(first)
                .chain(it)
                .join(", ");

            write!(result, " and {}", last).unwrap();
            result
        } else {
            format!("{}", first)
        }
    } else {
        String::new()
    }
}


Generates a bare git repo from existing one and copy it to a central server

Bug

First things first, this doesn't work:

if [ "$1" == "--help" ] | [ $# -eq 0 ] ; then

You need || there, not |.

Local bare repo + copy vs remote bare repo + push

I completely agree with @Vogel that it would be better to create the bare repo on the remote, and then push to it:

git push is the simplest and safest way to transport Git repo data
Working with temporary dirs is messy. If your script gets killed in the middle, the cleaning at the end may not be reached (this could be improved by using trap)
The local bare clone unnecessarily doubles the .git storage space locally

Usability

The current script must be run in the parent directory of a Git repo,
as it is enforced by the [ ! -d "${LOCAL_REPO}" ] condition.
This is not convenient, and it doesn't have to be that way.

You could make it work with any valid path by making these two simple changes:

# LOCAL_REPO=$(basename $1)
LOCAL_REPO=$1

# NEW_REPO_DIRNAME=${LOCAL_REPO}.git
NEW_REPO_DIRNAME=$(basename "$LOCAL_REPO").git

Quoting

It's a good practice to double-quote variables used in command arguments.
For example instead of this:

LOCAL_REPO=$(basename $1)

It's good to make it a habit to write like this:

LOCAL_REPO=$(basename "$1")

(I trust you don't intend to ever create a repository with a space in the name, but this is still a good habit to pick up.)

The same goes for running the uses of $GIT and $SCP.

On the other hand, some quoting is unnecessary, for example you could write like this:

GIT=/usr/bin/git
SCP=/usr/bin/scp

if [ "$1" = --help ] || [ $# -eq 0 ] ; then

This is just for your information, it's ok the way you did it.

Only loosely related, but simply echo is the same as echo "".

Changing directories in scripts

Be careful with changing directories in scripts. If an error happens in the middle of the operation, the next operation may find itself in an unexpected directory (in the absence of adequate error handling).

Changing directories can become safer using (...) sub-shells. For example instead of this:

cd ${LOCAL_REPO}
$GIT remote add origin ${REMOTE_DIR}/${NEW_REPO_DIRNAME}
$GIT remote -v
cd ..

You could write like this (without the cd .. at the end):

(
    cd ${LOCAL_REPO}
    $GIT remote add origin ${REMOTE_DIR}/${NEW_REPO_DIRNAME}
    $GIT remote -v
)


Rotating contents of a matrix (vector) to the left or right

I didn't look very closely at the algorithm, so I'll trust that it is correct ;)

Some stylistic changes you could do are:

Use auto to clean up those long iterator names.
Break long lines. Shorter lines are usually easier to digest.
DIRECTION is a bit unusual for the name of an enum type. That notation is normally used for the enum constants, the type usually goes with the same notation used for classes and structs (CamelCase, in most projects).
Use const as much as possible. Making the integer indexes const in this case won't change much, but making things that are not supposed to change const is a good habit, so you should aways try to do it, even for small sections of code. You never know when that tiny function might grow.

Following is a snippet of code with the above changes applied:

enum Direction
{
    DIR_RIGHT = 0,
    DIR_LEFT  = 1
};

std::vector<std::string> rotate(const std::vector<std::string>& original, Direction direction)
{
    std::vector<std::string> rotated(original);

    for (auto irow = original.cbegin(); irow != original.cend(); ++irow) {

        const auto new_col = (direction == DIR_RIGHT) ?
            (original.size() - 1) - (irow - original.cbegin()) :
            (irow - original.cbegin());

        for (auto icol = (*irow).cbegin(); icol != (*irow).cend(); ++icol) {

            const auto new_row = (direction == DIR_RIGHT) ?
                (icol - (*irow).cbegin()) :
                ((*irow).size() - 1) - (icol - (*irow).cbegin());

            rotated[new_row][new_col] = *icol;
        }
    }

    return rotated;
}

Side note: You might also want to check out std::distance() to replace the iterator diferences you are computing with operator -.

Also, by using cbegin()/cend(), you can ensure the returned iterators are of type const_iterator and thus pointing to immutable data.


I think that in terms of performance you'd be hard pressed to do better than a LINQ query.  Not only fast but very compact and relatively easy to understand.  It could look something like this:

public IList<int> TopKFrequent(int[] nums, int k) {
    var answer = (from int n in nums
                  group n by n into g
                  orderby g.Count() descending
                  select g.Key).Take((k)).ToList();
    return answer;
}

For those that prefer method syntax here's the equivalent:

public IList<int> TopKFrequent(int[] nums, int k) {
    var answer = nums.GroupBy(n => n).OrderByDescending(g => g.Count()).Take(k).Select(g => g.Key).ToList();
    return answer;
}


Selecting orders submitted by a user, segregated by status

I see two opportunities to improve your code.

1. Custom orders collection

This would be the fast and easy approach. Make a custom 'Orders' collection that extends the Eloquent collection. On that collection, you can add your custom filters for 'completed', 'cancelled' and 'ceased'. By overwriting the newCollection method on the Order model, you can make it automatically return this custom Orders collection when queried. You can then assign that collection to your view, and there you can ask the collection for the different types of orders and use them as you please. Or you could do that in your controller as well if you prefer.

2. status_id in stead of flags

You may take it a step further, depending on how far you want to refactor your data and the scope of your app. In stead of working with those 3 booleans for determining the 'type' of order, consider working with a single 'status_id' column. You could for instance define in your model:

const STATUS_COMPLETED = 1;
const STATUS_CEASED = 2;
const STATUS_CANCELLED = 3;

Then you can just fetch all your orders (possibly paged, or with some filters added) in a single query, and again filter on your collection to get the order type you need. And if anywhere in your app you only need orders with a certain status, you can just do something like Orders::where('status_id', Orders::STATUS_CANCELLED)->get();

I can see a few aditional advantages for this approach:

It would be very easy to put an index on that status column, which could greatly improve query performance
Query performance will be better anyway, since you only need a single where condition, which is obviously better then 3
If you later decide to add an extra status, like 'shipped' or 'returned' or something, you would only have to add a few constants, your data would remain in tact.
It is just semantically more correct imo. An order can not be confirmed and cancelled at the same time, but what if you make a mistake somewhere. You the risk creating corrupt data.
This approach would make it fairly easy to expand your application with a full order history, by creating 'status_changes' table ('order_id', 'status_id', 'date' , ...), to which you would write the status each time you change it.

As I said, how far you should go depends on the scope of your project (and your budget), as always. But it wouldn't be that big a job I think, and the benefits would be substantial.

Let me know if you want me to elaborate on anything, or if you want me to add some (pseudo) code. Hope it helps!


I'll just list things as I read them, so don't expect any sort of meaningful order:

Prefer let over var - let provides variable declaration in block scope, rather than functional scope. It also prevents hoisting. It solves a few language gotchas that var has. Please note that currently, you can only use let in contexts under strict mode (which you already have, good for you!)
Your getDistanceFromLatLonInKm() function has many single letter variables, which makes it a bit hard to follow. What's R? Earth's radius in km? Why not EarthRadius?
If you only need to return a single expression from an arrow function, you don't need the full form.

(arg1, arg2) => { return something }

can be shortened to

(arg1, arg2) => something

in case something is an object literal, you can wrap it with braces like so:

(arg1, arg2) => ({something: here})

Your compareUserID() function can be shortened to

var compareUserID = (a, b) => a.user_id - b.user_id;

Think twice before defining a function within another function, the inner function will be redefined for every function call.
The [].map() function is meant for mapping one array to another, not for logging. If you want to just iterate the array and do something without returning anything, use [].forEach(), also, you don't need to full form of the arrow function for console.log:

contacts.forEach(contact => console.log(`...`));

Node supports object literal shorthands, if the key and the variable name you're defining have the same name, you can do it like this:

return {init, toRadians, processClients, getDistanceFromLatLonInKm};

It would be likely better if the init() function accepted the URL to the file to be processed. That way, if you ever change URLs (which is more than likely, because raw GitHub urls stay relevant for so long), you can leave your module's code untouched.
Node's modules are implicitly wrapped by IIFEs anyway, so your IIFE is redundant. Remove var ClientsNearby = (function(){ and }(); to save yourself a level of indentation across the script. Just assign your object literal with functions to module.export directly.
It's considered good practice to have as few side effects as possible in your modules (such as producing output). Think about how you'd want to use a module. Personally, I'd like to be able to invoke a function and get an array (or a collection) of data, for me to do what I please. Tomorrow you wouldn't want to output the clients, you'd want to log them into a file, or push them into a database.


The loop

while pointer >= len(players):
    pointer = pointer - len(players)

is a long way to say pointer %= len(players).
You'd be in a better position factoring the computations into a function,

def survivor(n):
    skip = 0
    players = [x for x in range (1, n+1)]
    pointer = 0
    while len(players) > 1:
        pointer += skip
        while pointer >= len(players):
            pointer = pointer - len(players)
        players.pop(pointer)
        skip += 1
    return players[0]

and adding an if __name__ == '__main__' clause. This way it is easy to generate first few results.

TL;DR

I did so, generated first 20 numbers,

    1 2 2 2 4 5 4 8 8 7 11 8 13 4 11 12 8 12 2

and search this sequence in OEIS.

Surprisingly there was a match. A closer inspection demonstrated that the problem is a Josephus problem with eliminating every n-th person. Try to prove, or at least convince yourself, that it is indeed the case.

Further reading revealed that there is a linear solution.


Handling multiple dimensions of arrays with speed

Have some rewrite rules applied, combinators used and helpers inlined while I think about your algorithmic question. And make Vendor a newtype.

minimalBasketPrice mP vD
  = nub
  . map vendorNbr
  . minimumOn (sum . map deliveryTime)
  . filter ((<= mP) . sum . map itemPrice)
  . sequence
  . (map . filter) ((/= -1) . itemPrice)
  . transpose
  . zipWith3 (\x y -> map (Vendor x y)) [0..] vD

This is the backpack problem and NP-hard. We won't be scaling well in the worst-case whatever we do, but we can do a little better by, for example, only keeping track of suffixes of vendor selections that can't be undercut in time and price at the same time:

newtype Candidate a = Candidate
  { vendors :: [Int]
  , time :: Int
  , price :: Int
  }

minimalBasketPrice mP vD
  = nub . vendors . head
  . foldr (foo mP) [Candidate [] 0 0]
  . map (filter ((/= -1) . itemPrice))
  . transpose
  . zipWith3 (\x y -> map (Vendor x y)) [0..] vD

foo :: Int -> [Vendor] -> [Candidate] -> [Candidate]
foo mP choices
  = catMaybes . snd
  . mapAccumL bar (mP+1)
  . sortOn time
  . liftA2 addVendor choices

bar :: Int -> Candidate -> (Int, Maybe Candidate)
bar bestprice candidate = if price candidate < bestprice
  then (price candidate, Just candidate)
  else (bestprice, Nothing)

addVendor (Vendor v t p) (Candidate vs ts ps) = Candidate (v:vs) (t+ts) (p+ps)


There are two approaches

For the sake of completeness, I’ll describe the typical, simple solution:

struct UserLoginResponse: Codable {
    let status: Bool
    let error: ErrorResponse?
    let accessToken: String?
    let data: [UserLoginData]?
}

The status is not optional (because it’s presumably there regardless). But you can just decode this struct:

do {
    let responseObject = try decoder.decode(UserLoginResponse.self, from: data)
    switch responseObject.status {
    case true:
        guard let accessToken = responseObject.accessToken, let userLoginData = responseObject.data else {
            throw ParsingError.requiredFieldMissing
        }

        // use accessToken and userLoginData here

    case false:
        guard let errorObject = responseObject.error else {
            throw ParsingError.requiredFieldMissing
        }

        // use errorObject here
    }
} catch {
    print(error)
}

If you really want to do this generic, wrapper approach, I’d suggest a slight refinement. Notably, the code in your question returns an object for which both the success and error objects are optionals. (There seem like there are a lot of ? thrown in there quite liberally, whereas most API dictate “if success, x and y will be present, if failure, z will be present”.)

I’d suggest, instead, a pattern that captures the fact that the response will be either success (when status is True) or failure (when status is False), and rather than returning both success and failure objects as optionals, use the Result<Success, Failure> enumeration with associated values, which is included in Swift 5. Or, if you’re using an earlier version of Swift, you can define it yourself:

enum Result<Success, Failure> {
    case success(Success)
    case failure(Failure)
}

Then, the API response wrapper can have a non-optional result property of type Result<T, E>, where:

If status is True, parse the success object as a non-optional associated value which is the Success type;
If status is False, parse the error object as a non-optional associated value which is the Failure type;

Thus:

struct ApiResponse<T: Codable, E: Codable>: Codable {
    let status: Bool
    var result: Result<T, E>
    var error: E?

    enum CodingKeys: String, CodingKey {
        case status, error
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        status = try values.decode(Bool.self, forKey: .status)
        if status {
            let singleValue = try decoder.singleValueContainer()
            result = try .success(singleValue.decode(T.self))
        } else {
            let parsedError = try .failure(values.decode(E.self, forKey: .error))
            error = parsedError
            result = .failure(parsedError)
        }
    }
}

Then you can do:

do {
    let responseObject = try decoder.decode(ApiResponse<UserLoginResponse, ErrorResponse>.self, from: data)
    switch responseObject.result {
    case .success(let object):
        print(object.accessToken, object.data)

    case .failure(let error):
        print(error)
    }
} catch {
    print(error)
}

This would seem to better capture the true nature of the response, that it’s either successful (and you get the non-optional success object) or it’s a failure (and you get the non-optional ErrorResponse object).

By the way, I’d suggest that in this scenario, that UserLoginResponse be updated to reflect which fields are truly optional and which aren’t. For example, if you know that if status is True, that both accessToken and data will be present, then I’d make those non-optional properties:

struct UserLoginResponse: Codable {
    let accessToken: String
    let data: [UserLoginData]
}


Efficient implemetation of AlertDialog callback in Android

for a confirmation dialog use setCancelable(true) to make the user able to cancel the dialog using the back button. This is the native way and you don't have to implement anything.

Note: in Android you are not supposed to close the application. The operating system will close it when it feels like to do so.


PEP 8, the official Python style guide, says that indentation should be 4 spaces per level.  Since whitespace is significant in Python, that is a pretty strong convention.

The implementation could be less verbose:

sorted(list(graph.keys()), …) could be shortened to sorted(graph, …).
Instead of defining available_colors as a list of booleans, you could define taken_colors as a set, ideally using a generator expression.
The loop that assigns color_map[node] can be simplified down to next(generator expression with a condition).

def color_nodes(graph):
    color_map = {}
    # Consider nodes in descending degree
    for node in sorted(graph, key=lambda x: len(graph[x]), reverse=True):
        neighbor_colors = set(color_map.get(neigh) for neigh in graph[node])
        color_map[node] = next(
            color for color in range(len(graph)) if color not in neighbor_colors
        )
    return color_map


Code organisation

You've tried to split your logic into smallish functions which is a good idea but you could go further. You should try to write a function that handles the input/output part and a function which takes a well defined input (with the most relevant data types as an argument) and computes whatever needs to be computed before returning it (such a function should not do any input parsing or print anything except for debug purposes).

In you case, the most logical input such a function would take is the queue. The corresponding data type would be a list of int and the return type would be an integer (or None).

If you do so, you have smaller independant logical parts which are easier to understand, to maintain and to tests. Among other things, you can write unit tests based on the examples provided to ensure the computation works well.

In you case, moving the different pieces of logic around, you get something like:

#!/bin/python3

import sys

# Swaps the i'th and (i-1)'th elements and returns the list
def swap(intermediate_q,i):
    intermediate_q[i],intermediate_q[i-1] = intermediate_q[i-1],intermediate_q[i]
    return(intermediate_q)

# Increment bribes and total_bribes
def compute_bribes(bribes,total_bribes):
    if(bribes+1==3):
        return (-1,-1)
    return (bribes+1,total_bribes+1)

def get_number_brides(queue):
    """Take a queue (list of int) as a parameter and return the number of brides or None."""
    n = len(queue)
    initial_q = list(i+1 for i in range(n))
    total_bribes = 0
    for i in range(n):
        bribes = 0
        # If the position in the initial/transition queue is not equal to the position in the final queue
        # queue is the input against which swaps are made in my initial_q.
        if(queue.index(initial_q[i]) != initial_q.index(initial_q[i])):
            index_in_initial_q = initial_q.index(queue[i])
            index_in_queue = queue.index(queue[i])
            while(index_in_initial_q != index_in_queue):
                initial_q = swap(initial_q,index_in_initial_q)
                bribes,total_bribes = compute_bribes(bribes,total_bribes)
                if(bribes == -1):
                    return None
                index_in_initial_q-=1
    return total_bribes

def test_stdio():
    inp0 = sys.stdin.read()
    inp1 = inp0.split('\n')
    T = int(inp1[0])
    del inp1[0]
    print("inp1", inp1)
    for i, val in enumerate(inp1):
        if i % 2 == 1:
            ret = get_number_brides([int(v) for v in val.split(' ')])
            print('Too chaotic' if ret is None else ret)

def unit_tests():
    assert get_number_brides([2, 1, 5, 3, 4]) == 3
    assert get_number_brides([2, 5, 1, 3, 4]) is None

if __name__ == "__main__":
    unit_tests()
    # test_stdio()

Among the nice benefits, because the function is now used for a single test case, I can return directly from the most relevant place and this is no need for a chaos_flag anymore (if you were to keep such a flag, it'd be a good idea to use the Boolean type).

Style

Python has a Style Guide called PEP 8 which is definitly worth having a look at and following. In your case, the spacing (both vertical and horizontal) is not quite perfect and so is the usage of useless parenthesis.

Fixing this, you get:

#!/bin/python3

import sys

# Swaps the i'th and (i-1)'th elements and returns the list
def swap(intermediate_q, i):
    intermediate_q[i], intermediate_q[i-1] = intermediate_q[i-1], intermediate_q[i]
    return(intermediate_q)

# Increment bribes and total_bribes
def compute_bribes(bribes, total_bribes):
    if bribes + 1 == 3:
        return (-1, -1)
    return (bribes + 1, total_bribes + 1)

def get_number_brides(queue):
    """Take a queue (list of int) as a parameter and return the number of brides or None."""
    n = len(queue)
    initial_q = list(i + 1 for i in range(n))
    total_bribes = 0
    chaos_flag = False
    for i in range(n):
        bribes = 0
        # If the position in the initial/transition queue is not equal to the position in the final queue
        # queue is the input against which swaps are made in my initial_q.
        if queue.index(initial_q[i]) != initial_q.index(initial_q[i]):
            index_in_initial_q = initial_q.index(queue[i])
            index_in_queue = queue.index(queue[i])
            while index_in_initial_q != index_in_queue:
                initial_q = swap(initial_q, index_in_initial_q)
                bribes, total_bribes = compute_bribes(bribes, total_bribes)
                if bribes == -1:
                    return None
                index_in_initial_q -= 1
    return total_bribes

def test_stdio():
    inp0 = sys.stdin.read()
    inp1 = inp0.split('\n')
    T = int(inp1[0])
    del inp1[0]
    print("inp1", inp1)
    for i, val in enumerate(inp1):
        if i % 2 == 1:
            ret = get_number_brides([int(v) for v in val.split(' ')])
            print('Too chaotic' if ret is None else ret)

def unit_tests():
    assert get_number_brides([2, 1, 5, 3, 4]) == 3
    assert get_number_brides([2, 5, 1, 3, 4]) is None

if __name__ == "__main__":
    unit_tests()
    # test_stdio()

I have no time to go any further but I hope this will help you, another reviewer and future me to take over.


Handling errors with minimal repetition when using Find function

If you absolutely need to use your Find approach, or if you'd just like to see a centralized error handler, as per you question, then you can use a variable to store the custom error message, and then refer to that variable from the error handler:

Also, in you On Error statement, you don't need the trailing ":" as that indicates that the line will have another statement following the ":"

Function getDataPoint(rowItem As String, searchCol As Integer, colItem As String, searchRow As Integer, shtName As String) As Variant

  Dim rowNum As Integer, colNum As Integer
  Dim rowNumRng As Range, colNumRng As Range
  Dim sError As String

  'Find worksheet to search
  sError = "Sheet not found"
  On Error GoTo itmNotFound
  With ThisWorkbook.Sheets(shtName)
    'Find rowNum where rowItem appears in searchCol
    sError = "Row not found"
    Set rowNumRng = .Columns(searchCol).Find(What:=rowItem, _ After:=.Cells(1, searchCol), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=True)
    rowNum = rowNumRng.Row
    'Find colNum where colItem appears in searchRow
    sError = "Column not found"
    Set colNumRng = .Rows(searchRow).Find(What:=colItem, _ After:=.Cells(searchRow, 1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=True)
    colNum = colNumRng.Column
    getDataPoint = .Cells(rowNum, colNum).Value
  End With
  On Error GoTo 0
  Exit Function

itmNotFound:
  Debug.Print sError
  getDataPoint = "NOT FOUND"

End Function


Using record variant for register mapping in Ada

I don’t see any problem with your code in itself; this is exactly the sort of thing variant records are for.

I think the only problem with naming record components is that it can lead you into writing code that attempts to directly alter one component, relying on the compiler to do the necessary whole-register reads and writes (the reference document says in para 17.4 that write accesses must be 16- or 32-bits wide, read accesses must be 8-, 16-, or 32-bits wide). There were discussions on comp.lang.ada about the fact that Ada currently has no way to specify this requirement; AI12-0128 refers (for Ada 2020). GNAT now has the pragma/aspect Volatile_Full_Access.

Nevertheless, naming the components will produce much more writable, readable and verifiable code.


Anything I'm missing on this delegate implementation?

You are missing const and volatile qualified method pointer versions.

Example:

template<class Obj, class R>
struct DelegateHelper<R (Obj::*)() const>{
    typedef R (Obj::*FuncPtr)() const;

    DelegateHelper(const Obj* obj_ptr, FuncPtr func)
        : object_(obj_ptr)
        , func_(func)
    {}

    R operator()(){
        return (object_->*func_)();
    }

    const Obj* object_;
    FuncPtr func_;
};

Also, you may (probably) need specializations or internal delegates for handling of functions with void return values. Someone else may be able to fill in the details, but it seems some compilers are OK with

return function_returning_void();

And others are not.

Another thing that makes the boost version and some others larger is being able to accept & or * arguments for the object value when calling methods.


Here are a few pointers. I should first say that I am more familiar with R;  I know next to nothing about Fortran but I could read your code and guess about a few things that will likely improve your code: both in simplicity and speed.

1) Why the need for two inputs DARTS and ROUNDS? You know that in the end you will have a total of DARTS * ROUNDS simulations: could there just be a single input num_simulations that will be split evenly among your numprocs? This should get you rid of the loop inside snowpi so it could only call dboard once.

2) You should make your slave (snowpi) as simple as possible. IMO, it should not know about things like proc_num or numprocs if you just tell it how many simulations it needs to do. Let R do the math upstream and pass it down to the slave. I don't know much about random generators but maybe the same can apply with the random seeds: if you could let R compute a seed for each slave and pass it down as an (optional) argument to the slave, that would be best. (However, if knowing the proc_num and numprocs is crucial for seed selection and can only happen on the Fortran side, then disregard my comment...)

3) This one I feel is important: do not compute averages too early. They are costly and can make you lose precision. This line in your code (avepi = ((avepi*i) + pi_est)/(i + 1)) is particularly problematic: you are doing so many unnecessary multiplications and divisions... Instead, you should just be counting the number of darts, i.e. incrementing a counter. Your slave should just be returning an integer. Let R add all these integers together and do a single division by num_simulations at the end.

To summarize 1, 2, and 3, it would be great (if possible) if you could just tell your slave: here is your seed number n; now throw x darts and tell me how many ended up in the circle.

4) Now looking at your R code. Yes, the use of <<- in your code is not very elegant. That's because you are trying to use clusterEvalQ which may not be the best option from the snow package. Instead, clusterApply or clusterMap are better suited for functional programming. Your code could look like this, I let you figure out the rest:

FSnowPi <- function(num_simulations, seed_num = 123456L) {
  retvals <- .Fortran("snowpi",
                      num_inside      = 1L,  # an integer
                      num_simulations = as.integer(num_simulations),
                      seed_num = as.integer(seed_num))
  return(retvals$num_inside)
}

SnowPi  <- function(num_simulations, num_procs) {
  # input checks
  stopifnot(is.integer(num_simulations),
            is.integer(num_procs),
            num_simulations > 0L,
            num_procs > 0L)
  # initialize cluster
  cl <- snow::makeCluster(num_procs, type = "MPI")
  # balance the number of simulations per node
  node_num_simu <- balance_evenly(num_simulations, num_procs)
  # compute random seeds
  node_seeds <- sample.int(1e6, num_procs)   # please review...
  # run in parallel
  num_inside <- snow::clusterMap(cl, MyPi::FSnowPi, node_num_simu, node_seeds)
  # close the cluster
  snow::stopCluster(cl)

  pi_estimate <- 4 * Reduce(`+`, num_inside) / num_simulations
  return(pi_estimate)
}

balance_evenly <- function(total, among) {
   min_load <- floor(total / among)
   max_load <- min_load + 1L
   rest <- total - min_load * among
   load <- c(rep(max_load, rest),
             rep(min_load, among - rest))
   return(load)
}

I hope some of it is helpful. Please let me know. And thanks for sharing your Fortran code; I know at least one other R package that uses it:  fields whose rdist() function for computing euclidean distances is extremely fast. I want to give a try one day.


Multi threading with webrequests/responses

You say you suck at class design but there's only one class in your code and everything is very "linear". I'm no expert anyway, but I'll try to help.

First of all you should separate the Main() function from the code you're executing (unlesss the code is short), this will improve readbility at it will be easier to update the code. To do this you can create a class where the main work will happen.

On the Main() function:

serverUrl = Console.ReadLine();

If you have many variables it might be better to declare this at the start of the function, but it isn't always necessary. In my opinion on the top you should put the variables that will be used many times or that are important.

while (fileName != "start");

I would do this with an if but this works fine. What I would also do is to save all the inputs in a list, either a List<> or a string[].
Also you're doing the "start" checking twice, one on the loop, and one on the code inside the loop.

It's simpler like this:

List<string> fileNames = new List<string>();
while (currentLine != "start")
    fileNames.Add(currentLine);

After this you iterate thorugh the items 2 times, I will go on that later.

Now we can create a class that does the "heavy work". Let's ask ourselves: what do we want this class to do? And what does it need to do that?

Well, now you have the class functions and its params.
We want the class to send data on, it needs the "XML file path", and we want to do it on a  thread.

 class TestClass
{
    private string xmlPath;
    public TestClass(string _xmlPath)
    {
        xmlPath = _xmlPath;
    }
    public void SendDataAsync(object data)
    {

    }
    public void SendData(object data)
    {

    }
}

We create a local class variable that's asked when we create the class and that will be accesed later: xmlPath.

Sometimes, using Threads it's nasty and can cause problems and performance issues (if using many of them, so I like using Tasks. This is what will be happening on the SendDataAsyncFunction:

 public void SendDataAsync(object data)
        => Task.Run(() => SendData(data));

If we only have one line of code using => makes it simpler than using brackets.

Then on the SendData function:

On the first line we see a try block, then is it really necessary? What could throw an exception?
Things that could throw and exception are File.ReadAllBytes , request.Write and the response, in this case it's ok to have a try block on the whole function, but normally you shouldn't do that.

 System.Net.ServicePointManager.DefaultConnectionLimit = 10000;

Is it necessary to do this every time? Why not take this to the main function? Since it's only executed once.

Then the bytes are read, to reduce code lines we can do this:

 byte[] bytes = File.ReadAllBytes(xmlPath);

Next the HttpResquest is created, if we take this to another function (ideally each function should do only 1 thing), the code will be easier to read and if something has to be change less problems will occur.

 private HttpWebRequest CreateRequest(int length)
    {
        WebRequest request = WebRequest.Create(ATMSimulator.Properties.Settings.Default.KTHBaseUri);
        request.ContentType = "text/xml; encoding='utf-8'";
        request.ContentLength = length;
        request.Method = "POST";
        return (HttpWebRequest)request;
    }

We take the cast to the end of the function, since it's not necessary to do it earlier.

Then we want to write the request. If you use using the stream will be closed itelf. We can change the code to this:

using (Stream requestStream = request.GetRequestStream())
            requestStream.Write(bytes, 0, bytes.Length);

Then the function receives the response, we can take that to a different function too, like this:

 private string ReceiveResponse(HttpWebRequest request)
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
    }

In this function we send Data and then we get the response, so the mame must be changed to something like SendDataAndGetResponse.

Now we go back to the top, and we see that we change some things that we had written before, like instead of using a string[] we can use a List of the class itelf.(I'm tired from explaining everything, so I just post the final code here):

   using System;
   using System.Collections.Generic;
   using System.IO;
   using System.Net;
   using System.Threading.Tasks;

    namespace test
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 10000;
            string serverURL;
            List<TestClass> fileNames = new List<TestClass>();

            Console.WriteLine("Please enter the URL to send the XML File");
            serverURL = Console.ReadLine();

            string currentLine = "";
            while (currentLine != "start")
                fileNames.Add(new TestClass(currentLine));
            foreach (TestClass tClass in fileNames)
                tClass.SendDataAndGetResponseAsync();
            Console.ReadLine();
        }
    }

    internal class TestClass
    {
        private string xmlPath;

        public TestClass(string _xmlPath)
        {
            xmlPath = _xmlPath;
        }

        public void SendDataAndGetResponseAsync()
            => new Task(SendDataAndGetResponse).Start();

        public void SendDataAndGetResponse()
        {
            try
            {
                ServicePointManager.DefaultConnectionLimit = 10000;
                byte[] bytes = File.ReadAllBytes(xmlPath);
                HttpWebRequest request = CreateRequest(bytes.Length);
                using (Stream requestStream = request.GetRequestStream())
                    requestStream.Write(bytes, 0, bytes.Length);
                Console.WriteLine(ReceiveResponse(request));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private HttpWebRequest CreateRequest(int length)
        {
            WebRequest request = WebRequest.Create(ATMSimulator.Properties.Settings.Default.KTHBaseUri);
            request.ContentType = "text/xml; encoding='utf-8'";
            request.ContentLength = length;
            request.Method = "POST";
            return (HttpWebRequest)request;
        }

           private string ReceiveResponse(HttpWebRequest request)
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                return new    StreamReader(response.GetResponseStream()).ReadToEnd();
            }
       }
   }

I hope this helps you :). I had some free time so I wrote the long answer.


The first number is included in the range but the last number is not. That inconsistency is odd. You should document the limitations you set to the input. If your limitations make documentation hard, it's a sign of bad programming.

Knowing what I wrote above, right now you to check for both equality and greater than between firstNumber and lastNumber. Just check if (firstNumber > lasNumber) instead and tell the user that "firstNumber must be smaller than lastNumber."

FirstNumber and lastNumber are not descriptive variable names. LowerLimit and upperLimit would be better.

You're not prepared for negative input.

Using firstNumber as both the lower limit and loop counter makes the variable name to be incorrect in both uses. It's really never the lowerLimit nor the number being checked. Add a separate variable and use a loop for (int candidate = lowerLimit; candidate <= upperLimit; candidate++) { ...

You should separate the algorithm from main method that reads the input to a static utility method that operates on integers. Reading code that is nested four deep is difficult.


Split a list into equal parts that using LINQ in a way that has good performance

We can make the method more generic:

public static IEnumerable<IEnumerable<T>> Split<T>(IEnumerable<T> source, int chunkSize)
{

Then we can store the current chunk in a List<T>. Using the constructor that takes the initial capacity should be good for performance:

    var chunk = new List<T>(chunkSize);
    foreach (var item in source)
    {
        chunk.Add(item);
        if (chunk.Count == chunkSize)
        {
            yield return chunk;
            chunk.Clear();
        }
    }

Finally we need to return the final (non-empty) chunk

    if (chunk.Count > 0)
    {
        yield return chunk;
    }
}

Depending on your use case, you might want to make a copy of the list and yield return chunk.ToList() instead.


It should also be fine in earlier versions of .NET as you are not using any 4.5 specific classes or language features.

The reset is fine as the assignment is atomic as you mentioned, however if you were using a long then you would want to use Interlocked.Exchange because the assignment of a 64bit number is not atomic on a 32bit operating system (as it is stored as 2 32bit values).

The only changes I would suggest are purely from a coding standards perspective:

// seal the class as it's not designed to be inherited from.
public sealed class Counter
{
    // use a meaningful name, 'i' by convention should only be used in a for loop.
    private int current = 0;

    // update the method name to imply that it returns something.
    public int NextValue()
    {
        // prefix fields with 'this'
        return Interlocked.Increment(ref this.current);
    }

    public void Reset()
    {
        this.current = 0;
    }
}


Let me look at this...first you include the headers, good.

void main (void)
{
    /* snip */
}

Well, for C it's standard to call int main(int argc, char** argv) to facilitate arguments, or if there are no arguments just int main().

This is minor style compaint, not a major problem.

Examining your main function's contents:

    int x,y,m;
    for(x=0;x>=0;x++){
        m=scanf("%d %d",&x,&y); /* NOTE THIS LINE!!! */
        if (m!=2 || m==EOF){
            break;
        }
        else printf("/%d/%d/\n",x,y);
    }

1. This scanf uses STDIN for input, i.e., the user will enter stuff from the command line. Is this what you desire?

I don't think EOF would be entered by the user...

Perhaps you meant fscanf to scan a file for input?

2. So if I enter -9 3 I should expect this for-loop to terminate. Is this the desired behaviour?

On the /* NOTE THIS LINE!!! bit of code, I am suspicious about using sanf(...,&x,...). Again, perhaps this is desired, I don't know.

3. You should also be consistent with the use of brackets for single lines, writing if (...) break; instead. Or change the else to include brackets. But don't include brackets for one, then forget them for the other.

    if (feof ( stdin )){
        printf("End of input\n");
    }
    else if(m!=2){
        printf("There was an error\n");
    }
    getch();
}

4. These lines could be tucked into the for-loop.

5. Avoid using getch() since it's deprecated. If you're just waiting for the user to hit some key to continue, use getchar().

You could have condensed the main function to be:

int main() {
    int m,x,y;
    for(x=0; x>=0; x++) {
        m=scanf("%d %d",&x,&y);
        if (m!=2) { /* note multiple lines always trapped between brackets */
            printf("There was an error!\nHit any key to continue...\n");
            getchar();
            return EXIT_FAILURE;
        } else if (m==EOF) {
            printf("End of input\n");
            break();
        }
        else printf("/%d/%d/\n",x,y); /* single lines don't have brackets */
    }
    printf("Hit any key to continue...\n");
    getchar();
    return EXIT_SUCCESS;
}

The beauty of returning an int is you can have multiple different exit failures, e.g., -1 for bad input, -2 for some other problem, etc.

Addendum

After sleeping on it, I realized some additional style points for C.

A1. You should always initialize your variables! So instead of just writing int m,x,y; we should instead write:

    int m,x,y;
    x=0;
    y=0;
    m=0;

It's something people overlook in C programming.

A2. You could have written a while-loop instead of a for-loop, which may have been more elegant. For example:

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main() {
    int m,x,y;
    m = 0;
    x = 0;
    y = 0;
    while (x++ >= 0) {
        m=scanf("%d %d",&x,&y);
        if (m!=2) { /* note multiple lines always trapped between brackets */
            printf("There was an error!\nHit any key to continue...\n");
            getchar();
            exit(EXIT_FAILURE);
        } else if (m==EOF) break();
        else printf("/%d/%d/\n",x,y); /* single lines don't have brackets */
    }
    if (feof(stdin)) printf("End of input\n");
    printf("Hit any key to continue...\n");
    getchar();
    return EXIT_SUCCESS;
}

Note that we immediately terminate when there's an error, as is noted in the C Book in Chapter 1 and Chapter 10.

A3. Observe the only way to leave the while-loop is through (a) scanning an EOF, (b) scanning a "negative enough" number, or (c) through bad data. So we can notify the user of an error immediately, and exit (which is good form).

And the only remaining way to leave the loop is through (a) or (b). But it appears in the OP either case is acceptable, but only for (a) should we notify the user there's the end of input.

A4. Note upon exiting when encountering an error, it's good form to use exit(<error code>). You need stdlib.h to use exit(...) though.


Unqualified names from C headers

It appears that your <cstdint> happens to declare its identifiers in the global namespace as well as in std; this means that you weren't notified of the consistent misspelling of std::uint8_t, std::uint16_t and the like.

Interface

It's not clear why ExtractValue is visible at file scope (rather than being a private static method within NetworkData).

The get() methods ought to be declared const (and if you never implement set() methods, then perhaps _p should be a pointer-to-const).

Pass pointer to member rather than offsetof

The use of offsetof() and pointer arithmetic with std::uint8_t* (which should be char*, given that offsetof() works in units of char) is deeply disturbing.  One possibility is for NetworkData<T> to hold a private reference to the T, and accept pointer-to-member to indicate which value is desired:

#include <type_traits>
#include <utility>

// Get a field of the class T, in host byte order.
// The class T is wrapped in NetworkData class. The get() function
// takes the offset to the member as an argument, gets the address
// of field and extract the field
template <typename T>
class NetworkData
{
    const T& data;

public:
    NetworkData (void *data)
        : data(*reinterpret_cast<T*>(data))
    {
    }

    template<typename V>
    V get(V T::*field) const
    {
#if BIG_ENDIAN
        return data.*field;
#else
        return byte_swap(data.*field);
#endif
    }

private:
    template<typename V>
    static
    std::enable_if_t<std::is_integral_v<V> && std::is_signed_v<V>, V>
    byte_swap(V value)
    {
        // We manipulate using unsigned bitwise arithmetic.
        return reinterpret_cast<V>(byte_swap(reinterpret_cast<std::make_unsigned_t<V>>(value)));
    }

    template<typename V>
    static
    std::enable_if_t<std::is_integral_v<V> && std::is_unsigned_v<V>, V>
    byte_swap(V value)
    {
        // We assume CHAR_BIT == 8 (so that sizeof gives us octets)
        static const V mask = 0xff;
        V result = 0;
        for (auto shift = 0u;  shift < 8 * sizeof value;  shift += 8)
            result = (result << 8) + ((value >> shift) & mask);
        return result;
    }

    // We could add overloads here to take advantage of processor-native byte swap instructions, as available.
};

We can then use it like this:

#include <cstdint>
struct Msg {
   std::uint32_t a;
   std::uint16_t b;
};

void process (std::uint8_t *p)
{
    NetworkData<Msg> h(p);

    auto a = h.get(&Msg::a);
    auto b = h.get(&Msg::b);
}

This eliminates the use of preprocessor macros, and makes a slightly more natural object-access syntax.

Consider modifying the structure members

If we're allowed to re-write Msg, we could make its members be network-endian values:

#include <cstdint>
struct Msg {
   NetworkEndian<std::uint32_t> a;
   NetworkEndian<std::uint16_t> b;
};

We can declare NetworkEndian like this:

template<typename Integer>
class NetworkEndian
{
    Integer value;

public:
    NetworkEndian(Integer value)
        : value(byte_swap(value))
    {}
    // default copy, assign, destructor

    operator Integer() const
    {
        return byte_swap(value);
    }

private:
    static Integer byte_swap(Integer v)
    {
        using Unsigned = std::make_unsigned_t<Integer>;
        Unsigned u = reinterpret_cast<Unsigned>(v);
        // Assume CHAR_BIT == 8 (so that sizeof gives us octets)
        static const Unsigned mask = 0xff;
        Unsigned result = 0;
        for (auto shift = 0u;  shift < 8 * sizeof u;  shift += 8)
            result = (result << 8) + ((u >> shift) & mask);
        return reinterpret_cast<Integer>(result);
    }
};

The conversion operators mean that we can now read the members in a completely natural manner:

void process(const Msg& message)
{
    auto a = message.a;
    auto b = message.b;
}

Not only that, but by providing a converting constructor, we also get to assign values equally naturally.


Determining if a pair exists in a large sorted array

\$O(1)\$ is impossible indeed. Your solution is \$O(n^2)\$, because you ignore the most important part of the question: the array is sorted.

The \$O(n)\$ solution is to set a pair of iterators to the beginning and the end of the array. Then if a sum of their values is less than target, advance the beginning; if it greater, retreat the end. Keep going until they meet (or a target is found).


How could I have made this Powershell script that executes robocopy code better

If you don't want an external csv file,
use an internal one - simulated with a here string and ConvertFrom-Csv
in a date format specifier upper case MM are for month, minutes are lower case mm
the following script has several variable names shorted to keep line length down.
the final command is only echoed / commented out.

## Q:\Test\2019\08\23\sf_226703.ps1
# sets the files to exclude
$defaultDirExclusionSet = '"$Recycle.Bin" "System Volume Information"'

#options for robocopy
$RoboOpts = "/MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD $defaultDirExclusionSet /NP /TEE"

# simulate external csv with a here string and ConvertFrom-Csv
$RCJobs = @'
desc,src,dst,log
"main fileshares","\\server1\D$\Shares","\\server2\D$","fileshare"
"Citrix User Store Shares","\\server1\D$\CitrixUserStore","\\server2\E$\CitrixUserStore","ctxusrshare"
"Citrix User Redir Shares","\\server1\D$\CitrixUserRedir","\\server2\E$\CitrixUserRedir","ctxusrredir"
'@ -split '\r?\n' | ConvertFrom-Csv

$RCJobs | Format-Table -Auto

##### launch all at once.  fix the first line before using.
foreach($J in $RCJobs){
    Write-Host -Fore Green "Starting job $($J.desc)"
    $Args = '"{0}" "{1}" {2} /log+:"C:\robocopylogs\{3}_{4:yyyy-MM-dd-HH-mm}.txt"' -f `
           $J.src,$J.dst,$RoboOpts,$J.log,(Get-Date)
    "Start-Process robocopy.exe -ArgumentList $Args"
    #Start-Process robocopy.exe -ArgumentList $Args
}

Sample output without executing RoboCopy.

> Q:\Test\2019\08\23\sf_226703.ps1

desc                     src                          dst                          log
----                     ---                          ---                          ---
main fileshares          \\server1\D$\Shares          \\server2\D$                 fileshare
Citrix User Store Shares \\server1\D$\CitrixUserStore \\server2\E$\CitrixUserStore ctxusrshare
Citrix User Redir Shares \\server1\D$\CitrixUserRedir \\server2\E$\CitrixUserRedir ctxusrredir

Starting job main fileshares
Start-Process robocopy.exe -ArgumentList "\\server1\D$\Shares" "\\server2\D$" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD "$Recycle.Bin" "System Volume Information" /NP /TEE /log+:"C:\robocopylogs\fileshare_2019-08-23-20-59.txt"
Starting job Citrix User Store Shares
Start-Process robocopy.exe -ArgumentList "\\server1\D$\CitrixUserStore" "\\server2\E$\CitrixUserStore" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD "$Recycle.Bin" "System Volume Information" /NP /TEE /log+:"C:\robocopylogs\ctxusrshare_2019-08-23-20-59.txt"
Starting job Citrix User Redir Shares
Start-Process robocopy.exe -ArgumentList "\\server1\D$\CitrixUserRedir" "\\server2\E$\CitrixUserRedir" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD "$Recycle.Bin" "System Volume Information" /NP /TEE /log+:"C:\robocopylogs\ctxusrredir_2019-08-23-20-59.txt"


Is the above code wasting space?

Yes. As @cHao pointed out in a comment, you are using \$O(N log N)\$ space. You can do mergesort in \$O(N)\$ space.

  Is there a better implementation?

Yes. The biggest problem wrt both time and space efficiency is that you are unnecessarily allocating and copying auxiliary arrays.

You can instead create 1 auxiliary array and pass the same array around together with the interval to be sorted, or merged.

Your methods would look like these, some implementation left exercise :

public static void mergeSort(int[] arr) {
    mergeSortBetween(arr, new int[arr.length], 0, arr.length -1);
}

private static void mergeSortBetween(int[] arr, int[] aux,
    int startIndex, int endIndex) {
    if (...) {
        return;
    }
    //...
    mergeSortBetween(arr, aux, startIndexLeft, endIndexLeft);
    mergeSortBetween(arr, aux, startIndexRight, endIndexRight);
    merge(arr, aux,
        startIndexLeft, endIndexLeft,
        startIndexRight, endIndexRight);
}

private static void mergeBetween(int[] arr, int[] aux,
    int startIndexLeft, int endIndexLeft,
    int startIndexRight, int endIndexRight) {
    // only need to merge consecutive chunks
    assert startIndexRight = endIndexLeft + 1;
    //merge into aux
    while (currentLeft < startIndexLeft && currentRight < endIndexRight) {
        if (...)
            aux[...] = arr[...]
        else
            aux[...] = arr[...]
    }
    while (currentLeft < endIndexLeft) {
        aux[...] = arr[...]
    }
    while (currentRight < endIndexRight) {
        aux[...] = arr[...]
    }

    //copy merged values back into arr
    System.arraycopy(aux, ..., arr, ..., ...);
}


Shortening Script - Add new class/css to an li in setIntervals

One simple solution would be to extract your common functionality into a method. We'll also cache the selector for speed (don't do this if the elements change).

var tabs = $("ul.homepageTabs li");

function animateAfter(index,timeout){

    setTimeout(function () {
        tabs.eq(index).css("display", "inline-block");
        tabs.eq(index).addClass('animated fadeInDown');
    }, timeout);
}

Then we can call it like so:

for(var i=3;i<8;i++){
   animateAfter(i,2400+300*i);
}

I noticed the first two are intervals, was that a mistake? If it was, you can start the loop at 0 (and a smaller timeout). If it wasn't you can can create a similar function for intervals.

Also, consider using queued animations.

We want all our animations to occur 300 mili-seconds (after each other) right?

(function(){
    var i=3; //the start index

    function myAnimEffect(next){
        $(this).eq(i).css("display", "inline-block").
               eq(i).addClass('animated fadeInDown');
       next();
    }
    var $el = $('ul.homepageTabs li');
    $el.delay(1800);
    for(var j=0;j<5;j++){ //5 is the number of lis
        $el.queue(myAnimEffect).delay(300);
    }
});


There are problems with your readFile and writeFile functions.  These functions are asynchronous.  As such, the callbacks you pass to fs.writeFile() and to fs.readFile() are called some time in the future, long after fs.readFile() and fs.writeFile() have already returned and finished executing.

As such, the return value you have in those callbacks just returns back into the bowels of the file I/O sub-system and does not go back to any of your code.

So, as you have the code written, you have these problems:

There's no way for the code that calls readFile() or writefile() to know when either function has completed.
There's no way for the code that calls writeFile() to know when that function succeeded or failed.
There's no way for the code that calls readFile() to know if an error occured.

Your functions will need to accept either a completion callback or they will need to return a promise because that's how the caller gets completion and error information.

Then, once you've fixed the above issues, you'll find that you've hardly changed fs.readFile() and fs.writeFile() much at all.  Pretty much all you will have done is default the encoding to utf8 since everythning will be pretty much the same.  I'd have to say that this module doesn't really seem worth it.

You could use the native fs.readFile() like this:

    var fs = require("fs");

    app.get('/aa', function(req, res) {

        var filePath  = 'C://test.txt';
        fs.readFile(filePath, 'utf8', function(err, data) {
            if (err) {
                res.send(err);
            } else {
                console.log(data);
                res.send(data);
            }
        });

    });

So, this is pretty much the same amount of code as what you had, the main difference being that this version has full error handling whereas your version did not handle errors from fs.readFile() and the browser request was left permanently with no response upon error.

Creating modules to contain shared code is a generally good idea.  But, when working with async functions and their responses, you need to make sure you preserve full async response and error handling when you write cover functions that use async library functions.  In this case, you missed some of that, rendering your cover function not fully functional.

In addition, when covering a built-in function, you should pretty much make sure you're adding enough value to justify a new interface.  Simple defaulting one argument is probably not enough change/improvement to justify creating a whole new set of functions that someone learning or modifying your code would have to become familiar with in order to be productive in your code (which would not be an issue if you just used the standard functions).

Also, in this specific example, Express has res.sendFile() which will do all this work for you:

    app.get('/aa', function(req, res) {
        res.sendFile('C://test.txt', function(err) {
            if (err) {
                res.status(err.status).end();
            }
        });
    });


Swift permutations of the digits of an Integer

My main point of criticism is that the code uses a global variable to share data between the main function and the auxiliary function. That is problematic for various reasons:

The variable must be reset before the function can be called again.
The variable can be modified from outside of your function, causing
wrong results.
The function is not thread-safe.

Example:

print(permsOfInteger(12)) // [[12], [21]]
print(permsOfInteger(12)) // [[12], [21], [12], [21]]

So

var outputArray = [[Int]]()

should be a local variable of func permsOfInteger(). You can then pass it as an “inout argument” to the helper function func perms(), or make that helper function a nested function of the main function:

func permsOfInteger(_ input: Int) -> [[Int]] {

    var outputArray = [[Int]]()

    func perms (_ input: [Int], _ output: [Int]) {
        // ... adds something to `outputArray` ...
    }

    // ...
    perms(inpArray, [])
    return (outputArray)
}

Why is the return type a nested array where each “integer permutation” is wrapped into a single-element array? Returning a simple array of integers seems more natural to me, and would be more efficient:

func permsOfInteger(_ input: Int) -> [Int] {
    // ...
}

print(permsOfInteger(12)) // [12, 21]

As @janos already said, combining the digits to an integer should be done in “pure maths” instead of using string operations. This can be done with reduce(), for example:

let digits = [1, 2, 3]
let number = digits.reduce(0, { $0 * 10 + $1 })
print(number) // 123

An [UInt8] array would be sufficient to store the decimal digits and save some memory. Here is a possible implementation as a computed property and custom initializer of the Int type:

extension Int {
    var decimalDigits: [UInt8] {
        precondition(self >= 0, "Value must not be negative")
        var digits = [UInt8]()
        var n = self
        while n > 0 {
            digits.append(UInt8(n % 10))
            n /= 10
        }
        return digits
    }

    init(decimalDigits: [UInt8]) {
        self = decimalDigits.reduce(0, { $0 * 10 + Int($1) })
    }
}

The slicing

let before = Array(input[0..<i])
let after = Array(input[(i + 1) ..< input.count])

can be slightly shorted with partial ranges:

let before = Array(input[..<i])
let after = Array(input[(i + 1)...])

An alternative would be to remove the current element from the input array:

var remaining = input
let current = [remaining.remove(at: i)]
perms(remaining, current + output)

Instead of if input.count == 0 you can test if input.isEmpty – it does not make a difference for arrays, but can be more efficient for arbitrary collections, where determining the count requires a traversal of the entire collection.

For the same reason you might want to replace

for i in 0..<input.count { ... }

by

for i in input.indices { ... }

since collection indices are not always zero based.

Finally, I would suggest some more descriptive variable names and argument names. Putting it all together, the function could look like this:

func permutations(of number: Int) -> [Int] {

    var permutations = [Int]()

    func addPermutations(of digits: [UInt8], withSuffix suffix: [UInt8]) {
        if digits.isEmpty {
            permutations.append( Int(decimalDigits: suffix) )
        } else {
            for i in digits.indices {
                var remainingDigits = digits
                let currentDigit = [remainingDigits.remove(at: i)]
                addPermutations(of: remainingDigits, withSuffix: currentDigit + suffix)
            }
        }
    }

    addPermutations(of: number.decimalDigits, withSuffix: [])
    return (permutations)
}

print(permutations(of: 123))
// [123, 213, 132, 312, 231, 321]


Expanding url from shortened url obtained from tweet

Couple things I'd try:

switch to requests module reusing the requests.Session() to let it reuse the same TCP connection:

  ..if you're making several requests to the same host, the underlying TCP
  connection will be reused, which can result in a significant
  performance increase

use the "HEAD" HTTP method (in case of requests you may need the allow_redirects=True)
try out Scrapy web-scraping framework which is of an asynchronous nature and is based on the twisted network library. You would also move the CSV output part to an output pipeline.
another thing to try is use the grequests library (requests on gevent)

Some micro-optimization ideas:

move the hdr dictionary definition to the module level to avoid redefining it every time urlResolution() is called (and, since it is a constant use upper-case; and pick a more readable variable name - HEADERS?)


Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files.
Word array "percent" literals
Ruby has special array literals for arrays of single-word strings that can make your code easier to read by reducing the amount of "syntax fluff" around the actual content.
The literal starts with the sigils %w or %W (think "word" or "witespace-separated"). %w behaves like a single-quoted string, i.e. does not perform interpolation and supports no escape characters other than \' and \\. %W behaves like a double-quoted string.
So, the beginning of your script could look like this:
# frozen_string_literal: true

## SAMPLE VARIANTS
sizes = %w[small medium large]
colors = %w[red green blue]
materials = %w[cotton linen]

As with all percent literals, you can freely choose the delimiter you want to use such that the delimiter does not occur inside the literal. For example, you can use | as the delimiter, ,, @ anything you want:
sizes = %w@small medium large@
colors = %w@red green blue@
materials = %w@cotton linen@

The first character after the w determines the delimiter. Delimiters come in two variants: paired and unpaired. With an unpaired delimiter, the same character ends the literal, as in the second example. With a paired delimiter, the corresponding closing delimiter ends the literal, e.g. when you start with <, you close with >, etc. See the first example.
Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style improvements I pointed out above, and also was able to autocorrect all of the ones I listed.
I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".
Here's what the result of the auto-fix looks like:
# frozen_string_literal: true

## SAMPLE VARIANTS
sizes = %w[small medium large]
colors = %w[red green blue]
materials = %w[cotton linen]

## ITERATE TO ALL VARIANTS
titles = []
sizes.each do |size|
  colors.each do |color|
    materials.each do |material|
      ## PUT THE VARIANT IN THE NEW ARRAY
      titles.push("#{size} - #{color} - #{material}")
    end
  end
end

puts titles.inspect

puts foo.inspect
Kernel#p is the preferred debugging method. It does the same thing, but is more idiomatic, and is specifically designed for quick debugging (hence the one-character name).
So, the last line can simply be
p titles

Also, Kernel#puts returns nil, but Kernel#p returns its argument(s), so you can quickly chuck it into a long chain of expressions without changing the result.
Vertical whitespace
Your code could use some vertical whitespace to give the code more room to breathe. I would suggest at least separating the initialization at the beginning of the loop:
titles = []

sizes.each do |size|
  colors.each do |color|
    materials.each do |material|
      ## PUT THE VARIANT IN THE NEW ARRAY
      titles.push("#{size} - #{color} - #{material}")
    end
  end
end

The "shovel" operator <<
Array#push is not idiomatic. More precisely, it is only idiomatic if you are using the array as a stack, then you would use Array#push and Array#pop, since those are the standard names for the stack operations.
The idiomatic way of appending something to something else is the shovel operator, in this case Array#<<, so that should be
titles << "#{size} - #{color} - #{material}"

Iterators
In Ruby, it is idiomatic to use high-level iterators. In your code, you are already using iterators instead of loops, so that is good. However, each is really the lowest-level of all the iterators. It is essentially equivalent to a FOREACH-OF loop. It has no higher-level semantics, and it relies on mutation and side-effects.
Whenever you have the pattern of "Initialize a result, loop over a collection appending to the result, return result", that is a fold. There are two implementations of fold in the Ruby core library, inject and each_with_object. inject is the more functional one, each_with_object is the more imperative one. So, for now, we will use each_with_object here, since the code is still pretty imperative, and that makes the relationship between the old and new code more clear.
As a general transformation,
accumulator = some_initial_value

collection.each do |element|
  accumulator = do_something_with(accumulator, element)
end

becomes
accumulator = collection.inject(some_initial_value) do |accumulator, element|
  do_something_with(accumulator, element)
end

or
collection.each_with_object(some_initial_value) do |element, accumulator|
  do_something_with(accumulator, element)
end

In your case, it would look like this:
titles = []

sizes.each do |size|
  colors.each do |color|
    materials.each do |material|
      ## PUT THE VARIANT IN THE NEW ARRAY
      titles << "#{size} - #{color} - #{material}"
    end
  end
end

becomes
titles = []

sizes.each_with_object(titles) do |size, titles|
  colors.each_with_object(titles) do |color, titles|
    materials.each_with_object(titles) do |material, titles|
      ## PUT THE VARIANT IN THE NEW ARRAY
      titles << "#{size} - #{color} - #{material}"
    end
  end
end

Granted, this doesn't buy us much, actually the opposite. It starts to look slightly different though, when we move to a purely functional version without side-effects and mutation using Enumerable#inject:
titles = sizes.inject([]) do |acc, size|
  colors.inject(acc) do |acc, color|
    materials.inject(acc) do |acc, material|
      ## PUT THE VARIANT IN THE NEW ARRAY
      acc + ["#{size} - #{color} - #{material}"]
    end
  end
end

Linter, revisited
Rubocop actually complains about my use of shadowing the outer acc with the inner acc.
I disagree. You should not be afraid to disable or re-configure rules in your linter to fit your style.
However, note that programming is a team sport. If you are modifying code, adopt the existing style. If you are part of a team, adopt the team's style. If you write open source code, adopt the project's style. If you start your own project, adopt the community's style (do not create your own style for your project, until your project is big and successful enough to have its own independent community).
Excursion: Generality of fold (inject / each_with_object)
When I wrote above that you can rewrite this iteration with inject or each_with_object, that was actually a tautological statement. I didn't even have to read the code to make this statement.
It turns out that fold is "general". Every iteration over a collection can be expressed using fold. This means, if we were to delete every method from Enumerable, except inject, then we could re-implement the entire Enumerable module again, using nothing but inject. As long as we have inject, we can do anything.
Iterators, take 2
So, what we did until now was replace the low-level iterator with a higher-level iterator.
However, we are still not done. What we are now doing is we take each three elements from our three collections, concatenating them, and putting it into a new collection. So, really, what we are doing is transforming each element (or triple of elements), or "mapping" each element to a new element.
This is called map and is also available in Ruby as Enumerable#map.
So, finally, our code looks like this:
titles = sizes.map do |size|
  colors.map do |color|
    materials.map do | material|
      "#{size} - #{color} - #{material}"
    end
  end
end

This result is actually not quite right: we get a triply-nested array, because we have a triply-nested Enumerable#map.
We could Array#flatten the result, but there is a better way: Enumerable#flat_map:
titles = sizes.flat_map do |size|
  colors.flat_map do |color|
    materials.map do | material|
      "#{size} - #{color} - #{material}"
    end
  end
end

What we did here, was to replace the general high-level iterator fold (which can do anything) with a more restricted, more specialized high-level iterator map. By using a more specialized iterator, we are able to better convey our semantics to the reader. Instead of thinking "Okay, so here we have an accumulator, and an element, and we do something with the element, and then append it to the accumulator … ah, I see, we are transforming each element", the reader just sees map and instantly knows that map transforms the elements.
Array methods
There is not much we can improve in the code by using iterators. However, there are many more methods in both the Enumerable mixin and the Array class.
So, let's take a step back and think about what we are actually doing here: we are constructing the Cartesian Product of the three arrays. And perhaps not surprisingly, there already is a method that computes a product of arrays, creatively named Array#product:
titles = sizes.product(colors, materials).map do |size, color, material|
  "#{size} - #{color} - #{material}"
end

Array#join
As a last improvement, let's look at what the block is doing: it is "joining" the three variants together. And again, there is already a method which does that: Array#join:
titles = sizes.product(colors, materials).map do |variant|
  variant.join(' - ')
end

Final result
So, in the end, the entire thing looks something like this:
# frozen_string_literal: true

## SAMPLE VARIANTS
sizes = %w[small medium large]
colors = %w[red green blue]
materials = %w[cotton linen]

titles = sizes.product(colors, materials).map do |variant|
  variant.join(' - ')
end

p titles

Which I think is some nice-looking, easy to read, easy to understand code.


Create dictionary with default immutable keys

When reading the title of the question, I wondered: "Why use a dict subclass when a regular class with __slots__ can do?". And judging by the interface, it seems that it may fit.

Slots defines attributes names that are reserved for the use as attributes for the instances of the class. However, no more attributes can be added to the instances when defining __slots__ on the class:

>>> class Example:
...     __slots__ = ('a', 'b', 'c')
...
>>> e = Example()
>>> e.a = 3
>>> e.d = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no attribute 'd'
>>> e.a
3

However, __slots__ are not auto-populated and doing so at class level is prohibited:

>>> class Example:
...   __slots__ = ('a', 'b', 'c')
...   a = 3
...   b = 4
...   c = 5
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' in __slots__ conflicts with class variable

You can, however, still define them in __init__:

class Bones:
    __slots__ = (
        'between_hips',
        'bicep_right',
        'bicep_left',
        'arm_right',
        'arm_left',
        'thigh_right',
        'thigh_left',
        'leg_right',
        'leg_left',
        'spine_lower',
        'spine_upper',
    )

    def __init__(self, default_value=0):
        for attribute in self.__slots__:
            setattr(self, attribute, default_value)

Now the only thing left is to add a dictionary-like interface (and/or inherit from collections.abc.Mapping):

    def __getitem__(self, key):
        return getattr(self, key)

    def __setitem__(self, key, value):
        setattr(self, key, value)

    def __len__(self):
        return len(self.__slots__)

    def __iter__(self):
        return iter(self.__slots__)

    def items(self):
        for attribute in self.__slots__:
            yield attribute, getattr(self, attribute)

Or not necessarily, since you can still access the __slots__ as regular attributes, it all depend on your use case.

Note that with this implementation, you can still delete values, which you try to prohibit in your original implementation:

>>> b = Bones()
>>> b.bicep_right
0
>>> b['arm_left'] = 6
>>> b.arm_left
6
>>> del b['leg_left']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delitem__
>>> del b.leg_left
>>> b.leg_left
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: leg_left

If you wish to prevent that, you need to define __delattr__ on your class as well:

    def __delattr__(self, key):
        raise AttributeError(key)


I think the main improvement to this code would be to separate the definition of the premium lookup table from the logic that finds the premium for a given benefit and age, for example, using an Object-Oriented design.  Doing so will simplify changes to the table and make the code easier to test and debug.

For example, consider the usage below that makes the table itself an object mapping benefit and age ranges to premium values:

var premiumTable = new PremiumTable({
  '[50000, 75000)': {  // 50k <= benefit < 75k
    '     30)':  2.00, //          age <  30
    '[30, 40)':  2.50, //    30 <= age <= 40
    '[40, 50)':  5.00, //    40 <= age <= 50
    // ...
    '[75     ': 35.00, //    75 >= age
  },
  '[75000, 100000)': {
    // ...
  },
  // ...
});

var premium = premiumTable.valueForBenefitAndAge(someBenefit, someAge);

Now you can implement the valueForBenefitAndAge method in a way that can be unit tested and changes to the premium table are localized to the initializer object rather than being related directly to the code itself.

Moreover, the PremiumTable constructor function can validate the premium table input object based on rules that will be easier to encode than using your example code.  Additionally, the table could be loaded as a separate resource to further isolate the code that applies the logic from the premium table values themselves.


N-Queens without recursion (but with one goto)

Only problem is the goto. Can it be avoided without using a function?

Candidate goto replacement
    for (col = bq[row];;) {
        //NEXT_col: // Delete
        if (++col == N)
            bq[row--] = -1;
        else {
            for (rd = 1; rd <= row; rd++)
                if ((old = bq[row-rd]) == col || old == col+rd || old == col-rd)
                    // goto NEXT_col;  // Delete
                    break; //ADD
            if (rd <= row) continue; // ADD
            if (row == N - 1) {
                cnt++;
                row--;
                //pr_solution(bq, col);
            }
            else
                bq[row++] = col;
        }
        break;
    }

if (rd <= row) continue; takes advantage that for (col = bq[row];;) lacks a test and increment.

Is there a more convincing non-recursive version?

I'd re-write the loop (perhaps a state machine)  - need some time to think about it.

Later:
Code as written is quite tight.  A very nice simple non-recursive solution.
Yet (at the risk of the ire of OP) lacks clarity making it unnecessarily  difficult to optimize.
The style uses terse variable names like rd and bq which do not well convey their meaning.  It is as if short variable names make faster code (it does not).  init_board() does not initialize a board, but a single dimension of data.  Use more meaningful names.
Use of incomplete for loops like for (col = bq[row];;) seems like a code golf goal than a clearer col = bq[row]; while (1).
Helper functions like pr_solution() rely on the global N, which instead could be passed in, facilitating clearer function flow and allowing use with more than one size.
Local variable instantiation would help see their limited impact.
For clarity, use {} even for one-line blocks.
Consider rectangles, not only squares.  It adds clarity to code and offers other investigations for eventual optimization.
Some other ideas in code below too.
A first round cut:
int main(void) {
  for (int N = 1; N <= 8; N++) {
    const int ROW_N = N;
    const int COL_N = ROW_N;
    int queen_column[ROW_N];
    init_queen_column(ROW_N, queen_column, -1);
    long long count = 0;
    int parity[2] = { 0,0};
    int row = 0;
    while (row >= 0) {
      int col = queen_column[row];
      while (1) {
        if (++col == COL_N) {
          queen_column[row--] = -1;
        } else {
          int row_offset;
          for (row_offset = 1; row_offset <= row; row_offset++) {
            int old = queen_column[row - row_offset];
            int diff = old - col;
            if ((diff == 0) || diff == row_offset || diff == -row_offset) {
              break;
            }
          }
          if (row_offset <= row) { // From early break above
            continue; // ADD
          }
          if (row == ROW_N - 1) {
            count++;
            // print_solution(ROW_N, queen_column, col); // Print, then change state.
            row--;
          } else {
            parity[(row ^ col)&1]++; // Count parity for later optimization (stub code)
            queen_column[row++] = col;
          }
        }
        break;
      }
    }
    printf("%lld SOLUTIONS (%dx%d)\n", count, ROW_N, COL_N);
  }
  return 0;
}
1 SOLUTIONS (1x1)
0 SOLUTIONS (2x2)
0 SOLUTIONS (3x3)
2 SOLUTIONS (4x4)
10 SOLUTIONS (5x5)
4 SOLUTIONS (6x6)
40 SOLUTIONS (7x7)
92 SOLUTIONS (8x8)

Other idea to speed things up

Keep track of the count of queen placement on black (and/or white) squares.  Once that exceeds about half of N, time to unwind as subsequent forward iterations will all fail.

Look for patterns.  Example: Symmetry.  A solution that starts with the first queen on column 0 will have as many solutions as column N-1.  Looks like run time can be halved in some fashion.


I see a lot of if-else statements that could be improved upon.

Ones like these for example, are returning a boolean variable depending on an if-else statement with nothing else inside.

In those cases you can return boolean values directly.

  if(in_array($method, $this->unguarded, true)) {
      return true;
  }

into:

return (in_array($method, $this-unguarded, true));

The following code does the same thing for both 'cases', meaning that no matter what 'Request::ajax()' is, the same result will be given:

public function accessDenied() {
    if(Request::ajax()) {
        return Response::make('You cannot access this!', 403);
    }

    return Response::make('You cannot access this!', 403);
}

Which could simply be turned into:

public function accessDenied() {
    return Response::make('You cannot access this!', 403);
}

Your usage of the following code really bothers me, and I believe it could do with refactoring:

return strtolower(
        substr(
            $controller,
            strrpos($controller, '\\'),
            - 10 // 'controller' word
        ) . '.' . $method
    );


Python Search file for string and read into list

You could use the with..as construct to not worry anymore about closing the file.

Also iterating over the file and reading in the data can be simplified.

Also, you should not shadow the reserved name file.

menu_name and dotted seem not to be used atm.

Implementing these changes I get the following code:

def print_emp():
    # menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LOOKUP"
    # dotted = (OFFSET+len(menu_name))*'-'
    search_name = input('Give me an employee to search for: ')
    try:
        with open('employees.txt') as employees:
            for line in employees:
                if not line:
                    continue
                first_name, last_name, rate, hours = line.split()
                name = "{} {}".format(first_name, last_name)
                rate, hours = map(float, (rate, hours))
                if name == search_name:
                    print("{} ${:4.2f}".format(name, rate*hours))
                    break
            else:  # Will be triggered if the loop was not interrupted with break
                print('Employee is not listed')
    except FileNotFoundError:
        print("Error: File not found.")

Now, you could actually separate the concerns here. Write a function that reads all employees, another that finds a name in all employees and a third that prints it. This can be efficiently implemented using classes. I would probably also not fail and continue if the file is missing:

class Employee:
    def __init__(self, name, rate, hours):
        self.name = name
        self.rate = rate
        self.hours = hours

    def __repr__(self):
        return "name: {}, ${:4.2f}/hour, {} hours".format(self.name, self.rate, self.hours)

    def __str__(self):
        return "{} ${:4.2f}".format(self.name, self.rate*self.hours)

def read_employees(file_name):
    employees = {}
    with open(file_name) as employees:
        for line in employees:
            *name, rate, hours = line.split()
            name = "{} {}".format(name)
            rate, hours = map(float, [rate, hours])
            if name in employees:
                raise ValueError("Employee with name {} already exists!".format(name))
            employees[name] = Employee(name, rate, hours)
    return employees

if __name__ == "__main__":
    employees = read_employees('employees.txt')
    name = input('Give me an employee to search for: ')
    print(employees[name])

This code will raise a KeyError if the name does not exist, To prevent this you can use this:

if __name__ == "__main__":
    employees = read_employees('employees.txt')
    name = input('Give me an employee to search for: ')
    try:
        print(employees[name])
    except KeyError:
        print('Employee is not listed')

Or even this to keep on asking until a valid name is given:

if __name__ == "__main__":
    employees = read_employees('employees.txt')
    name = input('Give me an employee to search for: ')
    while name not in employees:
        print('Employee is not listed, try again')
        name = input('Give me an employee to search for: ')
    print(employees[name])

This more modular design allows you now to easily implement a write_employees(employees, file_name) function to write the dict back to a file, delete employees (del employees[to_delete]), modify them (employees[name].rate = 10), etc.


Use input redirection instead of cat | ...

Instead of cat somefile | somecommand, you should use input redirection, for example:

xgengen bash < Samples/template_bash_CMakeLists.txt | bash - > CMakeLists.txt

The advantage of this is that you're running one fewer process (no more cat).

Use modern style command substitution $(...)

Don't use old style `...` command substitution.
Use the modern and better $(...) style.

Simplify sed + awk pipelines when possible

This looks very complicated, and it's suspicious to have both sed and awk in the same pipeline:

echo $_class | sed -e 's/\([A-Z]\)/_\1/g' | awk '{printf toupper($0)} END{printf "_H_";}'

You can simplify using a single awk command:

echo $_class | awk '{gsub("[A-Z]", "_\&"); printf toupper($0) "_H_"}'

Use here-strings instead of echo | ...

Similar to using input redirection instead of cat | ...,
in Bash it's better to replace echo | ... with here-strings using <<<,
rewriting the above example as:

awk '{gsub("[A-Z]", "_\&"); printf toupper($0) "_H_"}' <<< $_class

Use alternative regex pattern separator to improve readability

When a regular expression pattern contains /,
using such patterns with the s/// operator becomes tedious and hard to read,
because of the escapes.
To improve readability, it's often good to use an alternative pattern separator.
So for example instead of this:

sed 's/\.\//  /'

You can do this instead to avoid escaping /:

sed 's|\./|  |'

The benefit is more obvious when you have multiple / in the pattern.
In this example the difference might be negligible.

Simplify regex

The s/// here can be simplified:

sed -e 's/\(.*\)/#include \"\.\.\/\1\"/g'

To this:

sed -e 's/.*/#include "..\/&"/'

That is:

No need to capture .* in \(...\), you can access the matched string directly with &
No need to escape . in replacement, as it has no special meaning there
No need to escape " within single-quoted strings in Bash
Since the pattern matches the entire line, no need for the g flag


Your code doesn't compile cleanly with GCC:
move.c: In function 'memCopy':
move.c:16:15: warning: comparison of distinct pointer types lacks a cast
     while (a2 < end)
               ^

Also 2 brief points:

Why reinvent the wheel? Most implementations of memcpy, memmove etc in the standard libraries will be correctly and efficiently implemented, in many cases not using pure C.
Your code assumes that both source and data are correctly aligned to be accessed as double. If they are not, depending on the platform the code may a) perform badly, b) give incorrect results or c) simply crash, unless I'm much mistaken. It happens to run (apparently correctly) on my PC, but that's no guarantee of portability.

The FreeBSD implementation shows how this can be done, assuming that that the mapping of pointers to uintptr_t gives values which can be masked appropriately - this is true of the relevant targets of the code, but may not be universally so.