Find all occurrences of all permutations of a shorter string within a longer string

Whitespace, variable extraction, etc.

function permutationsInString(longString, shortString) {
  let hash = {}; // let hash store the resulting found permutation strings and their respective index in the long string
  let permutations_shortStrings = permutationArr(shortString) ; // permute the short string and store the values in an array called permutations_shortStrings
  for(let i = 0 ; i < permutations_shortStrings.length ; i++) { // iterate through the array of permutations to check if the long string contains any of the values
    if(longString.indexOf(permutations_shortStrings[i]) !== -1)  // need to check for -1 as it indicates the substring cannot be found
      hash[longString.indexOf(permutations_shortStrings[i])] = permutations_shortStrings[i];
    }

    return hash ;

}

What happened to the indentation? Why do some ; have a space before them and others not? Why the blank line before the closing }?

permutations_shortStrings[i] is a mouthful. Extracting a local variable with a short intelligible name would improve readability.

longString.indexOf(permutations_shortStrings[i]) is not only a bigger mouthful but also potentially very expensive. A common subexpression which takes non-constant time should definitely be extracted to a local variable.

The comments are largely noise. The only one which contributes to my understanding of the code is the one saying what hash is supposed to contain.

Bug

      permutations.push(arr.join().replace(/,/g, ''));

What output should I expect if I call permutationsArr(",;")? What do I actually get?

This bug can be fixed, and performance improved, as:

      permutations.push(arr.join(""));

Algorithm

  My solution is Naive and Brute Force, was wondering if there are any other possible ways to reduce the time and space complexity.

There most certainly are.

Step back to a simpler task: given strings a and b which are guaranteed to be of the same length, is a a permutation of b? Write a solution which doesn't calculate any permutations. Hint:

   Count the number of times each character occurs

Now apply that to your search problem. Consider longString.substring(0, shortString.length): is it a permutation of shortString? Now consider advancing one character through longString: you remove longString.charAt(i) and add longString.charAt(shortString.length + i). How can you update the data structures used to test whether it's a permutation of shortString in constant time? Hint:

   In addition to counts of the characters, you might find it useful to have a count of the number of characters for which the difference is non-zero.

More sophisticated approaches (modelled on e.g. KMP) can allow you to skip more than one character at a time, but the one I've outlined already gets you down to linear time (subject to certain assumptions) so beyond that it's just a case of improving the constant factor.


Implementation of the Access version DBLookup() in VB6

In addition to @RubberDuck's excellent input (which I completely agree with), I have the following concerns:
Global Connection

Take note that the Database connection object cn is only valid for a single query

Nope, that's not how ADODB.Connection works. The reality here is that you have a function that consumes a connection that it doesn't own, encapsulated by an object that is global. Why isn't dbConn a function that returns the initialized connection? And if it initializes a connection, then why isn't it called InitializeConnection or GetConnection? And if cn is "only valid for a signle query", then why would it ever need to be visible to anything other than the procedure that needs an opened connection?
You're closing the recordset, but not the connection: if dbConn starts by closing the previous connection before opening a new one, this means you're leaving a database connection opened for much, much longer than you actually need to, and that's dirty. If dbConn doesn't do that, then your connection object simply falls in limbo, and that's outright wrong.

Call

Call dbConn
'Initiate Database connection object cn

That's an obsolete statement. This instruction is completely equivalent:
dbConn
'Initiate Database connection object cn

It doesn't look like a procedure call, only because of the poor naming of the dbconn procedure: if the name started with a verb...
InitializeConnection
'Initiate Database connection object cn

Why is that comment not on top of the instruction it's commenting?
'Initiate Database connection object cn
InitializeConnection

Now, if cn was local as it should be, that comment wouldn't even be needed, as the code would speak for itself:
Dim cn As ADODB.Connection
Set cn = InitializeConnection

As New
This is bad:

Dim rs As New ADODB.Recordset

Why? You might think that this:
Dim foo As New Collection

Is exactly the same as that:
Dim foo As Collection
Set foo = New Collection

But it will bite you. What does this code do?
Public Sub TestMe()
    Dim foo As New Collection
    foo.Add "bar"
    Set foo = Nothing
    foo.Add "surprise!"
End Sub

If you were expecting a Runtime error 91 - Object reference not set, you've been bitten. This blows up as expected:
Public Sub TestMe()
    Dim foo As Collection
    Set foo = New Collection
    foo.Add "bar"
    Set foo = Nothing
    foo.Add "surprise!" 'error 91
End Sub

Instead of running the query off the rs object with rs.Open, get a recordset instance from the connection with cn.Execute instead:
Set rs = cn.Execute(SQL)

Magic Return Values
Your function has several ways of "failing". A number of them involve an actual runtime error that the client code must handle. And if my German is correct, 3 of them involve returning a valid string that the client code must check (or treat as valid, and propagate to the UI?). Don't use your return value for that, raise proper errors: the client code should already be handling runtime errors, all you need to do is come up with a way of telling it exactly what went wrong.
An enum works great for that:
Public Enum DLookupError
    ErrNoRecordsReturned = vbObjectError + 42
    ErrMultipleRecordsReturned
End Enum

Now you can call Err.Raise DLookupError.ErrNoRecordsReturned, "DLookup", "Es ist ein Fehler in der Abfrage aufgetreten." to raise a runtime error that can be handled as such, effectively only ever returning an actual string result to your client code when there's such a result to return.
I left out the general "failure" error, since that's simply an error that you should bubble up to the caller.

Responsibilities
Code that's sprinkled with rs.Open calls all over the place, is code with poorly separated concerns. If your application needs to access a database, then you need an object whose responsibility is do to exactly that, so that the rest of the code can work at a higher abstraction level and not be bothered with connections and recordsets.
I've done exactly that in a previous life, and put everything up right here on Code Review, so you can see if you want something similar:

Materializing any ADODB Query
Creating ADODB Parameters on the fly

The entire function could be pretty much replaced with this (error-handling omitted):
Dim sql As String
sql = "SELECT " & fieldName & " FROM " & tableName & " WHERE " & predicate

Dim result As String
result = SqlCommand.QuickSelectSingleValue(sql)

Some other considerations

Parameters are implicitly passed ByRef; they can/should be passed ByVal instead.
Prefer camelCase for locals (I know VB6 isn't case-sensitive and that's a royal PITA at times); I'd go with fieldName, tableName and predicate.
You're not validating any of the parameters; an empty string is a valid condition resulting in invalid SQL. Granted that's handled by the error-handling there, but you could fail early and avoid sending malformed SQL to the database altogether.


Retrieving a substring from an exponentially growing string

The length of the string at level \$ K \$ is \$ 3 (2^K -1) \$, which means that for \$ K = 50 \$ a string with \$ 3377699720527869 \$ characters is (recursively) built. That is about 3 petabyte (if you count one byte per character) and won't fit into the memory of your computer.
On the other hand, only a small portion of that complete string is actually needed, because of the constraint \$ 1 \le end - start + 1 \le 100 \$. And in many cases, that substring is already contained in the string given by a previous, smaller level.
Therefore I would prefer a recursive algorithm: Check the given start and end indices for the positions of "X", "Y" and "Z" from the current level, and recurse to the preceding level for the portions between those positions.
Here is a possible implementation:
def substring(level, start_index, end_index):
    # Indices of "X", "Z", "Y" at the current level:
    low = 1
    high = 3 * (2 ** level - 1)
    mid = (low + high) // 2

    result = ""
    while start_index <= end_index:
        if start_index == low:
            result += "X"
            start_index += 1
        elif start_index < mid:
            e = min(end_index, mid - 1)
            result += substring(level - 1, start_index - low, e - low)
            start_index += e - start_index + 1
        elif start_index == mid:
            result += "Y"
            start_index += 1
        elif start_index < high:
            e = min(end_index, high - 1)
            result += substring(level - 1, start_index - mid, e - mid)
            start_index += e - start_index + 1
        else:
            result += "Z"
            start_index += 1

    return result

It computes
substring(50, 3377699720527869-200, 3377699720527869-100)

within fractions of a second.
Further improvements are possible, e.g. by noting that the string on level K starts with K "X" characters and ends with K "Z" characters, or by handling the first level separately.


Loading objects for users, roles, and groups from a query with LEFT OUTER JOINs

For the exact case you posted here, I would suggest to use group_concat() in the query. It will dramatically reduce the amount of code required, as well as the amount of data delivered from database.

Besides, I see a very little use for the prepared statement here, so the amount of code could be dramatically reduced on this account as well.

$sql = "SELECT u.id, u.firstName, u.lastName, u.email, u.phoneNumber,
    u.address, u.birthDate,group_concat(ur.roleName), roles group_concat(cg.name) groups
    FROM users as u
    LEFT OUTER JOIN user_role as ur ON u.id = ur.userId
    LEFT OUTER JOIN user_group as ug on ug.userId = u.id
    LEFT OUTER JOIN control_group as cg on cg.id = ug.groupId
    GROUP BY u.id";
$res = $mysqli->query($sql);
$users = array();
while ($row = $res->fetch_assoc()) {
    if ($row['id'] == $_SESSION["id"]) {
        continue;
    }
    $row['groups'] = explode(",", $row['groups']);
    $row['roles'] = explode(",", $row['roles']);
    $users[] = $row;
}

This is the response example which I consider most usable and clear.
But note it would take no trouble to make it exactly as in your example above, if you wish.

On a second thought, thinking one move ahead, I suppose you may wish to make groups and roles some sort of interactive - allowing clicks or other interactions with them. And for this purpose you will need group and roled IDs inevitably.

Therefore, to make this code robust and usable in the real life app, you have to supply group and role id as well. For this purpose I can't help it but use PDO, as its helper methods do A LOT of your job. For example, PDO::FETCH_KEY_PAIR gives you nice key-value pairs right out of SQL query:

$groups = $pdo->query("SELECT id, name FROM control_group")->fetchAll(PDO::FETCH_KEY_PAIR);
$roles  = $pdo->query("SELECT id, roleName FROM user_role")->fetchAll(PDO::FETCH_KEY_PAIR);

$sql = "SELECT u.id, u.firstName, u.lastName, u.email, u.phoneNumber,
    u.address, u.birthDate,group_concat(ur.roleName), roles group_concat(cg.name) groups
    FROM users as u
    LEFT OUTER JOIN user_role as ur ON u.id = ur.userId
    LEFT OUTER JOIN user_group as ug on ug.userId = u.id
    LEFT OUTER JOIN control_group as cg on cg.id = ug.groupId
    GROUP BY u.id";
