SPOJ "TESSER" - Getting TLE using KMP algorithm

Before addressing your performance problem, I'd like to discuss the readability of your code:

It's not immediately obvious that there are T test cases, all independent of each other.  while (test_case) { …; test_case = test_case - 1; } would be clearer if written as

while (test_case--) {
    …
}

All of the variables used in each test case (text, pattern, v, etc.) should be declared inside the loop, to make it clear that no state persists between cases, other than the test_case counter.  That would be less error-prone than calling .clear() to reuse the vectors.

Better yet, define a helper function for handling one test case.  Then it will be obvious that there should be no side-effects.
What is flag?  Flag variables, especially poorly named ones, are a code smell.  At the very least, rename it to pattern_found.

For a program whose main functionality is performing a substring search, it is baffling that nothing like a find(needle, haystack) function appears in your code.  That would be a more appropriate fix for your flag variable.
no is a weird name for an integer variable, yes?
Why bother building v and throwing it away?  You could just construct text directly.

In addition, there are some abuses of C++.

#include <bits/stdc++.h> is not standard C++.
using namespace std defeats the benefits of the namespace, and is not recommended.
Declaring vector<int> computePrefixFunction(string p) inside your main() function is highly unconventional.  Declarations usually go before the function or in a header file.  Better yet, put if you put main() at the end, you won't even need any declaration.
computePrefixFunction(string p) should accept a const std::string & — otherwise you end up copying the string.

I would drop "compute" and "function" from the function name, since those words don't contribute to the meaning.

I recommend the following outline for the code.  Note that you can replace the call to kmpFind() with std::string::find() and still get the same answer (though not necessarily with the right performance characteristics).

#include <iostream>
#include <string>
#include <utility>
#include <vector>

static std::vector<std::string::size_type> kmpPrefixTable(const std::string &w) {
    std::string::size_type candidate = 0;
    std::vector<std::string::size_type> t;
    t.reserve(w.length());
    for (std::string::size_type pos = 2; pos < w.length(); ) {
        …
    }
    return t;
}

/**
 * https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm
 */
std::string::size_type kmpFind(const std::string &s, const std::string &w) {
    std::vector<std::string::size_type> t = kmpPrefixTable(w);
    for (std::string::size_type m = 0, i = 0; m + i < s.length(); ) {
        …
    }
    return std::string::npos;
}

/**
 * Reads a test case, expecting:
 * 1) the number of data points (2 <= n <= 1e5),
 * 2) the sequence of data points (space-separated integers, each up to 1e9),
 * 3) the pattern to look for (a string consisting of letters 'G', 'L', and 'E').
 *
 * Returns the sequence (represented as a string, using 'G', 'L', 'E' to
 * represent an increase, decrease, or equality relative to the preceding
 * number), and the pattern to look for.
 */
std::pair<std::string, std::string> tesserect(std::istream &in) {
    size_t n;
    uint32_t prev, curr;
    std::string s, pattern;

    std::cin >> n;
    s.reserve(n);
    for (in >> prev; --n; prev = curr) {
        in >> curr;
        s += (curr < prev) ? 'L' :
             (curr > prev) ? 'G' : 'E';
    }

    in >> pattern;
    return std::make_pair(s, pattern);
}

int main() {
    int testCases;
    for (std::cin >> testCases; testCases; --testCases) {
        std::pair<std::string, std::string> strings = tesserect(std::cin);

        // Equivalent to: pos = strings.first.find(strings.second);
        std::string::size_type pos = kmpFind(strings.first, strings.second);

        std::cout << (pos != std::string::npos ? "YES\n" : "NO\n");
    }
}

Now, with the Knuth-Morris-Pratt algorithm moved into its own function, you can test and analyze it properly.  You seem to be using a variant that is different from the algorithm given in Wikipedia.  The version in Wikipedia doesn't use nested while loops — you may find it easier to analyze its performance.


Solution to the CodingBat Array-3 [fix34]

It can easily be done in O(n) i.e a single loop traversal. Think simple .Modify the below program to suit your understanding and find the algorithm in the comments.
Just a brief:

Traverse the array from 0 to get the first position where you meet 3 say curIdx. Now you know that curIdx+1 can be replaced.
Traverse the array from the last to get the last position of 4, say lastIdx. Now you know that lastIdx can be replaced.
Swap curIdx and lastIdx if its within the array's range.

void reArrange(int[] arr)
{

int[] arr = {2, 3, 5, 3, 2, 4, 4};
int lastIdx = arr.length-1;
int curIdx= 0 ;
while(true){ //I know when to exit. Trust me!!!
    // Where art thou my 3. I need to replace the index after you.
    while(curIdx<arr.length && arr[curIdx]!=3){
        curIdx++;
    }
    curIdx++;

    // Gotcha Mr 4. You need to lead 3 safely.
    while(lastIdx>0 && arr[lastIdx]!=4){
        lastIdx--;
    }

    // As I said, trust me and I will help you exit
    if(curIdx>=arr.length || lastIdx<=0){
        break;
    }

    // Swap Time to rearrange Mr 4's after 3.
    int temp = arr[curIdx];
    arr[curIdx] = arr[lastIdx];
    arr[lastIdx] = temp;
}

// Did I do it correctly? Lets check.
for(curIdx=0;curIdx<arr.length;curIdx++){
    System.out.print(arr[curIdx] + "  ");
}

}

Note:

I am rearranging the 4's after 3's without considering the order.
I assume that the input meets the constraints provided.


If you collect the indices along with the duplicates, you don't need to loop over the list again:

var header = new List<string>();
var duplicates = header.Select((x, index) => new { x, index }).ToLookup(x => x.x, x => x.index);
foreach(var duplicate in duplicates.Where(x => x.Count() > 1)) {
  var start = 1;
  foreach(var index in duplicate) {
    header[index] = $"{duplicate.Key}{start++}";
  }
}

This uses string interpolation ($-strings) as a shorthand for string.Format.

On premature optimisation:

You seem concerned about the \$O(n^2)\$ performance of your solution. At the same time you mention your actual input will have ~30 items. Before spending too much time worrying about the efficiency of your code, did you try to find out whether your current solution is problematic? It seems to me that the list is small enough that even a less efficient solution should be quick enough.

Before trying to optimise specific parts of your code, ask yourself two things:

Do I need to optimise? Is execution time currently a problem?
Where is the efficiency problem in the code?

Before optimising, profile your program to figure out where the problems actually are. Before that, efficiencies like  \$O(n^2)\$  or \$O(n \log n)\$ are purely academic.


Here is another version with guard clauses:

private void setupListener(final ImageView image, final String platform,
        final String urlLink) {
    image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!platform.equalsIgnoreCase(PLATFORM_ANDROID)) {
                startInBroswer();
                return;
            }

            final String packageName = extractPackageName(urlLink);
            if (packageName == null) {
                startInBroswer();
                return;
            }

            try {
                final Intent market = new Intent(Intent.ACTION_VIEW);
                market.setData(Uri.parse("market://details?id=" + packageName));
                activity.startActivity(market);
            } catch (final Exception e) {
                // TODO: log the exception
                startInBroswer();
            }
        }

        private void startInBroswer() {
            final Intent browser = new Intent(Intent.ACTION_VIEW,
                Uri.parse(urlLink));
            activity.startActivity(browser);
        }
    });
}

Two things to notice:

I've removed the urlLink parameter of the startInBroswer method.
It is a bad idea to use printStackTrace() in Android exceptions.


Similar statements need duplication removed

I am not sure your quest for de-duplication is warranted,
the only approach I know of is this:

DECLARE @city VARCHAR(10)
DECLARE @status INT

SELECT c.Name, c.Phone
FROM Customers c
WHERE c.City = @city
AND c.Status = @status
AND ( ( c.Status = 5 )
OR    ( c.Status = 10  AND c.SignUpDate NOT IN (EXEC ExpensiveQuery) ) )


Generate all possible unique combinations of positive numbers these have sum equal to N

Review
Your code is a good simple solution. The style is sloppy. The complexity is a bit high and the techniques uses are negatively impacting performance.
The template literal call  Array.split`+` always throws me, but I like it, your code reminds me to use it more often.
General points

Delimit all code blocks. Eg   if(n==0) return ["0"] better as if(n==0) { return ["0"] }
Why? JavaScript like most C style languages do not require delimited blocks for single statement blocks, however when modifying code it is very easy to over look the missing {}.

Use semicolons or be thoroughly familiar with automatic Semicolon Insertion (ASI)