$res = $pdo->query($sql);
$users = array();
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
    if ($row['id'] == $_SESSION["id"]) {
        continue;
    }

    $user_groups = array();
    foreach(explode(",", $row['groups'] as $id) {
        $user_groups[$id] = $groups[$id]
    }
    $row['groups'] = $user_groups;

    $user_roles = array();
    foreach(explode(",", $row['roles']) as $id) {
        $user_roles[$id] = $roles[$id]
    }

    $row['roles'] = $user_roles;
    $users[] = $row;
}

This is a response example.

As you can see, here we're first selecting all the group and role names, while in the main query selecting only ids. Then in the short loop finally creating groups and roles  arrays.


I see a few things I would do differently.  For one, I would not use a Queue.  At best, it's providing you an order in which floor buttons were pressed.  While the buttons may be pressed in any order, an elevator moves in sequential order be it up or down.

I would keep a simple List<bool> where true denotes a floor to stop at.  Once you stop at a floor, no need to Dequeue.  Instead just set the flag to false.  By keeping it simple, you won't have to jump through hoops if you are going up but someone presses buttons for 10, 5, 2, 9, 7.


Inheritance is by default private
class concreteObserver : ObserverInterface
                        ^^^^ Need public: here

Mark overriden methods:
void update(std::string message) // override ???

endl vs '\n'
Don't use endl unless you absolutely want to flush the buffer.
Probably OK here. Just wanted to note it.
Don't pass pointers:
    void subscribe(concreteObserver *subscriber)

Is subscriber every going to be NULL?
Do you need to check if subscriber has been destroyed?
Personally. I would pass by reference and document that a subject must live longer than the observers. Not that just because you pass by reference does not mean you can hold a pointer.
    void subscribe(concreteObserver& subscriber) // pass by reference
    {
        subscribers.push_back(&subscriber);      // but save pointer.
    }

But if you have a lot of dynamically allocated stuff this may not be suffecient. You could pass a std::weak_ptr then check of the subscriber is still available before sending the message.
Use the new foreach loop
        std::vector<concreteObserver*>::const_iterator itr = subscribers.begin();
        while (itr != subscribers.end())
        {
            (*itr)->update(message);
            ++itr;
        }

Easier to write as:
        for(auto& sub: subscribers) {
           sub->update(message);
        }


Looks good to me. The only thing I would change is

suffixes [] = [] : []

to

suffixes [] = [[]]

as it's a bit more readable.

When re-inventing functions, it can be instructive to look up their definition using Hoogle. Following the links, we find this definition in Data.List:

tails                   :: [a] -> [[a]]
tails xs                =  xs : case xs of
                                  []      -> []
                                  _ : xs' -> tails xs'