Rather than use continue consider using the statement  } else {
Why? continue breaks the use of indentation that visually helps you see flow in a glance. continue and its friend break should be avoided when possible.

// Avoid using continue to skip code

for (a of list) {
    if (foo) {
        ...do something...
        continue;
    }
    ...lots of code...
}

// Rather use an else statement

for (a of list) {
    if (foo) {
        ...do something...
    } else {
        ...lots of code...
    }
}

Spaces between operators i>=n/2|0 should be i >= n / 2 | 0

When using short circuit expressions (f(n) || []) use the Nullish coalescing operator
?? eg f(n) ?? [] in rather than logical OR ||

In the two inner loops you recurse with the call to (f(n) || []). The function f() always returns an array so there is no need for || []

In the most inner loop you recurse on f(i) for every x but f(i) is the same for every x. This is forcing a lot of redundant processing.
Always move calculations to a level that is One = One, rather than One = Many to avoid unnecessary overhead.
Your inner loop

for(let i=n; i>=n/2|0; i--){
  if(i==n){
    result.push(n + "+0")
    continue
  }
  for(const x of (f(n-i)||[])) {
    for(const y of (f(i) || [])) { //  repeated call to f(i)
      result.push(y + "+" + x)
    }
  }
}

Example of moving the recursive call out of the inner loop
for (let i = n; i >= n / 2 | 0; i--) {
    if (i === n) {
        result.push(n + "+0");
    } else {
        const solvedForI = f(i); // called once only
        for (const x of f(n - i)) {
            for (const y of solvedForI) {
                result.push(y + "+" + x)
            }
        }
    }
}

Tips
Bit-wise divide and floor
Using | 0 to floor Numbers is a handy short cut, But you can divide by a power of 2 and floor in one operation.
Example n / 2 | 0 is the same as n >> 1. For every left shift you divide by 2 and for every right shift you multiply by two.
(n / 2 | 0) === (n >> 1)
(n / 4 | 0) === (n >> 2)
(n / 8 | 0) === (n >> 3)
(n / 256 | 0) === (n >> 8)

Note that the conversion to uint32 happen before the shift, thus multiplying is not equivalent. Eg 1.5 << 1 === 2 and 1.5 * 2 | 0 === 3

Note Bitwize operations convert to unsigned int 32 and thus should only be used for only for Numbers in the range \$-(2^{31})\$ to \$2^{31} - 1\$

Cache
You can use a cache to store the results of a function. For recursive functions this can save a lot of processing.
Pseudo code example of a cache
For positive integer values you can use an Array, For other types of arguments you would use a Map
// n is a positive integer
function solution(n) {     // wrapper
    const cache = [];
    return recurser(n);    // call recursive solution.

    function recurser(n) { // n is a positive integer
        var result;
        if (cache[n]) { return cache[n] }  // Return cache if available

        while ( ) {
            ...
            recurser(n - val);

            /* Some complicated code that adds to result */

            ...
        }

        return cache[n] = result;
    }
}

Complexity, Performance, & Example
TLDR
The next part of the answer addresses performance and complexity and how both can be improved with example function.
As the example is a completely different different approach It is not considered a review (rewrite) however the some of it can be used in your solution.
Complexity
Your complexity is in the sub-exponential range \$O(n^{mlog(n)})\$ where \$m\$ is some value >= 2. This is rather bad. The example reduces complexity by reducing the value of \$m\$.
Performance
Performance is indirectly related to complexity. You can increase performance without changing the complexity. The gain is achieved by using more efficient code, rather than a more efficient algorithm.

Example
The example is a completely different algorithm but some of the techniques can be applied to your solutions, such as the cache and moving the check for found combinations out of the recursing function.
Addressing complexity
I could not modify your algorithm to improve the complexity, this is not due to the not being an less complex algorithm bases on your approach, just that I was unable to find it.
Addressing performance
There is a lot of room to improve performance via caching, strings, sorts, and stuff
Cache
The example uses a cache to reduce calculations. See above Tips regarding cache.

Note the cache is set up to contain the result of n 0 to 2 which is equivalent to your first 3 if statements.

Strings
To avoid duplicates you use a Set and because two array containing the same values are not the same, you convert the array to a string that can uniquely identify the array content.
However you are manipulating the strings in the inner loops and convert from string to number and back each recusing iteration.
Using the approach of wrapping the recursive function we can avoid the conversion within the main solutions and use the set to filter duplicates once just before returning the final result.
Sort
Though the sort is not a major part of the complexity, it is where I started when doing the example.
Each iteration adds only one value to the arrays being built. By maintaining the correct order as we go the sort can be avoided completely and we just build the array inserting the new element at the correct position.
The inner most for (const v of sub) { loop does this inserting the new value to each the  sub arrays returned by the previous recursive solution.
Code Comparison
To gauge the performance and complexity I ran your code as the base and used its results to test the examples correctness.
I then added counters to both counting every countable iteration, including under the hood iterations such as those performed by spreads ..., array map and reverse, string concats, sorts, etc.
The results as follows
Counted iterations per tested n value

n value
7
8
9
10
11
12
13
... 18

Your code
4,834
14,179
36,630
101,818
268,192
733,260
1,947,968
277,569,323

Example
333
718
1,584
3,418
7,445
16,018
34,528
1,503,242

Note The example results may not look that bad as n increases, however it is still in the same complexity range of \$O(n^{mlog(n)})\$. All I have managed to do is lower \$m\$

Note To match your result I had to add a Array.reverse to the final combinations. The reverse was counted but is not required.

function combos(n) {
    const cache = [[], [[1]], [[2], [1, 1]]];
    return [...(new Set([...combo(n).map(v=>v.reverse().join`+`)]))];

    function combo(n) {
        var a = n - 1, b, insert;
        if (cache[n]) { return cache[n] }

        const res = n % 2 ? [[n]] : [[n], [n >> 1, n >> 1]];
        while (a > n - a) {
            b = n - a;
            for (const sub of combo(a--)) {
                const subRes = [];
                insert = true;
                for (const v of sub) {
                    v > b || !insert ? subRes.push(v) : (insert = false, subRes.push(b, v));
                }
                insert && subRes.push(b);
                res.push(subRes);
            }
        }
        return cache[n] = res;
    }
}


To generate those nested, nearly identical setTimeout calls, instead of coding them all manually you could have a recursive function that builds and returns a function for you. Something like this would work:

// Accepts an array of elements and a final callback function
// Returns a function to show all elements and execute the callback
function getFunctionToShowElements(elements, callback, currentIndex) {
    var i = typeof currentIndex === "undefined" ? 0 : currentIndex;
    if (i === elements.length) {
        // after the final element, call the callback
        return function () {
            callback();
        };
    } else {
        // for any preceding element, show the element and call a timeout
        var nextMethod = getFunctionToShowElements(elements, callback, i + 1);
        return function () {
            elements[i].fadeIn();
            setTimeout(nextMethod, 1000);
        };
    }
}

Then you could set up a function for creating audio objects and attaching the event listener to fade in the given elements.

function createAudio(filename,elements){
    var audio = new Audio(filename);
    audio.addEventListener("ended",function(){
        getFunctionToShowElements(elements,function(){sprite.play();})(); // get the function and execute it immediately
    });
    return audio;
}

At this point you'll be able to create an audio object with the desired event handler like so:

var audio = createAudio("audio/test.mp3",[element1,element2,element3]);

That's just to give you an idea of how you could go about cleaning it up.

There are other improvements you'd want to make in your final code, such as using a variable for the timeout delay, and wrapping up the relevant code sections in closures as necessary. We'd need to see the full code to identify other areas for improvement.

Proof that the concept works:

var els = document.querySelectorAll(".showme");
var sprite = {
    play: function () {
        alert("sprite.play");
    }
};
createAudio("audio/test.mp3", els);

function createAudio(filename, elements) {
    var audio = document.querySelector("button"); //new Audio(filename);
    audio.addEventListener("click", function () {
        getFunctionToShowElements(elements, function () {
            sprite.play();
        })();
    });
}

function getFunctionToShowElements(elements, callback, currentIndex) {
    var i = typeof currentIndex == "undefined" ? 0 : currentIndex;
    if (i === elements.length) {

        return function () {
            callback();
        };
    } else {

        var nextMethod = getFunctionToShowElements(elements, callback, i + 1);
        return function () {
            elements[i].style.display = "inherit";
            setTimeout(nextMethod, 1000);
        };
    }
}
.showme {
    background-color:red;
    display:none;
}
<button>Click me</button>

Number 1

Number 2

Number 3

Number 4


Keep classes anonymous in TicTacToe program

def setup_board
  @gameboard = []
  9.times { @gameboard << " " }
end

Can just be:

@gameboard = Array.new(9){ " " }

It is idiomatic in Ruby to omit parentheses when not needed, e.g. display_board instead of display_board().

def winner?(player_score)
  WINNING_SCORES.each do |score|
    return true if player_score & score == score
  end
  false
end

Instead:

def winner?(player_score)
  WINNING_SCORES.any?{ |score| player_score & score == score }
end

(I'm trusting that the bitwise AND logic you have there is correct.)


Program to see how many points lie strictly inside a convex polygon

Data types

Why not use a simple point struct instead of std::pair<int, int>? It doesn't have to do anything, just a simple one would suffice:

struct point {
    int x = 0;
    int y = 0;
};

This would increase readability and generally might make the code more bug resistent. Remember, std::pair<int, int> can represent many different things: points, vectors, health + mana points, entry in a std::map<int, int> (which by itself can have many different meanings), exchange rate of apples for oranges, ...

Using a concrete type prevents that kind of confusion.
Similarly, one could make a type alias polygon for std::vector<point>, like

using polygon = std::vector<point>;

  A more advanced implementation could instead take a polygon as a range of points (= a pair of iterators), or use its own polygon class.

perdot

The name doesn't match what it actually does. Yes, the perpendicular dot product is used internally, but the returned value isn't the result of it. The returned value only indicates whether the point is left of, right of or on the line - and the function name should reflect that, e.g. something like determine_side.
The return values seem kinda arbitrary. Why not use an enum instead, like

enum class side {
    left,
    right,
    center
};

The order of the parameters seems kind of arbitrary and unintuitive. Why do the points of the "line" have to be passed as first and third parameter? With a simple help from the type system, this could be clarified a lot by introducing a small line helper struct:

struct line {
    point from;
    point to;
};

Putting all those fixes together (and refactoring the perpendicular dot product into its own helper function), we get:

int perpendicular_dot_product(point a, point b, point c) noexcept {
    const auto ab_x = b.x - a.x;
    const auto ab_y = b.y - a.y;
    const auto ac_x = c.x - a.x;
    const auto ac_y = c.y - a.y;

    return ab_x * ac_y - ab_y * ac_x;
}

side determine_side(line l, point p) noexcept {
    const auto per_dot = perpendicular_dot_product(l.from, p, l.to);

    if(per_dot < 0)
    {
        return side::right;
    }
    else if(per_dot > 0)
    {
        return side::left;
    }

    return side::center;
}

Much nicer to read and much clearer in its intent, right?

is_convex

Bug: If n <= 2 then the code likely doesn't work as intended, and might even access out of bounds memory. Please add checks for those cases.

  Now the question becomes: What should happen in those cases? Always return false, or throw an exception?

  I think always returning false would be better in this case, since it is just a query whether the contained data set conforms to some criteria. YMMV.

Also, there is another edge case if all points in convex_polygon are on a line. Currently, is_convex returns true for that case, but is this intended? I wouldn't assume so.

Other than that, it seems to be working fine. It would need some adjustments for the changes mentioned above, though, and could be slightly simplified.

bool is_convex(const polygon& convex_polygon) noexcept
{
    const auto n = convex_polygon.size();
    if(n <= 2) return false;

    auto sense = side::center;

    for(auto i = 0u; i < n; ++i)
    {
        auto new_sense = determine_side(line{convex_polygon[i], convex_polygon[(i + 2) % n]}, convex_polygon[(i + 1) % n]);

        if(sense == side::center)
        {
            sense = new_sense;
        }
        else if(new_sense != side::center && new_sense != sense)
        {
            return false;
        }
    }

    return sense != side::center;
}

is_inside

Not much to do here, other than adjusting for above changes and some slight simplification.

bool is_inside(const polygon& convex_polygon, const point p) noexcept
{
    const auto n = convex_polygon.size();

    const auto sense = determine_side(line{convex_polygon[n - 1], convex_polygon[0]}, p);
    if(sense == side::center)
    {
        return false;
    }

    for(auto i = 0u; i + 1 < n; ++i)
    {
        auto new_sense = determine_side(line{convex_polygon[i], convex_polygon[i + 1]}, p);

        if(new_sense != sense)
        {
            return false;
        }
    }
    return true;
}

p_inside

Again, the name is weird: Why not use count_points_inside?

Other than that, the logic seems fine. It could however easily be simplified using an algorithm provided by the standard library: std::count_if (inside header <algorithm>).

int count_points_inside(const polygon& convex_polygon, const std::vector<point>& points)
{
    return std::count_if(std::begin(points), std::end(points), [&](auto p) { return is_inside(convex_polygon, p); });
}

  Note how I didn't replace the type of points with polygon and used a std::vector<point> instead, since (at least for the human reader) there is a semantic difference between a polygon and a set of points.

  A better version would takes points as a range of points instead:

template<typename Iter, typename = std::enable_if_t<std::is_same_v<point, typename std::iterator_traits<Iter>::value_type>>
int count_points_inside(const polygon& convex_polygon, Iter first, Iter last)
{
    return std::count_if(first, last, [&](auto p) { return is_inside(convex_polygon, p); });
}

  (The typename = std::enable_if_t<...> part is only there to verify that the passed iterators point to points. The code would work without that.)

main

Errors should be printed to std::cerr instead of std::cout.
Some better instructions for the user would be nice. Currently, the user only ever gets notified if something goes wrong and thus has no clue what actually is expected of him.
The entering procedures of convex_polygon and points could be refactored out into a helper function, since the logic overlaps quite a lot.
In the error case, a different return value should be used, like 1 (or EXIT_FAILURE from the <cstdlib> header, to be more descriptive) in order to indicate that the program didn't execute as planned.
The final return 0; statement could be removed, as the compiler will autogenerate that one. (If it isn't removed, EXIT_SUCCESS could be returned instead as a more descriptive value).

Q & A

Generally, I try to pass everything but containers (including classes that contain containers as data members) and non-copyable types by value as default. I only switch to references if I either know that the type is very large, or performance measurements show that passing by reference is a performance benefit.

If in doubt, measure.
const is used well for function parameters. However, local variables that aren't being changed can also benefit from being marked const (see snippets above, e.g. for perpendicular_dot_product).
See above. Other than that, some functions like perpendicular_dot_product or determine_side could be made constexpr, as esote mentions in his answer. This would allow the compiler to precalculate those calls at compile time if the values are known.
I'd suggest trying test-driven development (i.e. write test before writing the actual implementation). Other than that, know your edge cases, and test those specifically (that way, you're unlikely to get bugs like the ones in is_convex).


Iterate JSON GIF collection array to HTML file

There aren't many things wrong. And the code itself is surprisingly short. But this will be a really long review.

The first thing that bothers me is that you talk about JSON, but you show an object. That's fine, but you should show how you decode the JSON into that object. But, within the scope of this review, I'll refer to it as an object, which is what was presented. Not to mention that all the links point to .jpgs.

Now, lets tackle the code!

Javascript:

The indentation of that object is really off. Not to mention that you have mixed quote styles.

Each gif has the following:

{
    "gifName" : "gif-One",
    "gifLink" : "http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg"
}

We know those are gifs, so, why repeat gif in every single property? Using just name and link is enough.

And you don't even use the gifName anywhere! So, just drop it! And just to have there to say it is gifs, you can remove it and just use an array.

The whole object can be something like this:

var gifCollection = [
    'http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg',
    'http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg',
    ' ... '
];

Notice that you have to use " instead if you are using this in JSON! As I refered earlier, I would review it as an object.

Looking a little below, you have this line:

var div = document.getElementById('#vids');

Well, that won't work. What you have there is a CSS selector. Fear not, just remove the #. But a few lines below you have this:

//div.innerHTML = div.innerHTML + '';

It seems like you made an attempt, but it didn't worked. Since these 2 lines aren't doing anything, just remove them.

Anyway, you are using jQuery below!

Right after it, you have this block:

for (var i in gifLink) {
    var src = gifLink[i].gifLink;
    //alert(gifLink.gifLink);
    console.log(src);
    //div.innerHTML = div.innerHTML + '';
    $("#vids").append('

');
}

These comments contain old code. Just remove them! They won't kill you. And that console.log can go away as well, since it isn't useful to make the code work. It may be in debug.

But wait! You have this line:

$("#vids").append('

');

Oh no! You are creating duplicated ids! They MUST be unique! Or that will be invalid HTML. Use a class instead. Also, don't be afraid of using the id videos. No one will die over 2 bytes. And it is way more clean.

Since I've suggested to change the structure of your object, you have to use a different for loop. Applying the changes above explained, and fixing the quotes:

for (var i = 0, length = gifCollection.length; i < length; i++) {
    var gif = gifCollection[i];
    $('#videos').append('

');
}

I've kept the length there because it will speed up your code quite a lot. Speaking in 'speeding up', you are re-running $('#vids') per gif. Just store it into a variable. Like this:

var videos = $('#videos');
for (var i = 0, length = gifCollection.length; i < length; i++) {
    var gif = gifCollection[i];
    videos.append('

');
}

Now you won't be running jQuery everytime and it will be way faster!

Putting your Javascript code all together:

var gifCollection = [
    "http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg",
    "http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg",
    " ... "
];

var videos = $('#videos');
for (var i = 0, length = gifCollection.length; i < length; i++) {
    var gif = gifCollection[i];
    videos.append('

');
}

HTML:

The HTML is pretty basic, but there's still plenty to improve. Lets look at it on it's original state:

Alright, you have a .container which has a .video which has #vids inside? What? Videos inside a video?

What I would do:

Remove .video. It's useless there.
Change the id to videos
Give the class row to the container.
The container is the one that will control the width of your #videos.
It makes sense to set it this way.
Closing videos in the same line
Since you are using jQuery, later on you may want to use the pseudo-selector :empty, which won't work if you have newlines in it.

Applying all the changes:

And yes, it works just like the old HTML.


Displaying unique objects generated by Raphael.js in FancyBox

Well you could author a jQuery plugin. That would have default settings, with the option of passing some parameters and override settings.

General ideas behind this are :

Making reusable code. Another project with similar stuff? You include the lib and re-use it.
Making the code as dry as possible. Writing the same thing again and again is annoying and hard to refactor. In a plugin everything is wrote once.
Even though you want everything to look the same, you have to build it a way you can override default setting, because there's always one object that need to be different.

I haven't debug the whole  plugin as I had no idea what did a paper object looked lik. But it seemed like it was a jQuery built object as you called .attr, .mouseover and .mouseout which are jQuery function. Though I have debugged the rest of the plugin without calling .path and it was working.

To call the plugin just do something like :

var basePath = 'img/rzuty/p1/';
paperObject.animatePath('M36.146...', 101, basePath);
paperObject.animatePath('M337.583...', 102, basePath);
//...

So the plugin code looks like that :

(function ($) {
    /**
     *
     * @param path the paper path
     * @param imageNumber the image number which is used in href and pdf and for the id
     * @param basePath the base path for the image
     * @param options option to override defaults settings
     */
    $.fn.animatePath = function (path, imageNumber, basePath, options) {

        //Default settings
        var defaults = {
            htmlAttr: {
                'class': 'reserved',
                    'id': 'ap_' + imageNumber
            },
            cssOptions: {
                fill: '#d3ae6b',
                    'stroke-width': 0,
                    'fill-opacity': 0.5,
                stroke: 'transparent',
                cursor: 'pointer',
                title: imageNumber
            },
            fancyboxOptions: {
                href: basePath + imageNumber + '.jpg ',
                openEffect: 'elastic',
                openSpeed: 150,
                closeEffect: 'elastic',
                closeSpeed: 150,
                padding: 2
            },
            fancyboxAnimations: {
                beforeShow: function () {
                    $('')
                        .appendTo(".fancybox-inner");
                }
            },
            mouseOver: function () {
                $(this).animate({
                    'fill-opacity': 0.8
                }, 200);
            },
            mouseOut: function () {
                $(this).animate({
                    'fill-opacity': 0.5
                }, 200);
            }

        };

        //Merge settings
        var settings = $.extend(true, defaults, options || {});

        //Add the fancybox and stuff
        this.path(path)
            .attr(settings.htmlAttr)
            .css(settings.cssOptions);
        this.click(function () {
            $.fancybox.open([settings.fancyboxOptions], settings.fancyboxAnimations);
        });
        this.mouseover(settings.mouseOver);
        this.mouseout(settings.mouseOut);

        return this;
    };
})(jQuery);

As you can see every default settings is defined in an object and you can override it by passing it in the options object (which is then merge recursively with the defaults object). The nice thing is that it is now easily reusable. Also, using function($){}(jQuery); enclose the function scope so that it doesn't clash with any other library using $.

Here is a link to a fiddle, be free to update it with the paperObject, because I couldn't do it not knowing what it was.

To learn more about jQuery Authoring.


Largest substring which starts and ends with some substring

You should use str.startswith and str.endswith and avoid reinventing them with list slicing.

The conditions can be simplified: if the string does not start with the substring remove the first char if it does not end with the substring remove the last.

Space complexity can be reduced by passing indexes to the recursive invocations instead of copies of the string.


Proportional sorting of web scrape results

I don't really understand what your code is supposed to do but I can see some room for improvement so let's go!

Style

Your code looks good and PEP 8 seems to be respected. I find the spacing in the argument lists a bit unusual but he... Also, your functions probably deserves some documentation like docstrings for instance.

Improvements

domain = '' is not needed here.

In :

    random.shuffle(sublist)
    if len(sublist) in matrix:
        matrix[len(sublist)][domain] = sublist
    else:
        matrix[len(sublist)] = {}
        matrix[len(sublist)][domain] = sublist

You don't need to call len over and over again.

    random.shuffle(sublist)
    leng = len(sublist)
    if leng in matrix:
        matrix[leng][domain] = sublist
    else:
        matrix[leng] = {}
        matrix[leng][domain] = sublist

Then, you could remove the duplicated logic :

    random.shuffle(sublist)
    leng = len(sublist)
    if leng not in matrix:
        matrix[leng] = {}
    matrix[leng][domain] = sublist

But the part with the test and the empty dict could be done automatically with defaultdicts.

In :

def proportional_sort( urls ):
    doms = [get_domain(url[0]) for url in urls]
    dom_set = set(doms)

    matrix = {}
    for domain in dom_set:
        sublist = [item for item in urls if get_domain(item[0]) == domain]

it seems like you are using the wrong data structure. You want to iterate over domains only and only once and then process the corresponding urls. It would be better to define a dictionnary mapping domains to list of urls once so that you don't have to call get_domain many times in many places. You have different ways to do this, the best involves setdefault :

dom_dict = {}
for url in urls:
    dom_dict.setdefault(get_domain(url[0])).append(url)

Then, your code becomes (not tested):

matrix = {}
for domain, sublist in dom_dict.iteritems():
    random.shuffle(sublist)
    leng = len(sublist)
    if leng not in matrix:
        matrix[leng] = {}
    matrix[leng][domain] = sublist


Rotating lists in linear time and constant space (Java)

The time complexity of the rotate method is O(N^2) if the list doesn't support random access because each call to swap takes O(N) time. One can fix it by using two ListIterators (one going forward and one going backwards) to reverse a part of the list.
There's no need to create separate rotateLeft and rotateRight methods. You can always take the shift modulo the size of the list (in mathematical sense, without negative results, not in a sense of the operator %) instead.


Remove useless whitespace from styled string

The answer is to put the newlines at the start of each line, directly before the text.

<string name="about_text"><big><b>About</b></big>
    \nLorem ipsum dolor sit amet and all that stuff...
    \n\nMore stuff.
</string>

Therefore all the redundant whitespace appears at the end of each line (e.g. after "About") where it doesn't affect the appearance of your text.


To be honest, your original implementation of cancelBills looks pretty good - it's very focused and is fairly easy to understand what it's doing even without much context.
If you really want to write the function as a single chain of functions then your alternative version is most of the way there. I'd consider replacing the last three functions in the chain with a single Result.asyncBind function to simplify it somewhat, i.e.
module Result  =
    let asyncBind (asyncBinder: 'T -> Async<Result<'U, 'TError>>) (result: Result<'T, 'TError>) =
        match result with
        | Result.Ok value -> asyncBinder value
        | Result.Error error -> async { return Result.Error error }

This is effectively just an async equivalent of the built-in Result.bind, so shouldn't add much overhead when reading the code and should be fairly re-usable if you're piping Result and Async around a lot. That being said, if you're not going to be re-using Result.asyncBind (or your equivalent function chain) then just stick with your original implementation of cancelBills!


Really you don't need DR to be stored as it's a user convenience. That is you can add DR when extracting the value. You also don't need to check calculate the next number as SQlite can do this on your behalf.

To further elaborate if DrawingID is defined using INTEGER PRIMARY KEY the column is then an alias of the normally hidden rowid (if not a WITHOUT ROWID table (rarely used)).

When inserting a row and you don't sepcify a value for the column then a unique value is supplied. This is typically 1 greater than the highest with the first value as 1.

However, there is no guarantee that the unique value will be 1 greater or that if when (if) you reached the maximum number of 9223372036854775807 (basically impossible due to storage device capacity) that a lower (but still unique) number will be assigned.

Using an alias of the rowid will be more efficient not only as the value stored is shorter (maximum of 8 bytes), it is stored in the most efficient (up to twice as fast as other indexes) index. Of course you then don't have the additional inefficiency of trying to replicate this inbuilt behaviour by So I need to split the string, convert it to an Integer and add +1. Then rebuild the ID and return it to the OnSave function.

As an example consider the following :-

/* Cleanup in case existing Environment exists */
DROP TABLE IF EXISTS Drawing;
/* The suggested Schema */
CREATE TABLE IF NOT EXISTS Drawing (DrawingID INTEGER PRIMARY KEY, Title TEXT, ProjectNumber INTEGER);

/* Add various drawings */
INSERT INTO Drawing (Title,ProjectNumber) VALUES
    ('Room1',1),('Room2',1),('Room1',3),('Room3',3),('Room3',1),('Room2',3),('Room1',2);
/* Extracting Project, Drawing Title and Drawing ID */
SELECT 'Project - '||ProjectNumber AS ProjectNumber, Title, 'DR'||printf('%07d',DrawingID) AS DrawingID FROM Drawing ORDER BY ProjectNumber,DrawingId;
/* Cleanup testing Environment */
DROP TABLE IF EXISTS Drawing;

The above results in :-

The actual data in the table being

sorted as above i.e. extracted using SELECT * FROM Drawing ORDER BY  ProjectNumber,DrawingId;) :-

You may wish to have a read of

SQL As Understood By SQLite - CREATE TABLE - ROWIDs and the INTEGER PRIMARY KEY
SQLite Autoincrement

(Noting that althogh this is a link to AUTOINCREMENT it explains why AUTOINCREMENT is best not used in addition to adding information)


Is given pattern a subString of given input string? KMP implementation

Bug #1

If the pattern matches to the end of the string, your function returns false:

String s = "ABC";
String p = "ABC";
System.out.println(isSubString(s, p));

false

Bug #2

Your function isSuffixIsAlsoAPrefix() is off.  Given a suffix of "ABCDAC", it returns "A" which is incorrect.  This leads to the following failure:

String s = "ABCDACBCDACGX";
String p = "ABCDACG";
System.out.println(isSubString(s, p));

true

Not a true KMP implementation

Even if your code were correct, isSuffixIsAlsoAPrefix() takes \$O(m)\$ time which causes the whole algorithm to take \$O(n*m)\$ time, where \$n\$ is the length of the string and \$m\$ is the length of the pattern.  A real KMP implementation would build a partial match table first, so that instead of calling isSuffixIsAlsoAPrefix() on a mismatch, it would instead look up the new value of pIndex from the table.  This leads to an overall time of \$O(n+m)\$.

I'm wondering how you came up with your algorithm, because it doesn't resemble any Knuth Morris Pratt implementation that I've ever seen.


Taking a node in rootA and finding a clone node in other tree

It looks like the solution solves the wrong problem: the rootA is completely ignored, as well as the fact that the trees are actually DOM. In a DOM structure it is safe to assume that the node has an access to its parent and siblings. So, given a node in rootA tree, you may trace its path to the root, and then descend the same path down from rootB. Since they are clones, such descend will get you to the node in question. I don't see the need (other than unit test purposes) to compare nodes.


Reading words and counting their occurence in Java

I have one comment:
Files.lines() method has the following comment in the JDK documentation:

  The returned stream encapsulates a Reader. If timely disposal of file
  system resources is required, the try-with-resources construct should
  be used to ensure that the stream's close method is invoked after the
  stream operations are completed.

in other words, in order to prevent resource leak, you need to construct the stream in a try-with-resources block

try (Stream<String> linesStream = Files.lines(path)) {
    Map<String, Long> occ = linesStream
        .flatMap(line -> Arrays.stream(line.split(delimRegex)))
        ....
}


The first paragraph of the man page says it all:

  sendfile() copies data between one file descriptor and another.
         Because this copying is done within the kernel, sendfile() is more
         efficient than the combination of read(2) and write(2), which would
         require transferring data to and from user space.

So, sendfile is quite efficient.

However, your loop may use sendfile incorrectly because you always try to transfer max_size and this could return an error (EOVERFLOW) on the last chunk of the file (i.e. you try to read more than remains in the input file).

This may work just fine if you handle the error case properly.

It also depends upon what max_size and leftsize actually are [which you didn't specify].

I'll assume that max_size is some reasonable chunk limit (e.g. max_size = 1024 * 1024;) and that leftsize is the size of the input file that comes from:

struct stat st;
fstat(fd_src,&st);
leftsize = st.st_size;

So, just to be safe, here is what I'd do:

while (leftsize > 0) {
    // get chunk size
    n = max_size;

    // clip transfer size to remainder of file
    if (n > leftsize)
        n = leftsize;

    n = sendfile(fd_dest, fd_src, NULL, n);
    if (n<0) {
        printf("sendfile failed. ret:%d errno:%d\n", n, errno);
    }

    leftsize -= n;
}


Please review my solution to Project Euler program 1

You certainly got the point of the problem. You applied Inclusion-Exclusion principle. Your code works well too. Most of the operations you use are constant time operations and can't be optimized further. The only problem is code formatting. Every coder develops a coding style that suites him or herself, but when you code, always remember that your code can fall into someone else's hand one day and you don't want the person to suffer before understanding your code.

A comment at the beginning of the code will be good. Not just for a third party reader, but you. You may open the code in another decade, you don't wanna have to go to project Euler's site before you understand what your code does.
Naming variables, your variables name should reflect its meaning. And you initialized way too many variables on the same line. Funny enough those variables are pointless. You can just use their values immediately in S1, S2 and S3.
Spacing also is important, not for the compiler of course but for you or whoever is reading this code.

This is how I would have done it;

#include<stdio.h>

/* Function to find the sum of the multiples
of a OR b between 1 and N, excluding N */

int findSum(int a, int b, int N){
    N--;
    int a_n = (N/a)*a,
        b_n = (N/b)*b,
        ab_n = (N/(a*b))*a*b,
        sum_a = ((N/a) * (a + a_n))/2,
        sum_b = ((N/b) * (b + b_n))/2,
        sum_ab = ((N/(a*b)) * (a*b + ab_n))/2;
    return sum_a + sum_b - sum_ab;
}

int main(){
    int a = 3, b = 5, N = 1000;
    printf("%d", findSum(a, b, N));
    return 0;
}


Find a service and update its last ping time

The code as posted doesn't compile; I had to add some includes and definitions:

#include <chrono>
#include <map>
#include <string>

using HeartbeatCheckpoint = std::chrono::high_resolution_clock::time_point;

Having done that, the simplest refactoring of the functions would be to just pass a member pointer to specify the field you want to set in the found object:

bool update(const std::string& id, HeartbeatCheckpoint (Service::*field))
{
    auto found = services.find(id);
    if (found == services.end())
        return false;
    found->second.*field = std::chrono::high_resolution_clock::now();
    return true;
}

bool updatePing(const std::string& id) {
    return update(id, &Service::lastPing);
}

bool updatePong(const std::string& id) {
    return update(id, &Service::lastPong);
}

Alternatively, something I've used before is a small wrapper around find to give it an interface that can be tested inline:

namespace collection
{
    template<typename T>
    inline bool contains(const T& container, const typename T::key_type& key)
    {
        return container.find(key) != container.end();
    }
    template<typename T>
    inline bool contains(const T& container, const typename T::key_type& key, typename T::const_iterator& it)
    {
        return (it = container.find(key)) != container.end();
    }
    template<typename T>
    inline bool contains(T& container, const typename T::key_type& key, typename T::iterator& it)
    {
        return (it = container.find(key)) != container.end();
    }
    template<typename T>
    inline bool contains(const T& container, const typename T::key_type& key, typename T::mapped_type& result)
    {
        typename T::const_iterator it;
        return contains(container, key, it) && (result = it->second, true);
    }
}

This is then used slightly more readably (at the expense of being unfamiliar outside your team):

bool updatePing(const std::string& id) {
    std::map<std::string, Service>::iterator it;
    const bool found = collection::contains(services, id, it);
    if (found)
        it->second.lastPing = std::chrono::high_resolution_clock::now();
    return found;
}

It's arguably slightly neater if we assign to a pointer, rather than to an iterator:

namespace collection
{
    template<typename T, typename V>
    inline bool contains(const T& container, const typename T::key_type& key, const V *& result)
    {
        auto it = container.find(key);
        if ((it = container.find(key)) == container.end())
            return false;
        result = &it->second;
        return true;
    }
    template<typename T, typename V>
    inline bool contains(T& container, const typename T::key_type& key, V *& result)
    {
        auto it = container.find(key);
        if ((it = container.find(key)) == container.end())
            return false;
        result = &it->second;
        return true;
    }
}

bool updatePing(const std::string& id) {
    Service *service;
    const bool found = collection::contains(services, id, service);
    if (found)
        service->lastPing = std::chrono::high_resolution_clock::now();
    return found;
}

As you haven't shown us where these functions are used, we can't determine whether the return value is important or not.  If it's not required, we can easily use the Null Object pattern to provide a sink for the result:

Service& find_service_or_default(const std::string& id)
{
    static Service dummy{""};
    auto it = services.find(id);
    return (it == services.end()) ? dummy : it->second;
}

void updatePing(const std::string& id)
{
    find_service_or_default(id).lastPing = std::chrono::high_resolution_clock::now();
}

void updatePong(const std::string& id)
{
    find_service_or_default(id).lastPong = std::chrono::high_resolution_clock::now();
}

This is all assuming that you have more functions than just those two - if not, then the refactoring is unlikely to be an improvement, and the original (with side-by-side duplication of a clearly recognisable structure) is likely to be more readable.


Since this functionality is heavily dependent on jQuery, you might consider making this into a jQuery plug-in rather than javascript (
Consider putting hard-coded class names and other configuration values (i.e. 300 value for window position comparison) into configuration to make this class more re-usable.
Don't use $ prefix on variables ($windowHeight,$windowPosition, etc.) that don't represent jQuery collections if you are attempting to adhere to a coding standard that prefixes jQuery collection-holding variables in this manner.
I don't know that either of the functions make sense in a static/prototype context, as each of the functions deals with the "state" of an individual control or set of control bound to the object.  This state should likely not be held on the prototype. You are actually calling the shareStickyFooter() function as one would an object constructor.  Is toggleStickyOnInit() even used? If not, it should be removed.
shareStickyFooter() is an oddly named function.  It looks to me like this function is simply defining scroll event handler. It doesn't "share" anything. attachScrollBehavior()?
Where is $window defined? If you are explicitly going to add a dependency to some global variable (which I assume is defined as $(window)), then you might consider passing that dependency in rather than just blindly relying on this being defined and available to this scope. I personally don't see great value in putting this in variable here at all.
I am not quite sure that the two different states that the control can seemingly be in are appropriately modeled.  Why do you have both sticky and non-sticky DOM elements shown in initialized state when it seems the intent is to only have one showing at a time?  Why does your scroll event handler have 3 possible outcomes (sticky/not sticky/?) vs. just two (sticky/not sticky)?
This code var $scrollTop = $(this).scrollTop(); seems ambiguous.  What do you expect this to be in this context?  I would think $(window).scrollTop() would be less ambiguous here.
Consider using $.toggle() and/or $.toggleClass() to consolidate code and pairing this with only doing toggle action when you cross the toggle "boundary". This will minimize re-rendering the DOM every single time a scroll happens. this of course means you would need to store some sort of variable on the current "state" of the component (sticky vs. non-sticky). This along with your other variables on positional information of the involved elements should likely exist on the object itself vs. object prototype.  This probably means only having a single class which provides incremental behavior for stickyness (i.e. change position) - one class to toggle on and off rather than changing between two classes.
Do you really need public visibility on all of your properties?

Why do this:

this.$el = $el;
this.$stickyEl = this.$el.find('.sticky-bar-behavior');
this.$noSticky = this.$el.find('.no-sticky');
this.$whenSticky = this.$el.find('.when-sticky');
this.shareStickyFooter();
return this;

Rather than this?

var $stickyEl = $el.find('.sticky-bar-behavior');
var $noSticky = $el.find('.no-sticky');
var $whenSticky = $el.find('.when-sticky');
init();
return this;

Would the class benefit at all from validation that various jQuery collections are valid (i.e. not empty)?  There is, of course, code size overhead for adding this, but it is something you might consider if you need to this class to be reusable in wider context.

Putting some of these thoughts together might yield code structure more like this:

function Sticky($el, config){
    // private variables
    var $stickyEl,
        $sticky,
        $noSticky,
        ...;

    // maybe we want public visibility to positioning or state information
    this.state = 'uninitialized';
    this.scrollTop;
    ...

    // constructor
    function init() {
        // not shown - perhaps validate passed collection $el and throw error if invalid
        // merge default and passed config values
        config = $.extend(this.defaultConfig, config);

        // populate your instance variables, also possibly validate
        $sticky = $el.find(config.stickyClass);
        ...

        // attach your scroll event handler
        $(window).on('scroll', onScroll);

        // perhaps some initial setup here like putting elements
        // into non-sticky state
        $el.toggleClass(config.stickyActiveClass, false);
        $sticky.toggle(false);
        $noSticky.toggle(true);
        this.state = 'nosticky';
    }

    // onScroll callback
    function onScroll() {
         var newState = 'nosticky';
         // not shown - calculate positional information
         if (/* sticky condition */) {
             newState = 'sticky';
         }
         // toggle state if needed
         if (this.state !== newState) {
             requestAnimationFrame(function(){
                 $el.toggleClass(config.stickyActiveClass);
                 $sticky.toggle();
                 $noSticky.toggle();
             });
             this.state = newState;
         }
    }

    // call constructor
    init();
    return this;
}

// set default configuration on prototype
Sticky.prototype.defaultConfig = {
    stickyActiveClass: 'sticky-active',
    ...
};


I found that I can use hash({}).each method to dry up the code. It is :

{"fast"=>266, "super_fast" => 100, "ludicrous" => 50, "budget" => 900}.each{ |key, value|
  Fabricate(:tl, :when =>Date.yesterday.to_s,:work => value,:type => key )
}

If there is a better technique, please share it.


Mouseover effects for five buttons which may be enabled or disabled

Well first you should think about refactoring your code.  The following

if (enabled1) {
    sectionButton1.setAttribute("class", "sectionButtonEnabled");
}

is repeated a few times with just 2 differences.  The enabled flag and the button.  So this could easily go into a new function

function SetClassIfEnabled(enabled, btn) {
    if (enabled) {
        btn.setAttribute("class", "sectionButtonEnabled");
    }
}

The following is also repeated:

sectionButton1.onmouseover = function() {
    if (enabled1) {
        sectionButton1.setAttribute("class", "sectionButtonOver");
    }
};
sectionButton1.onmouseout = function() {
    if (enabled1) {
        sectionButton1.setAttribute("class", "sectionButtonEnabled");
    }
};

so this could easily go into another function as well.  But I would change one thing. You are adding the mouse events to every button but they only do something if they are enabled.  So I would check that first and then add the mouse events.

function AddHoverIfEnabled(enabled, btn) {
     if (enabled) {
        btn.onmouseover = function () {
            btn.setAttribute("class", "sectionButtonOver");
        };
        btn.onmouseout = function () {
            btn.setAttribute("class", "sectionButtonEnabled");
        };
    }
}

Doing just the above will shorten your code quite a bit because you can then call the functions like this

SetClassIfEnabled(enabled1, sectionButton1);
SetClassIfEnabled(enabled2, sectionButton2);
...
AddHoverIfEnabled(enabled1, sectionButton1);
AddHoverIfEnabled(enabled2, sectionButton2);
...

But I took it a step farther.  By putting the buttons and the enabled flags into an array you can just iterate over each and do the work if necessary.  Doing it this way will make it extremely easy to add another button in the future.  The following code can replace all the above mentioned changes.

function prepareEventHandlers() {

    var btnArray = [];
    btnArray[0] = [document.getElementById("sectionButton1"), true];
    btnArray[1] = [document.getElementById("sectionButton2"), false];
    btnArray[2] = [document.getElementById("sectionButton3"), false];
    btnArray[3] = [document.getElementById("sectionButton4"), false];
    btnArray[4] = [document.getElementById("sectionButton5"), false];

    for (i = 0; i < btnArray.length; i++) {
        if (btnArray[i][1] == true) { // section/button is enabled

            var btn = btnArray[i][0];
            btn.setAttribute("class", "sectionButtonEnabled"); // set default class

            // Add Hover Events
            btn.onmouseover = function () {
                this.setAttribute("class", "sectionButtonOver");
            };
            btn.onmouseout = function () {
                this.setAttribute("class", "sectionButtonEnabled");
            };
        }
    }
}

I would actually take the array out of this function and pass it in as an argument but you get the point.

I'm also assuming the enabled flags may change for any of the buttons.  If not and it is only one (as you are showing) you could just eliminate all the code that has nothing to do with button1 because none of the others are enabled so they are not manipulated at all.


What value the rear and front counter of an Array implementation of Queue start with? -1 or 0 or 1?

Most implementations of a Queue use front to point to the head element of the queue and rear to point to the first empty element at the rear of the queue:

front       rear
v            v
[1][2][3][4][ ][ ]

Your implementation has them pointing one element previous.

To change your code to work like this would be a matter of change front/rear to start at 0 and then reversing your increment/read:

void Enqueue(int value)
{
    if(rear<SIZE-1)
    {
        queue[rear] = value;
        ++rear;
    }
    else
    {
        printf("Queue overflow!\n");
    }
}

Review:

Your IsEmpty function has the side effect of resetting the queue. The name does not reflect this; it sounds like it should be merely checking whether the queue is empty. There's not really anything wrong with that. Pragmatically, such an operation should be transparent. However, I'd put a comment in there describing the side effect.

You could also implement a circularly linked queue in which you insert elements in a (conceptual) ring. Basically, when you get to the end of the array, you start inserting at the begining again. However, this means that when front = back the buffer could be full or empty. Just check rear + 1 to see if it's empty.

Oh, and please spell "queue" and its varients correctly...it's really bugging me :)


Dropping rows from a PANDAS dataframe where some of the columns have value 0

I think you need create boolean DataFrame by compare all filtered columns values by scalar for not equality and then check all Trues per rows by all:

df = df[(df[['A','C']] != 0).all(axis=1)]
print (df)
   A  B  C
0  1  2  5
2  6  8  4

Details:

print (df[['A','C']] != 0)
       A      C
0   True   True
1   True  False
2   True   True
3  False   True

print ((df[['A','C']] != 0).all(axis=1))

0     True
1    False
2     True
3    False
dtype: bool

I think you need create boolean DataFrame by compare all values by scalar and then check any Trues per rows by any and last invert mask by ~:

df = df[~(df[['A','C']] == 0).any(axis=1)]

Details:

print (df[['A','C']])
   A  C
0  1  5
1  4  0
2  6  4
3  0  2

print (df[['A','C']] == 0)
       A      C
0  False  False
1  False   True
2  False  False
3   True  False

print ((df[['A','C']] == 0).any(axis=1))
0    False
1     True
2    False
3     True
dtype: bool

print (~(df[['A','C']] == 0).any(axis=1))
0     True
1    False
2     True
3    False
dtype: bool


A little bash function, assigning attributes

What you're doing is perfectly fine.

If you absolutely want to shorten it (at a slight loss of readability) for whatever reason you could do it this way (at least in bash):

fn() {
    [ -z "$1" ] && read -p "username:" username || username=$1
    echo "username is $username"
}

Output (in a bash environment):

$ fn() {
>     [ -z "$1" ] && read -p "username:" username || username=$1
>     echo "username is $username"
> }
$ fn
username:xx
username is xx
$ fn yy
username is yy
$


(Brilliant.org) Arrays Intermediate 3: Contiguous Knapsack

You are currently calculating the sum of all possible subarrays. A different approach is to imagine a sliding window on the array. If the sum of the elements in this window is smaller than the target sum, you extend the window by one element, if the sum is larger, you start the window one element later. Obviously, if the sum of the elements within the window is the target, we are done.

This algorithm only works if the array contains only non-negative numbers (as seems to be the case here when looking at the possible answers).

Here is an example implementation:

def contiguous_sum(a, target):
    start, end = 0, 1
    sum_ = sum(a[start:end])
    # print(start, end, sum_)
    while sum_ != target and start < end < len(a):
        if sum_ < t:
            end += 1
        else:
            start += 1
            if start == end:
                end += 1
        sum_ = sum(a[start:end])
        # print(start, end, sum_)
    return sum_ == target

This algorithm can be further improved by only keeping a running total, from which you add or subtract:

def contiguous_sum2(a, t):
    start, end = 0, 1
    sum_ = a[0]
    #print(start, end, sum_)
    while sum_ != t and start < end < len(a):
        if sum_ < t:
            sum_ += a[end]
            end += 1
        else:
            sum_ -= a[start]
            start += 1
            if start == end:
                sum_ += a[end]
                end += 1
        #print(start, end, sum_)
    return sum_ == t

The implementation can be streamlined further by using a for loop, since we actually only loop once over the input array, as recommended in the comments by @Peilonrayz:

def contiguous_sum_for(numbers, target):
    end = 0
    total = 0
    for value in numbers:
        total += value
        if total == target:
            return True
        while total > target:
            total -= numbers[end]
            end += 1
    return False

All three functions are faster than your algorithm for random arrays of all lengths (containing values from 0 to 1000 and the target always being 100):


Better container for tracking number of string elements?

@Deduplicator already did a worthy review of the code itself, so I'm not going to repeat their points. I'll just add a few things:

Don't use std::endl, ever. It's almost always wrong, and in the few cases it's not, it's better to use an explicit flush anyway. Just use '\n'.
Add const and noexcept qualifiers to member functions whenever possible. The const helps with correctness, the noexcept can help considerably with performance. In your case count() can be both const and noexcept, and remove can be noexcept.

Now, considering what your code currently does (which I assume accurately reflects your intentions), you can't get any more efficient than a vector. vector just can't be beat. The creator C++ himself didn't believe this, so he tested it himself (he talks about it in this presentation starting at around 40-45 minutes, but his slides were broken, so check this blog post to see them). He tested up to 100,000 elements, so your ~500 element use case is covered.

Okay, so you're already using the best data structure. Can it still be better?

Yes.

The first trick, which @Deduplicator mentioned, is sorting. When a list of elements is sorted, you can do much faster binary searches on it, rather than the linear searches that find() does. So let's start by using a sorted vector:

class Table
{
public:
    void insert(std::string);
    void remove(std::string_view name) noexcept;

    int count(std::string_view name) const noexcept;

private:
    std::vector<std::string> data;
};

As you can see, the class structure itself doesn't change.

Now the simplest thing to do with insert() is simply to push_back() and then sort(). But... that's a little inefficient given that you know the vector is already sorted except for that one last element.

So what would be better would be to find the place where the new value should be inserted, and then insert it there. For that, there's std::upper_bound(), which does a binary search and returns the first value greater than the given value. So if the list is {"apple", "orange", "orange", "pear"}, searching with "orange" would return an iterator to "pear"; if the list is {"apple", "pear"}, it would still return an iterator to "pear". This is ideal because it works whether the value is already in the list or not, and if it is, it gives us the end of the repetitions, so that an insertion will trigger the smallest amount of shuffling around.

So insert() might look like this:

void Table::insert(std::string name)
{
    auto const p = std::upper_bound(data.begin(), data.end(), name);
    data.insert(p, std::move(name));
}

As for remove() it works just fine as is! (It could be a little better. First you could use a binary search rather than std::find(). Then, rather than removing the first value you find, you could remove the last. This will trigger less moving around of stuff in the vector. For that you could use reverse iterators and std::lower_bound().)

For count() it also works just fine as it is! (Once again, it could be better. You could use std::equal_range() to find the full range of matches quickly, then just subtract the iterators you get as result for the count.)

So this is all cool, and should be a bit faster than what you've got. But can we do even better?

Yes.

Consider: Is there any reason to store multiple copies of a string in the data? If someone adds "apple" 10 times, is it really necessary to add 10 "apple"s? Why not just keep "apple" and a count of 10?

To do this, you need to modify your data structure a little bit. Rather than data being a vector<string>, it should be a vector<tuple<string, int>>. That tuple stores the name and the count.

So the data structure now looks like this:

class Table
{
public:
    void insert(std::string);
    void remove(std::string_view name) noexcept;

    int count(std::string_view name) const noexcept;

private:
    std::vector<std::tuple<std::string, int>> data;
};

Note the only change is to the type of data. The class's interface is unchanged.

So what would insert() look like. Well, the first thing you'd have to do is a lower_bound() search to find the value. Then:

If the result of lower_bound() is not data.end(), and it points to a value equal to name, just increment the count.
Otherwise, add a new element to the vector with a count of 1.

That might look like this:

void Table::insert(std::string name)
{
    // A lambda comparator is needed to compare a string to a
    // tuple<string, int>. All it needs to do is get the first
    // element (the string), and do a normal comparison.
    auto const p = std::lower_bound(data.begin(), data.end(), name,
        [](auto&& v, auto&& e) { return v < std::get<0>(e); });

    // If the result is not end, and the string matches...
    if (p != data.end() && std::get<0>(*p) == name))
    {
        // ... update the count.
        ++std::get<1>(*p);
    }
    else
    {
        // ... otherwise, add a new item with a count of 1. Because
        // we used lower_bound, p either points to end or the first
        // element greater than name, so it's the right place to
        // insert before.
        data.emplace(p, std::move(name), 1);
    }
}

remove() also has a special case to consider. First you find the item you want - you can use std::binary_search() for that. Then (assuming you find an item), you decrement its count. Now the special case is if the count is zero, you have to remove the item from the table.

That might look like this:

void Table::remove(std::string_view name) noexcept
{
    auto const p = std::binary_search(data.begin(), data.end(), name,
        [](auto&& v, auto&& e) { return v < std::get<0>(e); });

    if (p != data.end())
    {
        --std::get<1>(*p);
        if (std::get<1>(*p) == 0)
            data.erase(p);
    }
}

And from that, count() should be obvious:

void Table::count(std::string_view name) const noexcept
{
    auto const p = std::binary_search(data.begin(), data.end(), name,
        [](auto&& v, auto&& e) { return v < std::get<0>(e); });

    if (p != data.end())
    {
        return std::get<1>(*p);
    }
    else
    {
        return 0;
    }
}

That will give you the most compact, and almost certainly the fastest results.

The two key factors here are:

Compact data representation. vector is as compact as it gets, but using a single tuple with a name and a count is also much more compact that storing a name multiple times.
Sorting. Sorted data is predictable, which means you can optimize accessing it with tools like binary_search() and lower_bound() and the other binary search algorithms.

Put together, that will match the observable behaviour of your code, but should be many times faster.


The program that reverses bytes in two distinct ways (in C++)

Style-wise, objectively improvable:

Avoid leaving dead code

This looks like junk you forgot to delete:

int x(1), y(2);

++x = y;

Comment non-trivial algorithms:

reverse0() is funky enough that I had to squint a bit and take a quick minute to run the code in my head to even have an idea of what it's trying to do. An explanation of what each line is "supposed" to be doing would have been helpful here.

Either name the struct type or the field name, not both

struct Word
{
    unsigned b1 : 8;
    unsigned b2 : 8;
    unsigned b3 : 8;
    unsigned b4 : 8;
} _word;

You don't need Word for anything, so you should just omit it entirely

Redundant explicit void argument list in main declaration:

int main(void) should just be int main()

Style-wise: opinions:

I don't like using unsigned

Since unsigned generally reads like a qualifier (I know it's not, it just looks like one), I personally much prefer being explicit and using unsigned int instead.

non-style stuff, but important:

don't use non-sized types with hard-coded sizeof() expectations.

Your FourBytes struct assumes that sizeof(unsigned) is 4, which is bad, you should be using std::uint32_t to properly enforce that.

Writing to an union field and reading from another one is illegal

This is surprising to many people as using unions to perform type punning is such a common technique, but it is, in fact, undefined behavior. You are only allowed to read from the last field you wrote to.

That means your reverse1() function is not valid C++ at all.

What's legal is reading and writing from a char (or unsigned char) array obtained from reinterpret_casting the pointer of a standard layout object. In fact, it's the only legal way to do direct memory manipulation of an existing object.

Edit: as requested, an implementation of reverse() using casting to char array:

unsigned int reverse(unsigned int v) {
   unsigned int result = 0;

   char const* src = reinterpret_cast<char const*>(&v);
   char* dst = reinterpret_cast<char*>(&result);

   for(int i = 0; i < sizeof(v); ++i) {
     dst[sizeof(v) - i - 1] = src[i];
   }

  return result;
}


NinjectWebCommon implementation/translation - C# to F#

Your code seems like it's primarily plumbing. There are no algorithms or types that could be given the functional treatment. I have only two recommendations.

Instead of NinjectWebCommon being abstract/sealed with static members you can make it a module with let-bound functions.
_kernel in NinjectResolver is unnecessary because primary constructor parameters are available throughout the body of the type. So you can just reference kernel throughout instead.


c++11 Allows constructor chaining:

Ptr(const Ptr& t) {
    sz = t.sz;
    p = new T[sz];
    T* x = t.get();
    for (int i = 0; i < sz; ++i) {
        p[i] = x[i];
    }
}

Can be written as:

Ptr(const Ptr& t): Ptr(t.p, t.sz) {}

Good to see you using the copy and swap idiom.

Ptr& operator=(const Ptr& t) {
    Ptr copy{t};
    std::swap(copy.sz, sz);
    std::swap(copy.p, p);
    return *this;
}

But his can be simlified by making the compiler to the copy.

Ptr& operator=(Ptr copy) {
        //   ^^^^^    Pass by value is generating a copy.
    std::swap(copy.sz, sz);
    std::swap(copy.p, p);
    return *this;
}

This looks good.

~Ptr() {
    delete[] p;
}

But you ca still move p

void operator+=(int i) {
    check_range(index+i);
    index += i;
    p+= i;               // P has changed
}

void operator-=(int i) {
    check_range(index-i);
    index -= i;
    p -= i;               // P has changed
}

Thus using it with delete after the point it changed is going to cause UB.


Automated Teller Machine (ATM) implementation in Java

This is fairly good for a program in this category for being well formatted and having variable names that mostly make sense. I.e. I have no trouble figuring out what the code tries to do.
ATM a = new ATM("A", "S", 20000);

Here you create an ATM with a name and balance. If you think about what an ATM does, this does not reflect real life. ATM's have a balance as in how much money they contain but they do not have a first and last name. You may have been thinking of a BankAccount when implementing the code. This is supported by the code not having a step where the user tells the machine who they are and what account to access. But then again, bank accounts are identified by account number, not by the account owner name.
System.out.println("Please choose: " + "\n" +
    "1. Deposit" + "\n" + "2. Withdraw" + "\n" + "3. Info" + "\n" + "4. Exit");

This is just hard to read and maintain. In these situations I prefer reflecting the end result in the formatting so that the intended output is more clear.
System.out.println("Please choose:\n" +
    "1. Deposit\n" +
    "2. Withdraw\n" +
    "3. Info\n" +
    "4. Exit");

Now it is also instantly clear to the code maintainer what the valid input options are.
int option = in.nextInt();

Because you have not written any error handling, your program will show an ugly error message to the user and it will immediately exit if they make a wrong choice, such as enterin a letter instead of a number.
switch (option) {
    ....

Switch statements should always have a default-case. This is especially important as you are handling user input.
    default:
        System.err.println("Invalid input " + option + ". Please choose a value between 1 and 4.");
        break;

This also holds true if the swich handles an enumeration and you have handled all the cases because a change to the enumeration might add a new value and your code would then be unable to handle it. In such cases the default case should throw an IllegalArgumentException with a message describing the problem.
case 4:
    System.exit(0);

It is pretty much never Ok to exit from a Java program using System.exit(int). It's akin to pulling the power cord from the computer to exit. It exits your program but also takes out everything else that might have been running in the JVM. In this case the correct choice would be to set the loop condition in the while-loop to false.
boolean exitRequested = false;
while (! exitRequested) {
    ...
    switch (option) {
    ...
    case 4:
        exitRequested = true;
        break;
    }
}

Now that you have a variable controlling the exit, you can use it to search for the code that makes the program exit. This is a useful feature when the programs that you work with are larger.
public ATM(String name, String lastName, double balance) {

Money should never be handled using floating point numbers. Use either integers and divide the result with 100 to obtain euros and cents or use BigDecimal. For classroom code we can let it pass, but it's really not a good idea to learn that habit. I have seen it in production and it is neither nice to fix the issues nor explain to customers why our software stole a cent of their money.
public void withdraw(double value){
    if(value > balance){
        System.out.println("You can't withdraw that amount of money." +"\n"+ "Your balance is: " + getBalance() + "\n");

You've placed a user interface inside the ATM class (if we call it "BankAccount", it might be more obvious why this is a bad idea, bank accounts don't have a user interface). Instead of placing error messages in the withdraw method, you should throw an exception that describes the error and let the user interface code in your main class to decide what message to show to the user.


Replacing elements from a list and its sublists - part II

This looks pretty good. I only see one issue and it's more code appearance than functional

Fix your spacing

You indentation isn't quite right and makes it a little hard to see what clauses line up where. Here's your same code slightly altered:

(define (substitute2 lst oldlst newlst)
    (define (maybe-swap elem oldlst newlst)
        (cond ((null? oldlst) elem)
              ((equal? (car oldlst) elem) (car newlst))
              (else (maybe-swap elem (cdr oldlst) (cdr newlst)))))
    (if (list? lst)
        (map (lambda (elem) (substitute2 elem oldlst newlst)) lst)
        (maybe-swap lst oldlst newlst)))

I lined up the three cond clauses - and cleared up the fact that the map and maybe-swap both belong to the if. As-is, it kind of looks life the if is part of maybe-swap.

Make a swapper function

This is more for fun than it is necessarily a valuable suggestion (I have no idea if this is good or not). But one thing we can do is take oldlst and newlst and turn those into a swapper function - one that takes an elem and returns the correct substituted result. The code to build up such a swapper is pretty similar to your maybe-swap already:

(define (make-swapper oldlst newlst)
   (if (null? oldlst)
       (lambda (elem) elem)
       (lambda (elem)
          (if (equal? elem (car oldlst))
              (car newlst)
              ((make-swapper (cdr oldlst) (cdr newlst)) elem)))))

So then in substitute2, we just make one up front and call it:

(define (substitute2 lst oldlst newlst)
    (define swapper (make-swapper oldlst newlst))
    (define (substitute-impl lst)
        (if (list? lst)
            (map substitute-impl lst)
            (swapper lst)))
    (substitute-impl lst))


Traversing javascript/json based on a dot-separated lookup string

The very first problem I see is:

next instanceof Object

That's because almost everything, if not everything, in JS is an instance of Object. Go try new Date() instanceof Object and even that is true. That said, you can do it this way but you must assume that it's just a structure containing objects and arrays. Otherwise, you'll have to check for every possible kind of object out there. This means dates, regexes, DOM objects, functions etc.

Another way to do this is to create a function dynamically. I've seen frameworks do this, especially when it deals with templates containing JS expressions. Instead of lugging around a full-blown expression parser, they let the browser's parser do it. The advantage of this method over eval is that you only evaluate the expression once. You can then cache the generated function in some object for reuse. You can even have it return undefined or null if the entire subtree is missing instead of getting an error.

function createResolver(keypath){
  return new Function('root', `
    try { return root.${keypath}; }
    catch(e){ return undefined; }
 `);
}

// Return foo.bar.baz
var obj1 = { foo: { bar: { baz: 'bam!!!' }}};
var resolver1 = createResolver('foo.bar.baz');
var value1 = resolver1(obj1);

// Even when the subtree is missing, you can safely call it
var obj2 = { foo: {}};
var resolver2 = createResolver('foo.bar.baz');
var value2 = resolver2(obj2);

// Normally, this throws an error:
var value3 = obj2.foo.bar.baz


Converting a float to a fraction as a string

There isn't much to say about the function and algorithm it self. It's an ordinary recursive function - with tail call - which is optimal for recursive functions.
I don't find a string as return value really useful. Instead I think, I would return a tuple of two integers representing the numerator and denominator
let toFraction (num: float): (int * int) = etc...

Alternatively you could define a discriminated union as something like:
type Fraction = Fraction of int * int

... used like:
let toFraction num =
if num <= 0.0 || num >= 1.0 then
    failwith "Invalid input"
else
  let rec farey n0 d0 n1 d1 =
    let n2 = n0 + n1
    let d2 = d0 + d1

    match float n2 / float d2 with
    | x when abs (x - num) < 1e-10 -> Fraction(n2, d2)
    | x when x < num -> farey n2 d2 n1 d1
    | x when x > num -> farey n0 d0 n2 d2
    | _ -> failwith "Something went completely wrong" // just to fulfill the pattern matching - it should never happen

  farey 0 1 1 1

and called as
let (Fraction(num, denom)) = toFraction value
printfn "%d / %d" num denom

As shown, I've chosen to run farey with integers instead of floats. You should test if that is more efficient than using floats.

match (n2 / d2) with

You don't need the parentheses.

num is in the set 0 <= num < 1

0 = num is an edge case that is calculated wrongly to
1 / 100001

If you want 0 to be included in the domain, you need to start faray with the values -1 0 1 1. Then it will return "0 / 1".

Even though you specify in the comment, that it is assumed that num should be between zero and one, you should guard against invalid input, especially because invalid input may result in an infinite recursive loop.


Don’t roll your own encryption.  It takes a team of experts to develop new secure encryption methods, and even they can get it wrong from time to time.

Huge hole in your DIY encryption:

If I use a 2-character password, I might naïvely expect I’d have \$62^2\$ possible passwords that I can encrypt the data with.  I’d be really shocked when it turns out there are only 4.

random.getrandbits(len(password))

generates 2 random bits, for \$2^2\$ possible values to multiply to_num(data) by.  Only 4 possibilities is a lot easier to attack than \$62^2\$ different possibilities!

And one of those possibilities ... all bits zero ... destroys all the data you want to encode.  So we’re down to actually only 3 possible numbers to test to reverse the encryption.

Any encryption mechanism worth its salt uses a salt (initial random data) to prevent the same message with the same password from being encrypted as the same text.

Code improvements: use generator expressions.  Eg)

chunk = []
for digit in str(unique_id):
    chunk.append(LETTERS[int(digit)])
return "".join(chunk)

would be more efficient rewritten as:

return "".join(LETTERS[int(digit)] for digit in str(unique_id))

The chunk list is never created in memory; instead, the join method pulls items one at a time from the generator expression.

Finally, don’t roll your own encryption.


Looks good.

This is a little confusing:

void attachObserver(vector_type::value_type observer)

To see what I have to pass to this function. I need to look up vector_type (which is in the class). I would make it more explicit so that I can see exactly what is expected:

void attachObserver(std::unique_ptr<Oberver> observer)

Don't see the need for:

class FooSubject : public Subject

I would just put all methods in Subject (no need for a FoodSubject). But this is a pattern not a design and you may have a reason that are not obvious from the current question.

There is no need to define methods that are covered by the default versions.

// I would not bother with this
FooSubject() {}
~FooSubject() {}


Overview
Looks like you are reading data from the standard input and converting to a number. There is already code for that:
int val;
std::cin >> val;

You use C functionality throughout this code (printf/arrays/getchar) where there are better C++ alternatives (std::cout/vector/std::cin). A lot of this work can be delegated to standard functions.
Code Review
#include <iostream>

What are these headers and what do they define?
#include "TheGameHeaders.h"

This is very terminal specific.
#define CLEAR_LINE printf("\033[K")
#define POSITION(Ze, Sp) printf("\033[%d;%dH", Ze, Sp)
#define CLEAR printf("\033[2J")

A lot of terms might support this but it is not universal. Have a look at ncurses library; that will provide a terminal-neutral way to achieve all this. ncurses, and curses before it, look up these control characters from their terminal databases and retrieve the terminal-specific escape codes.

This is not standard C++:
    char fake_nbrs[qntty_of_incs];

If you want dynamic (run time sized) arrays, then you should be using std::vector<>

We have standard functions for checking for numbers:
        while((fake_nbr = getchar()) != '\n')
        {
            if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9')

Have a look at:
   std::isdigit()

Returning valid integer numbers to indicate failure conditions is probably not a good idea.
                else
                {
                    return 1;
                }
            }
            else
            {
                return 0;
            }

How can the user of your code tell if this is real user input or an error?

You use several loops to convert the each number to its correct value. Why not do this in a single loop?
    for(int a = 0; a < i; a++)
    {
        fake_nbrs[a] -= '0';
        real_nbrs[a] = fake_nbrs[a];
    }

    int i_fix = i;
    int i_fix_2 = i-=1;

    for(int a = 0; a < i_fix; a++)
    {
        i = i_fix_2;
        real_nbrs[a] *= pow(10, i-=a);
    }

    for(int a = 0; a < i_fix; a++)
    {
        real_nbr += real_nbrs[a];
    }

Seems simpler like this:
   int result = 0
   for(int a = j; a > 0; a--) {
       result = (result * 10) + (fake_nbrs[a - 1] - '0');
   }

There already exists a standard power function in the maths library.
int pow(int base, int exponent)

Nice touch. Most people forget this part.
    if(exponent == 0)
    {
        return 1;
    }


public static class IoCContainer
{
    public static IUnityContainer Container = new UnityContainer();
}

I've never used Unity, but this looks quite dangerous to me: your IoC container is accessible from anywhere in the code. Dependency Injection does not play well with anything public static - the IoC container is no exception here. In fact, the IoC container instance belongs in one, single place: your composition root - and that's app.xaml.xs. So instead of this:

IoCContainer.Container.RegisterType<ApplicationSettingProvider<Theme>, ApplicationThemeProvider>(new ContainerControlledLifetimeManager());
IoCContainer.Container.RegisterType<ApplicationSettingProvider<FontSize>, ApplicationFontSizeProvider>(new ContainerControlledLifetimeManager());
IoCContainer.Container.RegisterType<ApplicationSettingProvider<AppVersion>, ApplicationStartupVersionProvider>(new ContainerControlledLifetimeManager());

You should have that:

_container.RegisterType<ApplicationSettingProvider<Theme>, ApplicationThemeProvider>(new ContainerControlledLifetimeManager());
_container.RegisterType<ApplicationSettingProvider<FontSize>, ApplicationFontSizeProvider>(new ContainerControlledLifetimeManager());
_container.RegisterType<ApplicationSettingProvider<AppVersion>, ApplicationStartupVersionProvider>(new ContainerControlledLifetimeManager());

Where _container is an instance field of your App class. In a wpf application this setup code would be in the OnStartup override: the UnityContainer instance only ever lives at the composition root level.

Speaking of composition, you've either not included it, or all you're doing is the registration part. And this explains it:

  Wherever I want to access my settings:

private ApplicationSettingProvider<Theme> _ThemeProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<Theme>>();
private ApplicationSettingProvider<FontSize> _FontSizeProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<FontSize>>();
private ApplicationSettingProvider<AppVersion> _StartupVersionProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<AppVersion>>();

That's exactly the opposite of dependency-injection: everywhere you're accessing your settings, you have a tight coupling with that static class IoCContainer and its public static IUnityContainer field.

That's the Service Locator anti-pattern: anyone, anywhere, has access to anything that's registered with the IoC container. The typical Service Locator passes the container around as a dependency - but your is worse, because being a public static utility class, it becomes an ambient context that's accessible at any given time by anyone that wants to use it.

IoC containers are much, much more powerful than that. IoC stands for Inversion of Control - that means your types don't ask the container to resolve an instance of a service, but rather they tell it what their dependencies are, and the IoC container injects them... usually through the constructor.

The Hollywood Principle: Don't Call Them, They'll Call You

I'm going to have to make some things up here, because you've supplied us with the dependencies, but not with anything that depends on them.

So let's say your application is controller by a MainWindowViewModel.

This MainWindowViewModel class needs to access the settings; its constructor will statically document this fact, by taking in an interface that represents some SettingsProvider - here you've done that with an abstract class:

private readonly ApplicationSettingProvider<Theme> _themeSettings;
private readonly ApplicationSettingProvider<FontSize> _fontSizeSettings;
private readonly ApplicationSettingProvider<AppVersion> _appVersionSettings;

private readonly IView _view;

public MainWindowViewModel(ApplicationSettingProvider<Theme> themeSettings,
                           ApplicationSettingProvider<FontSize> fontSizeSettings,
                           ApplicationSettingProvider<AppVersion> appVersionSettings,
                           IView view)
{
    _themeSettings = themeSettings;
    _fontSizeSettings = fontSizeSettings;
    _appVersionSettings = appVersionSettings;

    _view = view;
}

The class may have more dependencies - the key is that it receives them all into its constructor.

  Constructor Bloating

  Everyone has their threshold. For most people, 3-4 constructor parameters is the upper limit, 5 in the extreme cases. When you start seeing that your constructor has too many dependencies, it's a sign that your class is responsible for too many things - you should then extract a class, wrap it with an interface, and inject that interface instead. In this case there could be a single IAppSettings abstraction injected there, and the implementation for that interface would receive the 3 SettingsProvider<T> into its own constructor.

  But let's say these are the only 3 dependencies you have to deal with for now... plus the IView.

When you register the types with your IoC container, you're telling it what types to use to resolve the dependencies when you compose the application - that's the step you missed.

Back to the Composition Root

_container.RegisterType<ApplicationSettingProvider<Theme>, ApplicationThemeProvider>(new ContainerControlledLifetimeManager());
_container.RegisterType<ApplicationSettingProvider<FontSize>, ApplicationFontSizeProvider>(new ContainerControlledLifetimeManager());
_container.RegisterType<ApplicationSettingProvider<AppVersion>, ApplicationStartupVersionProvider>(new ContainerControlledLifetimeManager());

// again, I don't know how Unity works - this is just for the concept:
_container.RegisterType<MainWindowViewModel,MainWindowViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IView,MainWindow>(new ContainerControlledLifetimeManager());

Now the IoC container knows about MainWindowViewModel, and all of its dependencies. The last thing to do is to resolve them, and get your app started:

var viewModel = _container.Resolve<MainWindowViewModel>();
viewModel.Show();

What just happened here? The container used the configurations you gave it, and constructor-injected all the dependencies of the viewModel - that's why that method is called Resolve: it resolves the entire application's depedency graph with a single call.

The only place you're allowed to do this is in the composition root!

That's why I said in chat, that you cannot do Dependency Injection halfway: you need to go DI all the way, and register all dependencies of every single type; every type needs to have its dependencies constructor-injected, otherwise you're breaking the pattern and you're going to have to new things up manually and thus introduce tight coupling.


Checking inactivity with periodic tasks in Java

It depends on your needs, but generally I would say that the second approach would be better.
Why? because it allows you to run multiple tasks and that gives flexibility to your system. Now the use of synchronized may be troublesome if there are many threads running, if you don't need to handle static or shared resources/variables it would be better to not use it.
Now, in the first place your classes has no static variables, and does not access to shared resources so synchronization is not needed. In the case of the class HealthCheck2, the following method will work fine without synchronized
    private void check() {
        //the variable diff isn't needed either
        if (ChronoUnit.MILLIS.between(lastActiveTime, Instant.now()) > 100)
            onExpire();
    }

Why? Because the check method is uniquely owned by each HealthCheck2 instance, even if they call the start method, the scheduler and the future variables are equally owned.
I think you could remember when you were learning about static variables and methods that these are accessible and modifiable by any class instance. Well, the oposite is true, non-static variables and methods are unique for each instance.
Hope it helped you.