(defn palindrome? [items]
  "Efficient algorithm: loops through only (array-size/2)"
     ...
         (not= (nth items i)
               (nth items j))

nth is efficient on vectors and other things that support random indexing. On sequences, which you're passing in right now, it's O(n) per lookup since it has to walk the list.

Changing your test cases to use vectors should help (use mapv instead of map):

(let [...
      nums (mapv #(Integer/parseInt %) nums-temp)]

(def example (concat (range 1000) (reverse (range 1000))))
(count example)   ; 2000
(def examplev (vec example))
(count examplev)  ; 2000

(dotimes [_ 3] (time (palindrome? example)))
; "Elapsed time: 45.167334 msecs"
; "Elapsed time: 44.568282 msecs"
; "Elapsed time: 45.304136 msecs"

(dotimes [_ 3] (time (palindrome? examplev)))
; "Elapsed time: 0.317649 msecs"
; "Elapsed time: 0.272229 msecs"
; "Elapsed time: 0.30044 msecs"


Not safe at all, I'm afraid. Sure, you're calling PDO::prepare, to create a prepared statement, and that's all fine and dandy, but you are directly concatenating unsanitized user data into the string form which the query is prepared:

 $pid = $_GET['pid'];
 $sql = "SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id=$pid";

What if I were to pass any of the following values as "pid":

1 OR package_id > 0;
//or:
?

That would mean that, in the first case, you're executing the query:

SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id = 1 OR package_id > 0;
-- which translates to:
SELECT * FROM packages_to_be_shipped_on_bremail_address;

The second case is, in a way, even more subtle:

SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id = ?

This is a perfectly valid string to be passed to the PDO::prepare method. The ? is a placeholder for a value that will be bound later on in the code (at least, that's what PDO, and MySQL expects).
That means that your code will won't see anything wrong with the query, but once PDOStatement::execute is called, it'll throw an exception saying there is a problem. Something along the lines of "PDOStatement::execute expects one parameter, received null"
Just check the docs, and check the examples of how PDO::prepare should be used. What you're after should be:

$stmt = $pdo->prepare(
    'SELECT *
     FROM packages_to_be_shipped_on_bremail_address
     WHERE package_id = :pid'
);
$stmt->execute(
    array(
        ':pid' => $pid
    )
);
while($row = $stmt->fetch(PDO::FETCH_OBJ))//or FETCH_ASSOC
{
    echo 'Shipping Company - ', $row->shipcompany,
          '

Expected Delivery Date ', $row->deliverydate, '

';
}

Before you ask: Yes, those are comma's in the echo statement. echo is a language construct that works pretty similarly to C++'s std::COUT. You can push multiple values to it, separated by comma's.
The upshot is that PHP can then skip the string concatenation step, making the statement more efficient.
The downside? Well, there isn't one AFAIK.

Anyway: How does this produce safer queries? Well, that's easy: you send the query, without the user-supplied data to the server. MySQL can already compile and optimize the query. Often, MySQL will even be able to pre-fetch some of the data you need.
When you execute the query, and provide the data that makes up the WHERE clause (or other parts of your query), then MySQL can escape them properly, and since the query is already compiled, there's no real danger of the user supplied data being able to alter the query itself. This is just a short, very basic, and incomplete explanation of prepared statements. For more details: ask Google.

Other Niggles
There are some other issues that should be fixed, too:

$pid = $_GET['pid'];

What if $_GET isn't set, or the pid parameter wasn't passed? In that case, PHP will emit a notice (undefined index or something). Simply check before you attempt to assign:

if (!isset($_GET['pid']))
    exit();//or do something else
$pid = $_GET['pid'];

Avoid SELECT * FROM queries as much as you can. Sure SELECT * is quick and easy to write, but it does what it says on the tin: it selects every field. You only seem to be using 2 fields per row.
Why, then, do you feel compelled to select everything? Wouldn't:

SELECT shipcompany, deliverydate FROM your_wacky_tbl_name WHERE package_id = :pid

Work, too? As an added bonus: it's easier to see/understand for anyone maintaining this code what the query does, and what it selects. If you need some other field later on, then you can simply add that to the query.

Next, you've wrapped everything in a try block. Probably expecting PDO to throw up exceptions if any of the calls fail (PDO::prepare, PDOStatement::execute and PDOStatement::fetch or even that PDOStatement::bindColumn call that really serves no purpouse here, IMO).

This isn't going to work as you expect it to, because you haven't set PDO's error-mode so that it will throw exceptions. To do so, either pass an array to the constructor or call PDO::setAttribute:

$pdo = new PDO($dsn, $user, $pass,
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    )
);
//or
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

See a list of attributes that you can set, either by passing them as an assoc array to the constructor, or by calling PDO::setAttribute.

Pokémon Exception Handling
At the moment, you're just blindly catching any of the possible PDOExceptions that might be thrown. This is called Pokémon Exception Handling, when you "gotta catch 'em all". Another term you could use for this is code smell.

Depending on what part of your code that encounters problems, you should handle that problem differently: if the new PDO() line failed, then stop there but whatever you do: You don't echo the message to the user, as it is likely to contain information about your server.
Log the exception, and either throw up a new, more general RuntimeException('Server says no') exception.

If the PDOStatement calls fail, you can be a tad more specific in the error message you send to the user, but again: you don't show them the PDOException message. That message is likely to reveal information on your database or table.
Log the message, and present the user with a polite message, saying that you couldn't find his/her $_GET['pid'] product.

Basically, if you're going to work with exceptions, then have a handler registered that logs the exceptions that are thrown and present the user with a generic error message, hiding your server layout as much as possible.
It's easy to do, and increases the overall security of your application a bit.


I'd suggest using String.prototype.slice to implement startsWith like this:

String.prototype.startsWith = function(str) {
  return this.slice(0, str.length) === str
}

For type-checking (not needed in this example, but generally speaking) you might want to use the typeof operator:

if (typeof str !== 'string') return false

You can also use the instanceof operator if the value your dealing w/ isn't a literal or you need to check every value in the prototype chain, e.g. str instanceof String

haystack = this? Super-tacky ;p, but each to their own

Not sure if JS has an AIOOBE equivalent but 'blah'.charAt(6) === '' which tells me that check isn't needed.

And I'd suggest using Array iterators rather than for loops in the future:

var haystackStartsWithNeedle = needle.split('').
  forEach((v,i) => v === haystack[i]).find(v => v)

You might want to check babeljs.io. It transpiles new & flavoured JS to code most browsers can use.


Naming conventions

As you will have noticed from the coloring: you're not following naming conventions. Variables inside a method are lowerCamelCase which means this

FVc

becomes this

fvC

Naming

Your variables have very unclear names. From the context I know that this is part of a math formula, but you might be able to clarify them. If possible, consider using full words that clearly explain what that variable means.

In that regard I would definitely change this

totSaved

into this

totalSaved

"Saving" 2 characters is nothing, but it lowers readability.

Parsing

You parse the same textbox fields many times. Instead, parse it once and put it a variable. Now you can reference that variable every time and it will be a lot easier to work with.

Formula clarity

You should also consider splitting up your long formulas (insofar a portion of a formula would make sense) to help you in case something needs to be debugged. It will be easier to check intermediate values and to keep the overview over what your formula represents.


I'd just say, WTF is this doing?

You're testing minutes and hours first as if they were the most important things. So with 10 minutes, 1 hours and 1000 days, you output something like "1 hours ago".

Maybe it's impossible as the variables all get computed from a single time interval. But you didn't show us.

I guess it's better for my sanity not to try too hard to figure out what it exactly does. So let me assume that all variable come from a single time interval. Then a condition like

minutes >= 60 && hours < 24

can be expressed like

1 <= hours && hours < 24

This doesn't buy us much as the order is still confusing:

" hours ago"
" days ago"
" minutes from now"
" months ago"

Again, not trying to find a system there.

What about something like

String suffix = minutes < 0 ? "ago" : "from now";

if (Math.abs(days) >= 365) {
    return (Math.abs(days) / 365) + " years " + suffix;
} else if (Math.abs(days) >= 2*30) {
    return (Math.abs(days) / 12) + " months " + suffix;
} else if (Math.abs(days) >= 30) {
    return days < 0 ? "Last month" : "Next month";
} else if (Math.abs(days) >= 1) {
    return Math.abs(days) + " days " + suffix;
} else if (Math.abs(hours) >= 1) {
    return Math.abs(hours) + " hours " + suffix;
} else {
    return Math.abs(minutes) + " minutes " + suffix;
}

I'm not claiming it's correct, but it's short and damn simple, so you find and fix all bugs in a few seconds.

So what I dislike is

The high count of cases, which could be cut in half using the abs idea stolen from Hosch250.
Placing two tests in each if when one is enough. You need no range tests if you do it systematically.
Even with range tests, there should be a clean order.

I always prefer to keep things simple from the very beginning. Otherwise, it can easily happen that you get a cool idea, but can't apply it because of the need to preserve compatibility with some quirks in the original.

Another disadvantage of starting with complicated stuff is that you may miss some simplifications the way I did above. Concerning correctness, all the divisions and comparisons with 356 and 30 are slightly wrong.

Note also that the task is not exactly defined. Given the dates 2000-12-31T23:23:00 and 2001-01-01T00:11:22, multiple answers are correct:

"48 minutes from now"
"nearly one hour from now"
"tomorrow"
"next month"
"next year"

And maybe also "next century" and "next millennium", but both are disputable (and irrelevant most of the time).

There's no clear solution for this and you should specify the behavior precisely and cover it by tests. The most straightforward solution would be to look at the calendar year first, which would give us the answer "next year". Pretty impractical, but every other solution needs some arbitrary choices.

I'd probably start with

String timeDifferenceString(long currentTimeMillis, long otherMillis) {
    final boolean isPast = otherMillis < currentTimeMillis;

    final Calendar first = Calendar.getInstance();
    first.setTimeInMillis(Math.min(currentTimeMillis, otherMillis));

    final Calendar second = Calendar.getInstance();
    second.setTimeInMillis(Math.max(currentTimeMillis, otherMillis));

    return timeDifferenceString(first, second, isPast);
}

so that no Math.abs is needed anymore. Obviously, Joda-Time or the corresponding JDK8 classes are a better choice than Calendar, but let's keep it simple for this answer.

Now you can write

private String timeDifferenceString(Calendar first, Calendar second, boolean isPast) {
    final String agoOrFromNow = isPast ? "ago" : "from now";
    final String lastOrNext = isPast ? "last " : "next ";

    final int years = second.get(Calendar.YEAR) - first.get(Calendar.YEAR);
    if (years > 1) {
        return years + " years " + agoOrFromNow;
    } else if (years > 0) {
        return lastOrNext + "year";
    }

    final int months = second.get(Calendar.MONTH) - first.get(Calendar.MONTH);
    if (months > 1) {
        return months + " months " + agoOrFromNow;
    } else if (years > 0) {
        return lastOrNext + "month";
    }

    ...

    return "now";
}

This leads to a rather lengthy but trivial method. Now you may want to split it as suggested by h.j.k. This is not easy, as the parts above only conditionally return something. Using a guard condition, this can be solved like this

    if (years > 0) {
        if (years > 1) {
            return years + " years " + agoOrFromNow;
        } else if (years > 0) {
            return lastOrNext + "year";
        } else {
            return "this year";
        }
    }

After extracting the method, you'll see that it's about the same for every time unit, so you may want to generalize it to

private String timeDifferenceString(int count, String unitName, boolean isPast) {
    if (count > 1) {
        return count + " " + unitName +  "s " + agoOrFromNow(isPast);
    } else if (count > 0) {
        return lastOrNext(isPast) + " " + unitName;
    } else {
        return "this " + unitName;
    }
}

Note that this won't work for other languages for many reasons including pluralization rules.

Now, you have a few trivial methods and one important one looking like

private String timeDifferenceString(Calendar first, Calendar second, boolean isPast) {
    final int years = second.get(Calendar.YEAR) - first.get(Calendar.YEAR);
    if (years > 0) {
        return timeDifferenceString(years, "year", isPast);
    }

    final int months = second.get(Calendar.MONTH) - first.get(Calendar.MONTH);
    if (months > 0) {
        return timeDifferenceString(months, "month", isPast);
    }

    ...

    return "now";
}

This is the right time for making changes, allowing you to output "48 minutes from now" instead of "next year" in my above example.


Usage:

Famous Scott Meyers' words: "Make interfaces easy to use correctly and hard to use incorrectly". It should be kept in mind.

It is really cumbersome to use. Users have to create different scopes and they don't have any control over what's being output and where it's being output.

Also, it seems like the class is somewhat one shot, so users can't make multiple runs. Usually people make considerable amount of runs to normalize the numbers and diminish the noise. The interface could emphasize that.

It is needed to keep in mind that the responsibility of this class is to measure the timings. Don't do anything with it, just provide a way to read it.

Alternative solution:

template<typename Func>
class session {
    Func function;
    std::vector<std::chrono::duration<double>> timings;
public:
    session(const Func& f) :
            function(f)
    {}

    session(Func&& f) :
            function(std::move(f)) {}

    template<class ... Args>
    void measure(Args &&... args) {
        auto start = std::chrono::high_resolution_clock::now();
        function(std::forward<Args>(args)...);
        auto end = std::chrono::high_resolution_clock::now();

        timings.push_back(end - start);
    }

    //writes into the range until either exhausts it or timings vector is exhausted
    template<typename Unit, typename OutputIt>
    void get_as(OutputIt first, OutputIt last) {
        auto it = timings.begin();
        for (; it != timings.end() && first != last;
               ++first, ++it) {
            *first = std::chrono::duration_cast<Unit>(*it);
        }
    }
};

As you can see, single measure() call doesn't return the time, but rather get_as() is used to get all of the measurements at once, and throw it into some function that computes average and generally does processing of the collected data. The interface does little dictating on what users should do, and provides enough flexibility. In C++17, there even won't be a need to write

session<T> s(t);

it will be just

session s(t);

If it is so wanted, you can write freestanding measure() function to get timings of one function call.

What is done right:

The code is really generic, which is nice for portability reasons.

Rule of five nailed down.

Bad stuff:

(m_name == "" ? ": " : " (" + m_name + "): ");

This line is like calling for a challenge "Try to understand me!".

 m_end = Clock::now();
 output();

My opinion is that if you don't initialize a member variable during construction, then the member variable is a candidate for local variable and being passed by reference/const reference.

Don't postpone to runtime:

Get the string for units right in the beginning using the fact that units are aliases for std::ratio<>s.


The math

There is a useful formula for triangle numbers that vastly simplifies a lot of the code here:

$$\sum_{k=1}^n k = \frac{n(n+1)}{2}$$

So for instance, the first triangle number is \$1\$, the second \$1 + 2 = 3\$, the third \$1 + 2 + 3 = 6\$ and so fourth. Compare that to the Hearthstone fatigue counter.

The interface

The main function

In a lot of programming languages there is the concept of a main function. This is commonly emulated in Python with:

def main():
    ...

if __name__ == '__main__':
    main()

See this answer for more details. In your case, you should probably have your main() consist of the top level while True statement i.e.:

def main():
    while True:
        ...

if statements

It is rather unfortunate that Python doesn't have switch-case statements which provide a very nice way to match against mode. In this case I would recommend usage of tuple (or dictionary) to handle the modes. To illustrate:

def needed():
    while True:
        try:
            damageInput = int(input("\nPlease input the damage needed for lethal: "))
            startInput = int(input("Starting at how much damage? (default is 1): "))
            ...

def dealt():
    while True:
        try:
            turnsInput = int(input("\nPlease input how many fatigue turns: "))
            startInput = int(input("Starting at how much damage? (default is 1): "))
            ...

MODES = (needed, dealt)

def main():
    while True:
        ...
        MODES[mode]()

Default dictionary?

This takes a bit more work, but you probably want to invest some time into learning what defaultdict is. Default dictionaries give you the power of dictionaries in Python with the ability to avoid raising KeyErrors. You logic right now heavily relies on capturing bad input and handling the exceptions yourself. With a default dict, you:

don't need to convert anything to an integer, just use string keys. This prevents any sort of conversion error.
set the default value for the dictionary to error. In other words, MODES["SOME_GARBAGE_VALUE"]() will act like error().
Add another value to MODES which allows for an exit.


Keeping object consistence at its creation

At first:

  Note: Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations
  were added in that version.

Secondly:
You are passing in an array of volumes $volumes to the __construct function when instantiating an object of class Product. But there is no confidence that each element of $volumes is an object of Volume class. Someone could put into $volumes array an arbitrary value.
I would recommend applying dependency with Volume class and pass in Product constructor only one object of Volume class (following the initial rule: "Product must have at least 1 Volume"). And then, if necessary, you will be able to add some additional 'volumes' to product object using an auxiliary method addVolume().
See the optimized version:

<?php
declare(strict_types = 1);

namespace App
{
    class Product
    {
        private $id;
        private $name;
        private $volumes = [];

        /**
         * Product constructor.
         * @param int $id
         * @param string $name
         * @param array $volumes
         */
        public function __construct(int $id, string $name, Volume $volume)
        {
            $this->id = $id;
            $this->name = $name;
            $volume->setProduct($this);
            $this->volumes[] = $volume;
        }

        public function addVolume(Volume $volume)
        {
            $volume->setProduct($this);
            $this->volumes[] = $volume;
        }
    }

    class Volume
    {
        protected $id;
        protected $product;
        protected $description;

        public function __construct(string $description)
        {
            $this->description = $description;
        }

        public function setProduct(Product $product)
        {
            $this->product = $product;
        }
    }

    class ProductTest
    {
        public function __construct()
        {
            $volume1 = new Volume('part-1');
            $volume2 = new Volume('part-2');
            $volume3 = new Volume('part-3');

            $product = new Product(1, 'BED', $volume1);
            $product->addVolume($volume2);
            $product->addVolume($volume3);

            $invalidProduct = new Product(2, 'Table', []);
        }
    }

    return new ProductTest();
}


There are quite a few issues in this code to worry about on top of the virtual call in the constructor...
abstract public class MatlabData:eSoundMaster

The accessibility modifier should always come first and classes in C# are always PascalCase.
public abstract class MatlabData : ESoundMaster

You are using public readonly fields in the base class:
 public readonly int numTonspuren = 32;

It's usual to have public readonly fields use PascalCase
You then hide them with constants in the derived class and pass them to the base class's constructor. Don't hide the fields!

Don't abbreviate in your code. If you are going to, be consistent about it. E.g. nTonspuren vs numTonspuren.
Methods in C# should be PascalCase. isEQAMAvailable should be IsEQAMAvailable. That said, EQAMAvail should be a readonly property and the method should be removed.
In general, and without a good reason not to*, one should prefer properties to fields in C#. It's idiomatic to do that and it's an extra level of abstraction and leaves you free to change how that property is implemented without breaking consumers.
From the example, it's not clear why you have a class hierarchy at all here. It looks like you need one class with a factory:
// Typed directly on CodeReview, apologies for errors.
public class LabelDefinition
{
    public string Text { get; }
    public string Name { get; }
    // etc.
}

public class MatlabData : eSoundMaster
{
    public bool EQAMAvail { get; }
    public int NumTonspuren { get; }
    public int NumSubgroups { get; }
    public int NumStandardTS { get; }
    public int NumPremiumTS { get; }
    public int NumOutputs { get; }
    public int NumSoundtrackLUTs { get; }

    public MatlabData(
        int numTonspuren,
        int numIntermediateMixerChannels,
        int numStandardTS,
        int numPremiumTS,
        LabelDefinition[] labels,
        string[] additionalLabelNames)

    {
        NumTonspuren = numTonspuren;
        NumSubgroups = numIntermediateMixerChannels;
        NumStandardTS = numStandardTS;
        NumPremiumTS = numPremiumTS;
        LabelText = labels.Select(l => l.Text).ToArray();
        LabelName = labels.Select(l => l.Name).Concat(additionalLabelNames).ToArray();
        // etc.
    }
}

public class MatlabDataFactory
{
    public MatlabData CreateDefault => new MatlabData(...);
}

*There are vanishingly few reasons to use a public field over a property.


There really isn't much to say here. This looks really good.

Typos

You have a couple typos in your code on your equality operators. You're comparing against other.p instead of other._p.

Not restrictive enough

We have this constructor:

constexpr explicit contiguous_iterator(T* p);

But that means if we have contiguous_iterator<Base>, we can construct it with a Derived*. We definitely need to disallow this.

On a similar vein, rebind<U> should be restricted to those Us which are the same type as T and are at least as cv-qualified.

Add another alias

Rather than writing this:

constexpr explicit contiguous_iterator(contiguous_iterator_base<std::remove_cv_t<T>> other) noexcept : decltype(other)(other) {}

If you added a using base = contiguous_iterator_base<std::remove_cv_t<T>>;, you could write:

constexpr explicit(base other) noexcept : base(other) {}

which makes way more sense.

Missing alias

You're using the alias templates for the type traits throughout, except you're using typename std::conditional<X>::type instead of std::conditional_t.

Line widths

Some of these lines are really long! Add some line breaks.

Why?

I guess lastly... what does contiguous_iterator<T> accomplish that simple T* doesn't?


javascript property extractor optimisation

Here are some of my thoughts:

I don't see the point in providing the path as a dot separated string, but it may be useful in your application.
If you keep the dot separated string, then you should consider extracting the recursive function into a separate internal function, so that you don't have to repeat the check of the path argument in each iteration.
Why do you check for the shift method? If it doesn't exist, then your function will fail silently. The regular "method does not exist" exception would be much more useful. Instead implement the method on the Array.prototype yourself separately if it doesn't exist.
Finally I would move the path.length == 0 to the start of the function. That is where the break condition of recursive functions are usually expected.


Aside from @Sumurai8 recommendations, the sql query can be indeed complexified a bit to return all the results in one go:

SELECT DATE_FORMAT(`sessionStart`, '%Y-%m-%d') AS `day`, COUNT(*) AS `sessions`
FROM `sessions`
WHERE
    DATE(`sessionStart`) BETWEEN DATE_SUB(CURDATE(), INTERVAL 90 DAY) AND CURDATE()
GROUP BY
    `day`
ORDER BY
    `day`

It only needs to be executed once, and then iterated over the result set using your favorite FETCH_XXX method.


If the packet size is less than 32k words, then you do not need to add the carry until the end:

while(byte>0)  //len = Total num of bytes
{
    Checksum = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and  add previous calculated checsum value

    len -= 2; //decrease by 2 for 2 byte boundaries
    i += 2;
}

 Checksum = (Checksum>>16) + Checksum; //Add the carryout

 Checksum = (unsigned int)~Checksum;


Speed up a simple edge connecting algorithm

Just a collection of thoughts...

Terminology

Since you're talking about graphs, it might help the readers if you talk about nodes (your edges) and edges (your links).

Your graph is directed, and as far as I can tell, you're looking for the "strongly connected components".

Use simpler objects

Lists of pairs of pairs aren't very readable IMHO. When showing examples, you can replace them with lists of strings:

edges = ['AB', 'CD', 'EF', 'GH']
links = ['HA', 'BG', 'FC', 'DE']

Python strings are basically tuples of characters, so you don't have to change much in your code. The above example is isomorphic to yours and is much more concise.

KeyError

When calling edges[links[e[1]], you're hoping there won't be any KeyError. Your example would fail with :

edges = ['AB', 'CD', 'EF', 'GH']
links = ['HA', 'BG', 'FC']

Links between multiple edges

What happens in the case of link connecting more than 2 edges, for example

edges = ['AB', 'GH', 'AC']
links = ['HA']

? Your current algorithm doesn't seem to take it into account. A defaultdict(list) might help, for example to keep a list of nodes beginning with A and another list for nodes finishing with H.

Output format

If you only sort the edges, without grouping them in connected components, you're losing information which you have to recover later. You could return a list of sets of edges instead of a flat list of edges.

[{'AB', 'GH'}, {'CD', 'EF'}]

networkx

If you work with graph theory in Python, you should take a look at networkx. It's fast, easy to use and offers many algorithms. All you need to do is to preprocess your data and feed it to a nx.DiGraph.

Your example could become:

import networkx as nx
from collections import defaultdict
import matplotlib

edges = ['AB', 'CD', 'EF', 'GH']
links = ['HA', 'BG', 'FC', 'DE']

G = nx.DiGraph()

from_dict = defaultdict(list)
to_dict = defaultdict(list)

for edge in edges:
    node = ''.join(edge)
    G.add_node(node)
    to_dict[node[0]].append(node)
    from_dict[node[1]].append(node)

for link in links:
    for node1 in from_dict[link[0]]:
        for node2 in to_dict[link[1]]:
            G.add_edge(node1, node2)

list(nx.strongly_connected_components(G))
# [{'AB', 'GH'}, {'CD', 'EF'}]
nx.draw(G, with_labels = True)

It displays:

You get more information, it's more robust, you get diagrams if you want, it can handle more complex cases and (who knows?) it might be faster than your solution for large datasets.


Annotate a class's important string value via an attribute

It's considered bad form for a property getter to throw an exception. I would do so in a protected constructor of your FieldBase class. At that point, you can cache the retrieved value in a class member and not have to do any reflection in the property getter at all.

I'm also a fan of immutable semantics where available and appropriate and have modified the attribute itself to be such:

[FieldTag("Base")]
public abstract class FieldBase {
    protected FieldBase() {
        FieldTagAttribute fieldTagAttribute = (FieldTagAttribute) (GetType().GetCustomAttribute(typeof(FieldTagAttribute), false));

        if (fieldTagAttribute == null) {
            throw new InvalidOperationException(String.Format("Class {0} has no attribute [FieldTag]. Please add the attribute to this class.", GetType()));
        }

        s_FieldTag = fieldTagAttribute.FieldTag;
    }

    private readonly string s_FieldTag;

    public string FieldTag { get { return s_FieldTag; } }
}

[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited = false)]
public sealed class FieldTagAttribute : Attribute {
   public FieldTagAttribute(string fieldTag) {
       s_FieldTag = fieldTag;
   }

   private readonly string s_FieldTag;

   public string FieldTag { get { return s_FieldTag; } }
}

[FieldTag("32A")]
public class Field32A : FieldBase {
    public string Value { get; set; }
    public override string ToString() {
        return ":" + FieldTag + ":" + Value;
    }
}

public class Program {
    public static void Main() {
        Field32A field32A = new Field32A { Value = "12345" };
        field32A.ToString().Dump();
    }
}


I may not be considering all fringe cases (please enlighten me if this breaks with any realistic input), but all of the logic can be packed into a single preg_replace_callback() call.

I start by declaring a 1-dimensional array which will contain all numeric counters.
My pattern ~^(#+)\K~m says:
From the start of each line, capture one or more hash symbols as capture group #1, then restart the fullstring match .  In doing so, my replacement string to be determined inside the custom function will not actually be replacing any characters, but adding new characters at the zero-length position marked by \K.  This spares you needing to match the rest of the line and adding that to the replacement.
Making $levels modifiable by reference with & means that $level will be updated with each iteration of the regex matches.
After counting the elements in $levels and counting the length of the matched string, precise modifications can be done to $levels to provide the desired set of numbers.
The return value is a space followed by the dot-imploded $levels array.
array_slice() avoids poping in a loop.
I don't think your array_values() call is necessary.

Code: (Demo)

$headers = <<<HEADERS
# Hello

## World

### Let's add

## Some headers

### Yay!

# Foo

## Bar

## Bar Again
HEADERS;

$levels = [];
echo preg_replace_callback(
        '~^(#+)\K~m',
        function($m) use (&$levels) {
            $hashes = strlen($m[1]);
            $index = $hashes - 1;
            $reduction = sizeof($levels) - $hashes;
            if (!isset($levels[$index])) {
                $levels[$index] = 1;
            } else {
                ++$levels[$index];
            }
            if ($reduction > 0) {
                $levels = array_slice($levels, 0, -$reduction);
            }
            return " " . implode('.', $levels);
        },
        $headers
    );

Output:

# 1 Hello

## 1.1 World

### 1.1.1 Let's add

## 1.2 Some headers

### 1.2.1 Yay!

# 2 Foo

## 2.1 Bar

## 2.2 Bar Again


Putting the JSONArray aside (given I don't know the fully qualified name of the class), here's a Groovy-er version:

Working example

def invoiceList = [
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617151,SENDER_COUNTRY:'USA', CLIENT_COUNTRY:'USA'],
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617152,SENDER_COUNTRY:'CAD', CLIENT_COUNTRY:'MEX'],
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617153,SENDER_COUNTRY:'CAD', CLIENT_COUNTRY:'MEX']
]

def senderCountry = invoiceList[0]['SENDER_COUNTRY']
def clientCountry  = invoiceList[0]['CLIENT_COUNTRY']

def result = invoiceList.inject([:]) { status, invoice ->
    if(invoice['SENDER_COUNTRY'] != senderCountry) status << ["SENDER_COUNTRY": "Multiple sender Countries Associated"]
    if(invoice['CLIENT_COUNTRY'] != clientCountry) status << ["CLIENT_COUNTRY":"Multiple Client Countries Associated"]

    status
}

if(result) {
    println "Not all invoices have the same sender and client countries."
} else {
    println "All good"
}

How it works

The inject() method iterates through the invoiceList and calls a closure with an object to aggregate with and the current item in the list. Iteration begins with an empty Map as the aggregated object, which remains empty unless the un-matching countries are found. When a mismatch occurs, it is recorded in the Map. The closure purposely returns the Map because the output of the closure is what's fed back in during the next iteration.

Finally, if the resulting Map is empty, then all of the countries are the same. Otherwise, the Map contains one or two keys indicating what the problem was.

If all you really need to know is whether all the countries matched or not, you can simply use every():

def result = invoiceList.every { invoice ->
    invoice['SENDER_COUNTRY'] == senderCountry && invoice['CLIENT_COUNTRY'] == clientCountry
}


improve the design of class “accuracy” in Python

If you plan on calling the four functions ra_or, ra_os, sim_size and AFI outside of Accuracy then it is good to keep them as functions. If they never get called except through Accuracy, then they should be made methods.

Classes can help organize complex code, but they generally do not make your code faster. Do not use a class unless there is a clear advantage to be had -- through inheritance, or polymorphism, etc.

If you want faster code which uses less memory, avoid using a class here. Just define functions for each attribute.

If you want "luxurious" syntax -- the ability to reference each statistic via an attribute, then a class is fine.

If you plan on instantiating instances of Accuracy but not always accessing all the attributes, you don't need to compute them all in __init__. You can delay their computation by using properties.

 @property
 def area(self):
    return self.ref.area

Note that when you write accp1.area, the area method above will be called. Notice there are no parentheses after accp1.area.

To be clear, the advantage to using properties is that each instance of Accuracy will not compute all its statistical attributes until they are needed. The downside of using a property is that they are recomputed everytime the attribute is accessed. That may not be a downside if self.ref or self.seg ever change.

Moreover, you can cache the result using Denis Otkidach's CachedAttribute decorator. Then the attribute is only computed once, and simply looked up every time thereafter.

Don't use an arbitrary value for noData like noData = -9999. Use noData = np.nan, or simply skip noData and use np.nan directly.

import numpy as np
from shapely.geometry import Polygon
nan = np.nan

class Accuracy(object):
    def __init__(self, ref, seg=None):
        self.ref = ref
        self.seg = seg

    @property
    def area(self):
        return self.ref.area

    @property
    def perimeter(self):
        return self.ref.length

    @property
    def centroidX(self):
        return self.ref.centroid.x

    @property
    def centroidY(self):
        return self.ref.centroid.y

    @property
    def data(self):
        return [self.centroidX,
                self.centroidY,
                self.area,
                self.perimeter,
                self.segments,
                self.RAor,
                self.RAos,
                self.SimSize,
                self.AFI]

    @property
    def segments(self):
        if self.seg:
            return len(self.seg)
        else:
            return nan

    @property
    def RAor(self):
        if self.seg:
            return np.average(
                [(self.ref.intersection(s).area / self.ref.area) for s in self.seg])
        else:
            return nan

    @property
    def RAos(self):
        if self.seg:
            return np.average(
                [(self.ref.intersection(s).area / s.area) for s in self.seg])
        else:
            return nan

    @property
    def SimSize(self):
        if self.seg:
            return np.average(
                [(min(self.ref.area, s.area) / max(self.ref.area, s.area))
                 for s in self.seg])
        else:
            return nan

    @property
    def AFI(self):
        if self.seg:
            return (self.ref.area - max([s.area for s in self.seg])) / self.ref.area
        else:
            return nan

p1 = Polygon([(2, 4), (4, 4), (4, 2), (2, 2), (2, 4)])
p2 = Polygon([(0, 3), (3, 3), (3, 0), (0, 0), (0, 3)])

accp1 = Accuracy(p1, [p2])
print(accp1.data)
# [3.0, 3.0, 4.0, 8.0, 1, 0.25, 0.1111111111111111, 0.44444444444444442, -1.25]

accp1 = Accuracy(p1)
print(accp1.data)
# [3.0, 3.0, 4.0, 8.0, nan, nan, nan, nan, nan]

Here is how you could save your data (as a numpy array) to a CSV file:

np.savetxt('/tmp/mytest.txt', np.atleast_2d(accp1.data), delimiter=',')

And here is how you could read it back:

data = np.genfromtxt('/tmp/mytest.txt', dtype=None)
print(data)
# [  3.   3.   4.   8.  nan  nan  nan  nan  nan]


The GMP code on RosettaCode is about 2x faster if you're looking for performance improvements.

It has a reasonable number of comments explaining the various optimizations.  Most of the help will be in the pre-tests, where we know easy ways to find out if the result will be composite.  The test itself is not too dissimilar, with a few different choices made.

I don't particularly like your for loop, which you wrote more like a while loop -- mixing the iteration and test together.


A function which translates a sentence to title-case

I find this code quite reasonable on the whole, but you might consider the following suggestions relating to consistency, succinctness and semantics.

Move and rename the inner helper function

translateWord is reusable as a general utility function and seems better-placed in the global scope and renamed to titleCase. This meshes with similarly-named Ruby, Python and PHP builtins (titlecase, title, ucfirst, respectively). When I see "translate", I think of linguistics or mathematics before I think of strings or casing.

Avoid excessive calls to toLowerCase

.toLowerCase() is more efficient called once on the entire sentence before splitting rather than incurring the overhead of calling it multiple times per word. With this in mind, you can skip calling the titleCase function described above if you wish.

Improve "ignore" list

if (!["of", "and", "the", "to"].includes(words[i].toLowerCase())) {

is problematic for a few reasons:

It creates a new array object for every word. Move initialization to the top of the function and create it once.
Hardcoding restricts your function's reusability. Making this ignore list a default parameter allows the client to adjust the list as needed.
Giving this array a variable name makes its purpose more obvious.
Although the array is small, it needs to be traversed linearly to perform a lookup; using a set improves semantics, readability and time complexity all at once and is the ideal structure for testing membership.

Avoid the loop

This task is a map operation: each word has a function applied to it. You can roll split, map (your for loop) and join into one call to replace, which takes a regular expression that splits on non-word characters and applies the titleCase function to each one that passes the ignore test.

Minor points

sWord.slice(0, 1) can be sWord[0].
sWord is an okay variable name, but str (matching your outer function) or word seems more consistent.
Unless there is a good hoisting or context reason, I'd make the outer function also use an arrow function for consistency with your inner function.

A rewrite

const titleCaseWords = (words, ignore=["of", "and", "the", "to"]) => {
  ignore = new Set(ignore);

  return words.replace(/\w+/g, (word, i) => {
    word = word.toLowerCase();

    if (i && ignore.has(word)) {
      return word;
    }

    return word[0].toUpperCase() + word.slice(1);
  });
};

[
  "Into unmerciful the entreating stronger to of word guessing.",
  "the OLD MAN aND THE sEa"
].forEach(test => console.log(titleCaseWords(test)));


Bash script to extract wifi passwords from NetworkManager

General
Always include a shebang, and set options to exit the script when a command fails or when we use a variable that's not set:
#!/bin/bash

set -eu

Test for existence with -e, not -d
If wifi_pass_dir exists, but is not a directory (perhaps it's a plain file), it will not be deleted, and the mkdir will fail.  It might be better not to check (rm -f will succeed if the file doesn't exist):
# Ensure the wifi_pass_dir exists
rm -rf wifi_pass_dir
mkdir wifi_pass_dir

However, I don't believe it's necessary to copy the config files to an insecure location and make them world readable (and writeable) - see later.
sudo is for interactive use, not scripts
Avoid using sudo in a script - it expects to be interactive, and won't necessarily do what you want if not connected to a terminal.  It's easier to require that the script be run under sudo (and we can then use su to change to a non-privileged user where necessary).
Don't parse the output of ls
Filenames you don't control can contain all sorts of characters, including newlines.  Here, we don't need to do that, as we're reading from a directory.  The while read loop can simply be a for f in * loop.
Don't over-exercise the cat
This cat isn't needed:
cat "$name" | grep psk=

Just tell grep to take its input from $name directly:
grep psk= "$name"

We don't even need a loop, as we can pass all the filenames to grep in one go.

Simplified code
#!/bin/bash
exec grep 'psk=' /etc/NetworkManager/system-connections/*

Yes, that's the whole program.  Since we only execute one command, we don't need set -e, and as we use no variables, neither do we need set -u.


I am not sure if you like this one better but I personally prefer returning directly (and therefore omitting the else-clauses). I do not know if there was a better way.

public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) {

  if (!userCanJoinAndLeave)
    return getText(getLocale(), "no");

  if (startDate == null && endDate == null)
    return getText(getLocale(), "continuous");

  if (startDate == null && endDate != null)
    return getText(getLocale(), "to")
            + " "
            + formatDate(endDate);

  if (endDate == null)
    return getText(getLocale(), "from")
            + " "
            + formatDate(startDate);

  return formatDate(startDate);
          + " "
          + getText(getLocale(), "to")
          + " "
          + formatDate(endDate);
}


Cloning Distinct XML structures without data in PHP

I would consider getting all nodes using getElementsByTagName('*') (note wildcard usage).

I would also consider simply cloning the $doc object.

That could simplify to this:

$doc = new DOMDocument();
$doc->loadXML($xml);
$clone = cloneDOMDocument($doc, true);

function cloneDOMDocument(DOMDocument $source, $remove_values = false) {
    $clone = clone $source;
    if($remove_values === true) {
        // select all nodes in clone
        $all_nodes = $clone->getElementsByTagName('*');

        // iterate all nodes in clone, resetting leaf values to empty string
        foreach($all_nodes as $node) {
            if($node->hasChildNodes() === false) {
                $node->nodeValue = '';
            }
        }
    }
    return $clone;
}


From what I can see you are calling an init function on every service so you can get data and cache it at startup.

A better way to do this would be to use the dependency injection layer for example using unity

    builder.RegisterType<CurrenciesService>()
        .As<ICurrenciesService>()
        .AutoActivate()
        .OnActivating(x => x.Instance.Init())
        .SingleInstance();

So this code activates your Currency Service, auto activates it when the container is building, when it gets activated calls init and puts it in single instance. Single instance is needed otherwise the init will be called on every request.


The longest subsequence with specified difference between min and max

Bugs
The function doesn't handle the last series of numbers.  For example:
Input: 5 5 5       Output: 0
Input: 5 5 9 9 9   Output: 2

This can be fixed by modifying the end of the function:
    return Math.max(res, counter); // <-- Accounts for last series

Also, the function fails to consider a number as the lower of two numbers once it has used it as the upper of two numbers.  For example:
Input: 5 5 6 6 6 7 7 7 10    Output: 5 (should be 6)

Here, it groups 5 and 6 together but never considers that 6 and 7 can be grouped together.


I'd make an object whose key is the pathname and whose value is the unique string for that pathname, then iterate through the object to find the matching key:

const BASE_SITE_NAME = 'BASE_SITE_NAME';
const descriptions = {
    about: 'About Us',
    fees: 'Our Fees',
    legal: 'Legal Info',
    register: 'Registration',
    login: 'Login',
};
const getMetaDescription = (pathname) => {
    const foundDescriptionKey = Object.keys(descriptions).find(key => pathname.includes(key));
    return foundDescriptionKey
        ? descriptions[foundDescriptionKey] + ' | ' + BASE_SITE_NAME
        : BASE_SITE_NAME;
};

console.log(getMetaDescription('about'));
console.log(getMetaDescription('foobar'));

If pathname is directly from the URL in the browser, make sure to call toLowerCase() on it first (just in case, for example, someone types in example.com/ABOUT instead of clicking a link that redirects to /about).
This is faithful to your original code. But if each of the descriptions correspond to an entirely separate route, it'd be better to just use plain property lookup. For example, if the pathname is /about, extract the about from that and look up that key on the object, instead of iterating.

const BASE_SITE_NAME = 'BASE_SITE_NAME';
const descriptions = {
    about: 'About Us',
    fees: 'Our Fees',
    legal: 'Legal Info',
    register: 'Registration',
    login: 'Login',
};
const getMetaDescription = (pathname) => {
    const description = descriptions[pathname.slice(1)];
    return description
        ? description + ' | ' + BASE_SITE_NAME
        : BASE_SITE_NAME;
};

console.log(getMetaDescription('/about'));
console.log(getMetaDescription('/foobar'));

The .includes approach is needed only if you have multiple pathnames associated with a single description. Even if you have multiple pathnames associated with a single description, consider using startsWith instead - it'll be more precise and less likely to have collisions. For example, if you have example.com/profile/aboutme, the about would result in About Us being displayed, which would not be desirable.

const BASE_SITE_NAME = 'BASE_SITE_NAME';
const descriptions = {
    about: 'About Us',
    fees: 'Our Fees',
    legal: 'Legal Info',
    register: 'Registration',
    login: 'Login',
    profile: 'Profile',
};
const getMetaDescription = (pathname) => {
    const foundDescriptionKey = Object.keys(descriptions).find(key => pathname.slice(1).startsWith(key));
    return foundDescriptionKey
        ? descriptions[foundDescriptionKey] + ' | ' + BASE_SITE_NAME
        : BASE_SITE_NAME;
};

console.log(getMetaDescription('/about'));
console.log(getMetaDescription('/profile/aboutme'));
console.log(getMetaDescription('/foobar'));


Given a function that returns a random number 0 or 1, write a function that returns a number between 0 and 199

You're just trying to get a certain number of random bits, so calculate that number ahead of time:

bits = 199.to_s(2).length

Then your loop becomes:

loop do
  result = 0
  bits.times do
    result <<= 1
    result += f2
  end
  return result if result >= 0 && result <= 199
end


There are quite a few issues with your code as it stands. I know you've said to go "super tough" on you, but the amount of knowledge required to write a relatively complete linked list implementation in C++ is more than just about any other language.

As a minor point up-front, I'm going to change anything that has a prefixed _ (like _first or _key) to using a postfix underscore (so first_ and key_). The reason for this is that certain symbols are reserved for compiler usage; the rules are arcane, but the simplest thing to do is:

Avoid anything with a leading underscore (_<varname>)
Avoid anything with 2 trailing underscores (<varname>__)

Edit: As pointed out by @JerryCoffin, you should avoid __ just about anywhere (prefix, postfix, and so on).

The first (and largest) problem is that this never frees any of the heap allocated memory (that is, memory allocated with new). Every time you do:

Node<T> *first = new Node<T>(key, value);

This will allocate memory from the heap. Unlike garbage collected languages (most languages except C and C++), it is up to you, the programmer, to free this memory when you are done with it. Here, this means manually writing the destructor:

~LinkedList()
{
    Node<T>* next = _first;
    while(next != nullptr) {
        first_ = first_->next;
        delete next;
        next = first_;
    }
}

This will make sure that memory is reclaimed.

To go along with this, there are a few methods that are implicitly generated for you when you write a class in C++. These are the copy assignment operator, and the copy constructor. They have the forms:

LinkedList& operator=(const LinkedList& rhs); // Copy assignment
LinkedList(const LinkedList& rhs);  // Copy constructor

When are these called? Say you define a LinkedList<int>:

LinkedList<int> a;
// Do some operations on a, such as adding nodes
LinkedList<int> b;
// Some operations on b
b = a;  // Calls the copy assignment operator, operator=
LinkedList<int> c(a);   // Calls the copy constructor

The methods that C++ implements for you here will do something that you do not want them to do: the b.first_ pointer will be equal to a.first_. What this means is that, if the destructor for a is called, then b will be pointing to memory locations that have been reclaimed using delete (which is very, very bad).

To fix this, they need to be implemented to do the correct thing. So, what is the correct thing to do? Let's look at them each in turn:

The copy constructor just needs to copy each element of the passed in LinkedList in turn:

LinkedList(const LinkedList& rhs)
{
    Node<T>* tmp = rhs.first_;
    while(tmp != nullptr) {
        add(tmp->key_, tmp->value_);
    }
}

The copy assignment operator needs to:

Free the current memory held by this
Copy each value in the list rhs

So, the implementation looks something like:

LinkedList& operator=(const LinkedList& rhs)
{
    // Stop self assignment, like: a = a;
    if(&rhs != this) {
        // Step 1: Free current memory
        Node<T>* tmp = first_;
        while(tmp->next != nullptr) {
            first_ = first_->next;
            delete tmp;
            tmp = first_;
        }
        count_ = 0;

        // Step 2: Create a copy of rhs
        temp = rhs.first_;
        while(tmp != nullptr) {
            add(tmp->key_, tmp->value_);
        }
    }
    return *this;
}

This is actually a very well known thing in C++: it is called the rule of three (or in more modern C++, the rule of five - but ignore this for the moment). What it says is:

If you need to manually write any one of the destructor/copy constructor/copy assignment operator, then you need to manually define all three of them.

For a full treatment of this, you might want to read this post.

Using a const char * const as a key in a linked list is unusual, and doesn't really fit with the basic idea of the data structure. If you want to look something up by key, you're generally looking for a data structure called a map (or hashmap, or dictionary; there are multiple names for it). I'd remove the complication there, and just get rid of the key member entirely.

void add(const T &value)
{
    Node<T> *first = new Node<T>(key, value);
    first->next_ = first_;
    first_ = first;
    count_++;
}

I've also removed the return of the Node<T> *. You generally don't want to let the users of your class have direct access to a Node<T> *.

Your remove function also leaks memory, you again need to have a delete in there.

 Node<T>* tmp = next;
 if (next == _first) {
     _first = next->getNext();
     delete tmp;   // Need a delete here
 }
 else {
     previous->setNext(next->getNext());
     delete tmp;  // Or here
 }
 _count--;

Edit: How you've written a search is much more dictionary-like. For the standard library list, you'd often use something like std::find_if, which takes a predicate (which is just a fancy word for a function that returns a bool). This allows you to use an actual function to select what you're looking for. As an example, if you have a Student struct:

struct Student
{
    std::string name;
    int age;
    int year;
};

Then you had a list of Students:

std::list<Student> students;

You might want to search for a student who has the name "John": this would look like:

std::find_if(students.begin(), students.end(), [](const Student& s)
    { return s.name == "John"; });

In fact, this will actually return an iterator into the container.

This also gives you more flexibility, as you can use the same function to find a student who is, say, 17 years old:

std::find_if(students.begin(), students.end(), [](const Student& s)
    { return s.age == 17; });

Edit 2: As was pointed out, the copy assignment operator is not written in the best way. Firstly, understanding why this is the case is important. If you look at the steps we go through, we firstly free all the memory currently held, and then repopulate the current list. The problem with this is that if anything throws an exception during either of these, we'll be left with object state that is inconsistent. The way to fix this is to use what is commonly termed "copy and swap". This also has the nice property that it allows us some code reuse, cutting down on duplication.

The first port of call is to write a (member) swap function:

template <typename T>
void LinkedList<T>::swap(LinkedList<T>& other)
{
    using std::swap;
    swap(first_, other.first_);
    swap(count_, other.count_);
}

Then a free function that forwards to this:

template <typename T>
void swap(LinkedList<T>& a, LinkedList<T>& b)
{
    a.swap(b);
}

Now we can write a copy assignment operator as follows:

LinkedList& operator=(LinkedList rhs)
{
    swap(*this, rhs);
    return *this;
}

Note that the rhs parameter is now taken by value. This will perform a copy construction, hence once we enter the call, rhs will contain a full copy. Then all that needs to happen is a few pointer swaps. Note also that the original memory that was held is destroyed: when rhs goes out of scope at the end of the function, its destructor is called. Since it now points to (what was) the original memory for this, that memory is properly reclaimed.

This has a number of benefits: Firstly, it is succinct and reuses code, secondly, it is exception safe: if any operation throws, our object is left in a consistent state - the update is effectively atomic; it either works completely or fails completely.

Using swap, you can also easily write a move assignment operator.


The individual methods in your code are fine; the structure is what hurts its maintainability. By adding specific update methods to the main Item class, you are giving it a huge amount of responsibility. Adding a layer of abstraction could let you write a simpler Item class and implement the specifics of the item aging process somewhere else.
The trick with this challenge is to recognize the assumptions that are being made by all items, and which parts of the program change for different items. For example, the update logic only ever affects the quality and sell_in properties. Furthermore, these properties change based only on the state of that individual item.
With this in mind, the item class can be written as this, where ager() returns an object with a nextQuality() and a nextSellIn() method, which return the item's values for the next day.
class Item:
    def __init__(self,name,sell_in,quality):
        self.ager = ager(name)

        self.name = name
        self.sell_in = sell_in
        self.quality = quality

    def age(self):
        self.quality = self.ager.nextQuality(self)
        self.sell_in = self.ager.nextSellIn(self)

    def __repr__(self):
        return "%s, %s, %s" % (self.name, self.sell_in, self.quality)

Then, an ager could be written like this, taking in the item as an input.
class DefaultAger:
    @staticmethod
    def nextQuality(item):
        return clamp_quality(item.quality-1)
    @staticmethod
    def nextSellIn(item):
        return item.sell_in-1

Right, we need that clamp_quality(). There's no need to mutate the item with this function, as the mutation already occurs in the age() method of Item. clamper() returns a function that clamps values between lo and hi.
def clamper(lo,hi):
    return lambda val:max(lo,min(hi,val))
clamp_quality = clamper(0,50)

With all of this, we can add a barebones implementaton of ager(). This will handle all items that don't have any special rules.
def ager():
  return DefaultAger

Okay that's great and all, but the entire point of this program is the edge cases. Lets get those in. All of this logic can be handled using more Ager objects.
class ConjuredAger(DefaultAger):
    @staticmethod
    def nextQuality(item):
        return clamp_quality(item.quality-2)

class LegendaryAger(DefaultAger):
    @staticmethod
    def nextQuality(item):
        return item.quality
    @staticmethod
    def nextSellIn(item):
        return item.sell_in

class BackstageAger(DefaultAger):
    @staticmethod
    def nextQuality(item):
        if item.sell_in<=0:
            return 0
        if item.sell_in<5:
            return clamp_quality(item.quality+3)
        if item.sell_in<10:
            return clamp_quality(item.quality+2)
        return clamp_quality(item.quality+1)

Now for the beautiful part. If we dynamically give each item the correct ager, then all we need to do is call item.age() to update an item.
#maps items by name to the correct ager
agers={
    "Aged Brie":BackstageAger,
    "Sulfuras":LegendaryAger,
    "Backstage Pass":BackstageAger,
    "Mystical Hat":ConjuredAger
}
def ager(name):
    if name in agers:
        return agers[name]
    else:
        return DefaultAger

To verify it works:
items = [
    Item("Aged Brie",5,10),
    Item("Sulfuras",5,80),
    Item("Backstage Pass",5,20),
    Item("Jar",20,8)
]
# print this out to make sure we
# set all the agers correctly
print([
    item.ager for item in items
])

for i in range(10):
    print("========= Day %d ========="%i)
    for item in items:
        print(item)
        item.age()

I realize this probably comes off as me showing off my own solution to the problem , but it's the best way I could demonstrate this idea of delegating responsibility into smaller objects. If a new type of item were to be added, one would only need to write an ager and assign it; the Item class could remain untouched.


Rails passing in params to association on create method

You have two issues here:

need to find parent model first, and then build association (as group_id could be wrong)
create would try to save record, so you're trying to save twice. Use build/new instead.

    def create
      @group = Group.find(params[:group_id])
      @mapgroup = @group.mapgroups.build(mapgroup_params)

      respond_to do |format|
        if @mapgroup.save
          format.html { redirect_to groups_path, notice: 'Mapgroup crated' }
        else
          format.html { render :new, notice: 'That shit failed' }
        end
      end
    end


RESTEasy client that should use generics

I managed to get RESTEasy to work with generics (both lists and single objects) and parse the response to JAXB annotated classes by using the following code that uses reflection:

<T> List<T> getList(String path, List<String[]> params, final Class<T> clazz) {
    GenericType<List<T>> type = getListType(clazz);
    Response entity = getEntity(path, params);
    return entity.readEntity(type);
}

<T> T getObject(String path, List<String[]> params, final Class<T> type) {
    Response entity = getEntity(path, params);
    return (T)entity.readEntity(new GenericType(type) {});
}

private <T> GenericType<List<T>> getListType(final Class<T> clazz) {
    ParameterizedType genericType = new ParameterizedType() {
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        public Type getRawType() {
            return List.class;
        }

        public Type getOwnerType() {
            return List.class;
        }
    };
    return new GenericType<List<T>>(genericType) { };
}


I'm probably off my rocker here, but what if rather than nested chains of bind, you used a fork/join type of approach?

static combine<T, S, R>(
    monads: { [P in keyof T]: StateMonad<S, T[P]> },
    selector: (values: T) => R
)
    : StateMonad<S, R> {
    return new StateMonad<S, R>((state) => {
    var ret: any = {};
    for (const key in monads) {
        if (monads.hasOwnProperty(key)) {
        ret[key] = monads[key].runState(state).a;
        }
    }
    return { a: selector(ret), s: state }
    }
    );
}

and

var { a } = StateMonad
  .combine(
    {
      countLowerCase,
      countDigits
    },
    combined =>
      combined.countLowerCase +
      combined.countDigits
  )
  .runState("abc123ABC");


Not bad.

Unbounded recursion

Inside the Game class:

def initialize
  # ...
  play_game
end

def play_game
  @player1 = Player.new("X")
  @player2 = Player.new("O")
  # ...
  play_again
end

def play_again
  # ...
  if answer == "yes"
    TicTacToe::Game.new
  else
    # ...
  end
end

You're using recursion to repeat the game, which can get arbitrarily deep, leading to a stack overflow error. Use a loop instead. Also, to avoid violating the Single Responsibility Principle, put this loop outside the Game class whose sole responsibility should be to play a game.

Don't call play_again in play_game, and move play_again outside the class. The main code should be:

def play_again?
  puts "Play again? (yes or no)".yellow
  answer = gets.chomp.downcase
  return answer == "yes"
end

loop do
  TicTacToe::Game.new
  unless play_again?
    puts "Goodbye".cyan.bold
    break
  end
end

(I renamed play_again to play_again?. It's conventional to use a question mark in names of methods that return a boolean)

Unbounded recursion 2

def turn
  @current_turn.even? ? move(@player2) : move(@player1)
end

def move(player)
  while !winning_scenarios && !tie
    # ...
    turn
  end
end

This recursion is not bounded either (it's not bounded by the number of spaces in the board, because a function call occurs for (rejected) invalid moves too). Use a loop instead:

def play_game
  # ...
  while !winning_scenarios && !tie
    turn
  end
  # ...
end

def turn
  @current_turn.even? ? move(@player2) : move(@player1)
end

def move(player)
  # ...
  # Don't call turn here
end

Object oriented design

class Board; ...; end

class Game < Board; ...; end

A game is not a board. A game has a board. Use composition instead of inheritance:

class Game # NOTE: Don't inherit Board
  def initialize
    @board = Board.new # NOTE
    play_game
  end

  def play_game
    # ...
    while !@board.winning_scenarios && !@board.tie
      turn
    end
    # ...
  end

  def move(player)
    # ...
    space_available = @board.check_space(choice, player.symbol)
    @current_turn += 1 if space_available
    puts "Player #{player.symbol}'s move:".green
    puts @board # NOTE
  end

  def tie_message
    ... if @board.tie
  end

  def win_message
    ... if @board.winning_scenarios
  end

  # ...
end

Note I moved @current_turn += 1 to Game. A game has a current turn, a board doesn't. Modify check_space so it returns a boolean.

Encapsulation

Make internal methods private, so they aren't visible outside the class:

class Board
  def initialize; ...; end
  def to_s; ...; end
  def check_space(cell, sym); ...; end
  def winning_scenarios; ...; end
  def tie; ...; end

  private

    WINNING_COMBOS = [
      [0, 1, 2], [3, 4, 5], [6, 7, 8],
      [0, 3, 6], [1, 4, 7], [2, 5, 8],
      [0, 4, 8], [2, 4, 6]
    ]

    def place_symbol(cell, sym); ...; end
      spaces[cell] = sym
    end
end

class Game
  def initialize; ...; end
  def play_game; ...; end

  private

    def move(player); ...; end
    def tie_message; ...; end
    def win_message; ...; end
    def turn; ...; end
end

Remove this line which exposes internal fields of Game: (you never actually use Game#symbol, by the way)

attr_reader :player1, :player2, :symbol

And this line from Board: (then change every occurence of spaces in Board to @spaces)

attr_reader :spaces

Board methods

def check_space(cell, sym)
  if @spaces[cell].nil?
    place_symbol(cell, sym)
  else
    puts "Space unavailable! Please select another cell"
  end
end

Single Responsibility Principle: Board should not do any printing, as it's not its core responsibility. It's better to return a boolean instead and let Game do the printing.
Naming: This method both checks if the space is free and places a symbol. Rename it to place_symbol_if_free.
Naming 2: Use position instead of cell to be consistent with other methods.
Consider splitting this to two methods: space_free?(position) and place_symbol(position, sym) (already exists) and then call both from Game.

WINNING_COMBOS = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],
  [0, 3, 6], [1, 4, 7], [2, 5, 8],
  [0, 4, 8], [2, 4, 6]
]

Put this inside winning_scenarios, the only method where it's used.

def winning_scenarios
  WINNING_COMBOS.each do |set|
    if @spaces[set[0]] == @spaces[set[1]] && @spaces[set[1]] == @spaces[set[2]]
      return true unless @spaces[set[0]].nil?
    end
  end
  false
end

Rename winning_scenarios to game_won?. Or to winner and return the winner's symbol
Use Array#any? instead of looping.
Use Array#map to obtain the symbols at the locations of a set, instead of repeatedly accessing @spaces.

Result:

def winner
  WINNING_COMBOS.any? do |set|
    symbols = set.map { |position| @spaces[position] }
    if symbols[0] == symbols[1] && symbols[1] == symbols[2]
      symbols[0]
    end
  end
end

def tie
  if !@spaces.include?(nil) && !winning_scenarios
    return true
  end
end

Rename to tie?, and simply return the boolean:

def tie?
  return !@spaces.include?(nil) && !winner
end

I also suggets extracting first part to a new private method full?.

to_s can be simplified by using functional programming. See my implementation of as_string in this answer.

Game methods

play_game

puts Board.new

Change this to puts @board.

while !@board.winner && !@board.tie?

Looks like Board is missing a game_over? method.

win_message
tie_message

These method names are misleading. Each one conditionally prints a message. Merge them to a single print_game_result method.

turn

def turn
  @current_turn.even? ? move(@player2) : move(@player1)
end

The call to move is duplicated because the method does two things: (1) determine who's turn it is (2) call move.

It's better to do only the first one:

def current_player
  @current_turn.even? ? @player2 : @player1
end

Then use move(current_player) in play_game.

move

def move(player)
  puts "Where would you like to move 'player #{player.symbol}'?".red
  choice = gets.chomp.to_i
  space_available = @board.check_space(choice, player.symbol)
  @current_turn += 1 if space_available
  puts "Player #{player.symbol}'s move:".green
  puts @board
end

I'd move the last two puts statements to play_game, because they're not part of making a move.

If you split check_space as I suggest earlier, you can make a loop that gets input until Board#space_free? returns true and then call Board#place_symbol. Otherwise, you'll have to rename this method to try_make_a_move.

initialize

Don't call game_play. Constructors should only initialize an object, and should not do IO. Instead, call game_play in the main code (TicTacToe::Game.new.play_game).

Further Improvements

Say who won.
Use digits 1 to 9 when printing the board and getting user input. It's hard to tell 0 and O apart.


Python script to query REST API and write to database

Some suggestions:

A linter (or two) such as pycodestyle or flake8 will help you write more idiomatic Python. For example, brackets are not required around an if statement.
You can use query_posts_response.json() to easily get JSON response content.
I can't see a reason why this script should do anything with the input and output streams.
db_connection.close() should be in a finally block. The try block should start with creating the connection.
If you ever intend to reuse the code it should be wrapped inside at least a main function (which orchestrates argument parsing, handling exceptions which should lead to non-zero return codes, and the like) and a separate function to do the work.


Filtering out objects in a CollectionViewSource

I find neither approach is acceptable.

The first one with the empty blocks only confuses. It lacks comments so you can never be sure whether there is something missing or intentionally left empty.

The second solution is also a bad one because it concatenates multiple conditions in a single giant if without any hint what they are actually testing.

To me maintainable and self-documenting code looks different. This means that instead of writing comments you should create a helper variable for each condition. You then can put them inside the if. Now it is self-explanatory and anyone can easily understand it (provided you pick really good names for the variables).

var documentCategoryFilterExists = (_selectedDocumentCategoryFilter?.PicklistStringId != 0);
if (documentCategoryFilterExists)
{
    var docToFilterMatches = (docToFilter.CategoryId == _selectedDocumentCategoryFilter.PicklistStringId);
    if (!docToFilterMatches)
    {
        return;
    }
}

I'm not saying that these variable names are perfect but without knowing your exact use case there's not much you can come up with based on only a few lines of code. But I think you know what I mean.

I still find this nested ifs aren't pretty... but at least they are less misterious now.

But this is how refactoring usually works. You change your code a find a new pattern that you can replace with an ever more efficient code. So the next step could be replacing the magic 0 with a constant and use the ? null operator in conjuction with ?? coalesce:

const int emptyPicklistId = 0;

var picklistStringId = (_selectedDocumentCategoryFilter?.PicklistStringId ?? emptyPicklistId);
var docToFilterMatches = (docToFilter.CategoryId == picklistStringId);
if (!docToFilterMatches)
{
    return;
}


Could this PHP Facebook class be any more OOP-ified?

This answer is in two sections.  Firstly I am going to cover the Object Oriented nature of your solution and suggest possible architectural changes.  Then I am going to look at your existing Code line by line for improvements.

Object Oriented

Your OO is good, you have nothing bad in there.

Here are some of the features of OO that you have used:

Data hiding (baseUrl property is private)
Encapsulation (use of private __apiCall to minimize interface for callers)

Lets have a look to see what other features you could use.

Now, what is your class?  It seems that it is a URL builder for the Facebook API.  You could think about creating a class that helps you with this URL building.  Let me pull one out of my hat now... (untested, only syntax checked)

class UrlBuilder {
   protected $baseUrl;
       protected $domain;
   protected $scheme;

   public function __construct($scheme, $domain, $baseUrl) {
        $this->baseUrl = $baseUrl;
        $this->domain  = $domain;
        $this->scheme  = $scheme;
   }

   /** Build a URL.
    *  @param rel   @string The relative offset from the baseUrl.
    *  @param query @array Associative array of query parameters.
    *  @return @string URL string.
    */
   public function buildUrl($rel, Array $query) {
       $url = $this->scheme . "://" . $this->domain . '/' . $this->baseUrl .
           $rel;

       if (!empty($query)) {
         $url .= '?' . http_build_query($query);
       }

       return $url;
   }
}

You will see from above that I use http_build_query (which is covered in the Code section of the review).

I left parameter checking out of this class to make this answer easier to read.  However you should definitely check each scalar parameter $scheme, $domain, $baseUrl, $rel.  Here is an example of how you would check $rel:

if (!is_string($rel)) {
    throw new InvalidArgumentException(__METHOD__ . 'rel must be a string');
}

So, how do we go about using this?  The common initial thought is the fantastic OO feature inheritance!  Raise your hand if you want to use inheritance.  Luckily from here I can't see any hands raised.  What would happen if we used inheritance (class Facebook extends UrlBuilder)?  We would open up the buildUrl method allowing any URL to be built with your Facebook object. This would be bad.  Why was inheritance a bad idea?  Because the Facebook object is not a UrlBuilder.  It is something that uses URL building.

The answer is composition.  We should pass the URL builder that we want to use into our constructor (generally I would use an interface, lets call it "UrlBuilderIface" and have class UrlBuilder implements UrlBuilderIface).  Using an interface allows us to keep the class loosely coupled.  We can accept any object that fulfills the contract defined by our UrlBuilderIface.  Here is the implementation with one method defined:

class Facebook {
    protected $urlBuilder;

    public function __construct(UrlBuilderIface $urlBuilder) {
            $this->urlBuilder = $urlBuilder;
    }

    public function searchPublicPosts($query) {
            if (empty($query) || !is_string($query)) {
            throw new InvalidArgumentException('query must be a non empty string.');
        }

        return $this->__apiCall($this->urlBuilder('search', array('q' => $query)));
    }

    private function __apiCall($url) {
            $raw = file_get_contents($url);
            return json_decode($raw, true);
    }
}

Note how there is checking for the passed in parameter to the method.  The check is simple, and it makes the rest of the code easy.  It is also easy to think about it completely separately from the other code (because you know that an exception will be thrown if the guard condition is met).

Usage becomes:

$facebookGraphUrlBuilder = new UrlBuilder('https', 'graph.facebook.com', '');
    $facebook = new Facebook($facebookGraphUrlBuilder);

Code

Some minor comments:

__apiCall should be named apiCall.  __ should be reserved for magic methods.
json_decode does not produce json, so you shouldn't create a variable from it called $json.
$json should never have even been a variable (A variable is for varying).  So you should return straight away, return json_decode($raw, true);

I am going to look at a single method because you have the same problems shared across your methods.

public function basicInfo($username){

        if($username !== ''){
                $url = $this->baseUrl . $username;
            }
            if($url !== ''){
            $data = $this->__apiCall($url);
            }
            return $data;

    }

Observe what would happen if $username was '':

First if does not match, so $url is not set.
Non-existent $url is used in second if causes E_NOTICE error.
Second if matches as NULL !== ''  (This is not good).
apiCall is made using NULL.
Badness continues.

Actually, similar or worse would happen if you used NULL an array, etc.

The bad thing here is the combination of your conditional setting of variables and later expectation that the variables have been set.  I would recommend solving this using a guard condition to ensure that the parameters to your methods are sane.  Trying to continue with the processing using if statements is quite difficult.  Throwing an exception may be the easiest:

if (!empty($username) || !is_string($username)) {
    throw new InvalidArgumentException('username required as a non-empty string.');
}

Everything can then be assumed to work:

return $this->__apiCall($this->baseUrl . $username);

Finally, there is a PHP function that helps you build the query strings that you use.  Here is the manual page for it: http_build_query


Counting Neighbors (Why scipy.signal.convolve2D so fast?)

You can change your algorithmic approach to improve your speed.

Currently:

look at every cell
lookup every neighbor-cell
write the number of neighbors

My proposition:
You start with a zero-ed nbrs_count array and look at every cell. If it's occupied, increase the nbrs_count of all neighboring cells (you will get a huge speedup if the array is mostly empty).

To prevent all your conditional statements, you can simply use a try: ... except: block, as suggested by @JoeWallis

Here is an implementation using my propositions:

import numpy as np

def neighbors_count(n2d_array, radii=1):
    assert n2d_array.ndim == 2

    nbrs_count = np.zeros_like(n2d_array)

    # array of adjacents cells
    adjacents = []
    for i in range(-radii, radii + 1):
        for j in range(-radii, radii + 1):
            if j != 0 or i != 0:
                adjacents.append((i,j))

    for (row_idx, col_idx), value in np.ndenumerate(n2d_array):
        if value:
            for i, j in adjacents:
                try:
                    if row_idx + i >= 0 and col_idx + j >= 0:
                        # because a negative index doesn't fail
                        nbrs_count[row_idx + i, col_idx + j] += 1
                except IndexError:
                    # We are outside the array
                    pass

    return nbrs_count

This solution is about 5 times faster than the original code (which is still way slower than scipy)


Main is just a driver program. Separate it from the implementation class.
If the called function throws an exception , someone has to handle it. Check who should do it and log some helpful message.
Variable name temp , temp2.
Could we guarantee that user!=null or temp!=null or it may not contain a null status i.e check for user!=null , temp!=null and status!=null.
No hard-coded value.
Make the twit extraction implementation generic for any pageSize, any user, i.e take that as input parameters or member variable and feed on it.
Since the Twit extraction API may be called by anyone, so have the username correction logic there itself.
Limit the printlns for debugging purpose only.


Singleton class extending a parent class to utilise shared functionality

As others mentioned the getSingletonObject should be synchronized. There is a chapter in Effective Java, Second Edition about singletons (Item 3: Enforce the singleton property with a private constructor or an enum type). It's worth to read. Anyway, try to avoid them, they makes testing really hard.

You use the Timer as a single-threaded executor. In that case consider using Executors.newSingleThreadExecutor. Furthermore, are you sure that you need to pass Thread at all? Wouldn't Runnable be enough? Executors can run Runnables without any wrapper class and Thread.join call.

Instead of catching IllegalStateException in the runThread method you should check whether the timer is canceled. You can store this state in a boolean flag. Don't forget to synchronize the variable access. (See Effective Java, Item 57: Use exceptions only for exceptional conditions)

ExecutorService.submit returns Future which has a cancel method. Maybe it's better for you requirements (instead of Timer.cancel()).

If you're not familiar with concurrent code check Java Concurrency in Practice.


Service layer for course student registration

you can write fluent extension methods:
 public static class Extensions {
     public static T EnsureNotNull<T>(this T t, string message = null) {
         if (t == null) throw new StudentCourseValidationException(message ?? "Value not found");
         return t;
     }
     public static Student EnsureAlreadyRegistered(this Student student, string courseId) {
          if (student.Enrollments.Any(x => x.CourseId == courseId) throw new StudentCourseRegistrationException("Student is Already Registered for Course");
          return student;
      }
      //and so on
 }

then your code would look like:
public async Task<bool> RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent)
    {
        var student = await _studentRepository.GetStudentInformationAsync(registerStudent.StudentId);

        student
              .EnsureNotNull()
              .EnsureNotAlreadyRegistered(registerStudent.CourdeId)
              .EnsureCanHaveMoreCourses();

        var course = _courseRepository.GetCourseInformation(registerStudent.CourseId);

        course
             .EnsureNotNull()
             .EnsureNotFullyBooked();

        return await _courseRepository.SaveRegisterationOfStudentForCourse(course, registerStudent, student);
    }
}