I think you can extract small methods to simplify this code. Also you can try XPath to get specified sub-nodes and attributes.

And, yes, you can simplify this code with LINQ:

var ruleList = from rules in manifestXmlFile.DocumentElement.ChildNodes.Cast<XmlNode>()
               from ruleNode in rules
               from childNodeAttributes in ruleNode
               from childNodeAttrib in childNodeAttributes.ChildNodes.Cast<XmlNode>()
               from childNodeConditions in childNodeAttrib.ChildNodes.Cast<XmlNode>()
               from childNodeCond in childNodeConditions.ChildNodes.Cast<XmlNode>()
               where childNodeCond.Name.ToUpper() == "CONDITION"
               where childNodeCond.Attributes["type"].Value.ToUpper() == "HEALTHY"
               select new
               {
                   Id = new Guid(ruleElement.Attributes["ruleid"].Value),
                   AttributeName = childNodeAttrib.Attributes["name"].Value,
                   AttributeType = childNodeAttrib.Attributes["type"].Value,
                   CondTypeValud = condTypeValue = childNodeCond.Attributes["type"].Value,
                   OperatorValue = childNodeCond.Attributes["operator"].Value,
                   HealthyConditionValue = childNodeCond.FirstChild.InnerText,
               };

foreach (var r in ruleList)
{
    var psmsOperator = (PsmsOperator)Enum.Parse(typeof(PsmsOperator), r.OperatorValue, true);
    var psmsAttributeType = (TypeCode)Enum.Parse(typeof(TypeCode), r.AttributeType, true);

    var rule = new Rule(r.Id, r.AttributeName, r.HealthyConditionValue, psmsOperator);

    Rule(attributes, r.Id);
}


Performance
This is a performance only review and does not address any styling or composition.
Code examples are focused on performance with no attention given to readability, naming, or re-usability
Time complexity != performance
Time complexity is not a measure of performance. It is a measure of how performance changes as the input size changes.
Two functions can have the same time complexity but very different performance metrics.

Improving performance
Looking at your code I see some code that will negatively effect performance.
Your original code cleaned up a little. Semicolons, spaces and the like.
threeSum

function threeSum(nums) {
let out = [];
let seen = {};
for (let i = 0; i < nums.length; i++) {
    remainingArr = nums.filter((d, id) =>  id != i);
    twoSum(remainingArr, -nums[i], out, seen);
}
return out.map(d => d.split(',')).filter(d => d.length > 0);
};

function twoSum(nums, target, out, seen) {
let myMap = {};
for (let i = 0; i < nums.length; i++) {
    if (myMap[target - nums[i]] != undefined) {
        let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');
        if (!seen[val]) {
            out.push(val)
            seen[val] = true
        }
    }
    myMap[nums[i]] = i;
}
}

Major performance hits
The biggest problem is the line ...
        if (myMap[target - nums[i]] != undefined) {

where the most likely outcome is that myMap[target - nums[i]] is undefined.
Set or Map rather than Object
When JS sees a property name it needs to locate that property.
First it looks at the objects own properties. If that property does not exist, it then starts a recursive search up the prototype chain.
If the result is undefined it will have to have searched all the way up the prototype chain before it can return undefined. As this is the  most likely outcome this line adds a lot of additional (under the hood) overhead.
You can use a Set to avoid the need to traverse the prototype chain.
Memory management
There is also an incurred memory overhead because you create and release the object myMap each time the function twoSum is called.
Because javascript does not free up memory until  either

forced to due to low memory,
or when the code is at idle (Presumably in the leetcode environment that is after the function threeSum has exited and before the result is verified)

All the created myMap slowly eat up memory and will incur a GC (garbage collection) overhead. On a shared environment such as leetcodes cloud processing network memory allocated to a task can be rather small meaning forced GC calls are much more likely.
To avoid memory management overheads reduce the amount of work by reducing the number of new objects created.
In example threeSum1 I moved myMap to the first function and pass it to the second. I clear the map in the second function which is less of a management hit than creating and destroying a new one.
threeSum1

function threeSum1(nums]) {
const out = [];
const seen = new Set();
const myMap = new Set();
for (let i = 0; i < nums.length; i++) {
    remainingArr = nums.filter((d,id) =>  id != i);
    twoSum1(remainingArr, -nums[i], out, seen, myMap);
}
return out.map(d => d.split(',')).filter(d => d.length > 0);
};

function twoSum1(nums, target, out, seen, myMap) {
const b = -target;
myMap.clear();
for (let i = 0; i < nums.length; i++) {
    const a = nums[i], idx = target - a;
    if (myMap.has(idx)) {
        let val = [idx, a, b].sort((a,b) => a - b).join(',');
        if (!seen.has(val)) {
            out.push(val);
            seen.add(val);
        }
    }
    myMap.add(a);
}
}

More info

MDN Allocations

MDN Garbage collection

Minor improvements
You use Array.sort to sort the 3 values and then Array.join  them to get a unique key for the 3 values that sum to 0.
let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');

JavaScript's sort knows nothing about the array or why you are sorting it
For 3 items there are only 6 resulting outcomes, requiring at most 4 compares. You don't want the sorted array you just want to know how to build the key.
Building a small string using join is slower than building it manually using concatenation operators.
Thus we can remove the sort and use a set of if, else. and ternaries ? to build the key. No need to swap items in an unneeded array (an array that will use memory management just to exist). No need to use the slow join function to create the key.
Additional improvements.
For the best performance avoid

Indexing into arrays
Repeating calculations
Iterating over arrays more often than needed.
Manipulating Strings

Final code
Assuming that the order of items in each array in the returned array does not matter, and that the items can be Numbers (not Strings) we can remove the need to map and filler the result.
We store items in vars rather than indexing into the array nums[i] each time we want the value. eg a = nums[i]
We calculate values only once. eg b = -target, idx = target - a
threeSum2

function threeSum2(nums) {
var i = 0;
const out = [], seen = new Set(), map = new Set();
while (i < nums.length) {
    twoSum2(nums.filter((d,id) =>  id != i), -nums[i++], out, seen, map);
}
return out;
};
function twoSum2(nums, target, out, seen, map) {
var val = "", i;
const b = -target;
map.clear();
for (i = 0; i < nums.length; i++) {
    const a = nums[i], idx = target - a;
    if (myMap.has(idx)) {
        if (a < b && a < idx) { val =  idx < b ? "" + a + idx + b : "" + a + b + idx }
        else if (b < idx) { val =  idx < a ? "" + b + idx + a : "" + b + a + idx }
        else {  val =  a < b ? "" + idx + a + b : "" + idx + b + a }
        if (!seen.has(val)) {
            out.push([a, b, idx]);
            seen.add(val);
        }
    }
    map.add(a);
}
}

Results
Below are the test results for the 3 functions above.

threeSum Your original functions with changes unrelated to performance.
threeSum1 Major performance changes
threeSum2 Minor performance changes

The first test is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -10000 to 10000

Note threeSum2 is 5 time faster than original.
Note threeSum1 is only marginally quicker as the optimizations target only the resulting output data.

Name
Mean time 1
Call per sec
Rel performance
Total time
Calls

threeSum2
1,455.175µs
687
100.00%
1,412ms
970

threeSum1
1,547.062µs
646
94.03%
1,624ms
1,050

threeSum
7,047.454µs
141
20.52%
6,907ms
980

I don`t know the nature of the arrays that leetcode send the function.
The following table shows the result if we focus on the code that creates the result. This is done by reducing the range of values of the input to increase the resulting out array length.
Testing is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -100 to 100

Name
Mean time 1
Call per sec
Rel performance
Total time
Calls

threeSum2
1,904.629µs
525
100.00%
2,000ms
1,050

threeSum1
3,219.081µs
310
59.05%
3,380ms
1,050

threeSum
6,522.878µs
153
29.14%
5,871ms
900

The results show that threeSum2 is the quickest, either by a small or large margin depending on the number of matches found in the input.
Will it pass the leetcode test?
Will it be fast enough to pass the tests? That I do not know as I have not tried this example.
I do know that leetcode test times can swing wildly (from best to worst for the very same code) . Although I do not know as a fact, why, I strongly suspect that run time performance is effected by number of users using the service.
It is my experience (as an .au user) that to get the best results is to use the service in off peek times.

More
As i wrote this answer I forget to look into the array you filter
remainingArr = nums.filter((d,id) =>  id != i);

There is opportunity for more optimization in this line worth about ~5% performance increase.
Hints

use a Set and remove items using Set.delete tracking removed items, then replace them for the next pass with Set.add You can
iterate a set using for (const v of remainingArr) {

Or All the filter does is remove one element at the current index from the array. If you passed that index to the second function rather than a filtered array.

Test settings
Test settings. Same for both tests

Env: Chrome 89.0.4389.90 (64-bit). Laptop Passive cooling (ambient 17.9°)
Test Cycles.......: 100
Groups per cycle..: 1
Calls per group...: 10
Cool down 2........: 1,000,000µs

1 In microseconds µs (One millionth second)
2 time between cycles


Don't import stdafx

It is Windows only and you don't need it.

Remove all those spaces

The code is hard to follow when you must scroll continuously:

#include <iostream>

int input() {
    int x;
    std::cin >> x;
    return x % 2;
}

int main() {
    using namespace std;
    cout << "Enter a digit" << endl;
    int x = input();
    if (input == 0)
        cout << "Even";
    else
        cout << "Odd";
    return 0;
}

Always use braces

Ugly bugs may hide behind not using parenthesis:

if (input == 0) {
    cout << "Even";
} else {
    cout << "Odd";
}

In 2015 avoid return 0

The main() function is different; the compiler writes that for you.

Separate input and computation

If you care about having separate functions (not really necessary in this trivial case) you should define pure functions with no effect on the outside world:

bool is_even(int x) {
    return x % 2 == 0;
}

Avoid verbosity

A middle level language such as C++ must be pretty verbose, anyway for such trivial cases I propose inlining a ternary:

cout << ((is_even(x)) ? "Even\n" : "Odd\n");

Don't underestimate yourself

The program works for full numbers, ask `"Enter a number:"

The icing on the cake

using namespace std; is considered bad practice (read about that on StackOverflow)

The final reviewed code

#include <iostream>

bool is_even(int x) {
    return x % 2 == 0;
}

int main() {
    std::cout << "Enter a number:" << std::endl;
    int x; std::cin >> x;

    std::cout << is_even(x) ? "Even\n" : "Odd\n");
}


splitWith function for splitting a list doesn't seem optimal

You can gin up a safe version of tail lickety-split by using drop 1.


Graph seems quite reasonable:
But your distance implementation is not an implementation of Dijkstra.
Dijkstra finds only the cheapest path between two nodes (technically).
But I suppose you can use the technique to find the distance from a node to all others nodes. Dijkstra works by finding the cheapest distance to a node then expanding from there (it never re-expands a node, because it does not need to). To do this you need a sorted frontier list so you always expand from the node with the lowest cost to get there and keep track of nodes that were visited.

Some notes:
// Node Id can only by positive.
using node = int;

// Dijkstra assumes all costs are positive.
using cost = int;

Lets have a look at your search:
    // Returning the min distances to all nodes.
    // Sure: but you can not tell what the route to get there is
    //       so this does not help you traverse the graph it only
    //       tells you the shortest distances.
    //       Also how do you tell the difference between a
    //       a distsance of INT_MAX and a node that was never reached.
    std::vector<int> dijkstra(const node n) const {

        // I think this is what is causing you to go wrong.
        // The distance is usually part of the to_visit.
        // You sort the list by the distance.
        std::vector<cost> dist(adjList.size(), INT_MAX);

        // Sure. You need this for dijkstra
        //       In a classic implementation I would have used
        //       std::set<Node> as we don't need (in general) to traverse
        //       the whole graph to find a route from A to B.
        //       Since you are finding the distance to all nodes. This seems
        //       like a better choice.
        std::vector<bool> visited(adjList.size(), false);

        dist[n] = 0;

        // This is a mistake.
        // The order here based on the node-id.
        // It should be based on the cost to get to a node.
        // You always keep it sorted by the cost to get to the node
        // But you may have multiple routes to a node in the list with
        // different costs so after extraction from the list you check
        // if already visited (because if it is already visited then
        // this is not the shortest route).
        //
        // I am sure I could construct a graph that would break this.
        std::priority_queue<node, std::vector<node>, std::greater<int>> to_visit;
        to_visit.push(n);
        while (!to_visit.empty()) {
            node v = to_visit.top();
            to_visit.pop();
            visited[v] = true;
            for (const arc& a : adjList[v]) {
                node u = a.first;
                cost c = a.second;

                // In dijkstra the cost to a node is not known until
                // you actually visit it for the first time (as you may
                // see a node from many other nodes.
                if (!visited[u] and (dist[u] == INT_MAX or dist[u] > dist[v] + c)) {
                    dist[u] = dist[v] + c;
                    to_visit.push(v);
                }
            }
        }
        return dist;
    }

This is what it normally looks like:
    struct DN {
        node  src;
        node  dst;
        cost  c;

        friend bool operator<(DN const& lhs, DN const& rhs) {return lhs.c < rhs.c;}
    };

    std::vector<node> dijkstra(node begin, node end) const
    {
        std::vector<node>       route(adjList.size(), INT_MAX)
        std::set<node>          visited;
        std::priority_queue<DN> frontier;

        frontier.push({INT_MAX, begin, 0});

        while (!frontier.empty()) {
            node v = frontier.top();
            frontier.pop();

            // If we have already been here go to next value.
            if (visited.find(v.dst) != visited.end()]) {
                continue;
            }

            // OK. Found it and save the cost.
            visited.insert(v.dst);
            route[v.dst] = v.src;

            // If we reached the end exit.
            if (v.dst == end) {
                break;
            }

            for (const arc& a : adjList[v.dst]) {
                // Add nodes to frontier list.
                // That is sorted by the cost to the node.
                frontier.push({n, std::get<0>(a), v.c + std::get<1>(a));
            }
        }
        // You can start from the end node
        // and retrace the path the beginning node.
        return route;
    }


Binary HeapSort and Ternary HeapSort implementation

It's not bad. And I'm lazy, so just two comments:

static int[] array;

No statics should be ever used except for constants. Please always create an object, ideally assign everything in the constructor, and let it work on its data.

It's just a few lines more and it makes your class much more usable. Statics are sort of global variables, which means bad. The way you did it, it works... but try to start more threads and call start concurrently.

  Also should i use bit shifting like this:

No, except maybe on Android. Let the JVM do its work. It probably knows much more tricks than you (e.g., doing x / 10 without division instruction, i.e., maybe 3 times faster).


@EthanBierlein Made a really good point, but he forgot something important.
It's always a good idea to wrap your code on an anonymous function:
(function ($) {
    $(document).ready(function () {
        [code]
    });
})(window.jQuery);

This prevents problems in case you run jQuery.noConflict() before, but you forget it.

You have the following code block:
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();
    $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
});

Instead of this, consider wrapping the $.cookie call in a setTimeout:
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();
    setTimeout(function () {
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    }, 10);
});

This won't block the scroll event, which may improve UI responsiveness.
Why is that? The scroll event may be triggered multiple times a second, and that setTimeout schedules the cookie writting to a time that the browser is free.
Or that has some time for writing the cookie.
You should experiment with it.

Update!
As @Pevara pointed out in the comment section, this is not 100% a good idea.
He suggests to use a clearTimeout. From there, I could infer what he was trying to say.
Still follow the advice to use a setTimeout, but with a bigger delay (as he suggested: 250ms).
But now, the twist:
var timeout;
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();

    clearTimeout(timeout); //clear it to avoid crazy writing

    //and create a new interval to write it later
    timeout = setTimeout(function () {
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    }, 250);
});

This will eliminate all the craziness of writing cookies like mad! And will write it only once, saving the browser from re-re-re-re-writing it.


There's not really a one "right" way of doing things, and all of the others are wrong. However, there's a number of things that are considered good practice, and WRT to those, your code can do with a bit of TLC.

To that end, I'll just run through your code line by line, leaving comments on both style, and things I deem to be missing, hopefully ending up with something that is more "idiomatic" go.

package main

import (
    "log"
    "github.com/streadway/amqp"
)

Yup, I'm going to comment on your imports. The standard way to organise the imports in golang is to have multiple sections (separated by a blank line). The order is: first standard packages, second group have packages local to the project, then a third group with your external packages. In this case, the amqp package most certainly is an external one, so I'd write:

import (
    "context"
    "log"

    "github.com/streadway/amqp"
)

As you may have notices, I've also added the context package. It's a good idea to look into this one, especially once you start playing around with multiple routines. More on that later

func main() {
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

Ok, something you've probably heard before is "Don't panic". Maybe you know the phrase from the hitchhikers guide to the galaxy, but it's also one of the go proverbs. Just do a log.Fatalf("failed to connect to AMQP: %+v", err) or something. Fatal log is basically logging the output, and calling os.Exit(1).

    for _, q := range []string{"q1", "q2", "q3"} {
        go RunFetcher(q, conn, 3, 50)

    }

    select {}
}

The remainder of your main function just looks really weird. You seem to know what queues you want to consume from, but you've not given yourself any way to control the execution of the routines. Something you really would want is a way to stop the routines dead in their tracks. For example: the worker receives a kill signal, what you really want to do is cleanly terminate the workers. That's why I added the context package, because this allows you to do just that:

ctx, cfunc := context.WithCancel(context.Background())
defer cfunc() // cancel execution context when the main function returns
for _, q := range queueNames {
    go runFetcher(ctx, q, 3, 50) // no need to export this func
}

Now let's add the bit that listens for a kill/interrupt signal:

import (
    "os"
    "os/signal"
)

func main() {
    // add this:
    sch := make(chan os.Signal, 1)
    // listen for interrupt and kill signals
    signal.Notify(sch, os.Interrupt, os.Kill)

    // after you've done everything you needed to do:
    <-sch // this is blocking, so after the read, the context will be automatically cancelled thanks to the defer cfunc() we added
}

Now your worker can run indefinitely, but cleans up after itself once it receives an interrupt or kill signal. Also: we don't need the empty select {}, which looks really nasty to my eye...

func RunFetcher(queueName string, conn *amqp.Connection, workers, qos int) {
    ch, err := conn.Channel()
    if err != nil {
        log.Println(err.Error())
        return
    }

    ch.Qos(qos, 0, false)
    defer ch.Close()
    msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
    if err != nil {
        log.Println(err.Error())
        return
    }

    for index := 0; index < workers; index++ {
        go func() {
            for d := range msgs {
                // process message
                d.Ack(false)
            }
        }()
    }

    select {}
}

Ok, this is a big one to unpack. First off, let's not export this function (there's no reason to), and add the context argument as first argument to the function. Something I can't quite wrap my head around is why this function is kicked off in a routine, and doesn't even have a method of communicating any of the errors that it may encounter (for example in conn.Channel()). An error here causes an early return. To me, that error looks like something that needs to be handled. What's more, within this routine, you're actually spawning 3 subroutines that actually read from the same channel. That's fine, but it's actually this part you want to have running asynchronously. Why not change the runFetcher function to a normal function that returns an error, so you can handle it in main, and have it spawn as many routines as needed? You could also simply call conn.Channel() in the main function, and pass the Channel to the fetcher.

I'd also consider adding a loop so your fetchers can run indefinitely:

func runFetcher(ctx context.Context, queueName string, conn *amqp.Connection, workers, qos int) error {
    ch, err := conn.Channel()
    if err != nil {
        return err
    }
    // the usual stuff, but:
    msgs, err := ch.Consume(queueName, uuid, false, false, false, false, nil)

I would use a UUID package to create a unique consumer name, so we can actually stop our consumers correctly:

    // create your workers like so:
    for i := 0; i < workers; i++ {
        go func() {
            select {
            case <-ctx.Done():
                return // the context was cancelled, stop working
            case msg := <- msgs:
               msg.Ack(false) // acknowledge (or not)
            }
        }()
    }
    // now let's add this to stop the consumer
    go func() {
        <-ctx.Done()
        ch.Cancel(uuid, false) // stop consumer quickly
    }()
}

Now we're able to stop the consumers from actually getting messages from the queue, we can stop all our routines cleanly, and errors when establishing a consumer channel are actually propagated to the main function, so we can decide whether or not we want to proceed consuming messages from other queues or not.

These are some initial thoughts after quickly reading through the code. I might revisit this later on with more comments.


The first thing which stands out to me is that it's typically better to use standard functions than to roll-your-own even for trivial things. For example
val length = if (str1.length >= str2.length)
    str1.length else str2.length

could be better written as
val length = maxOf(str1.length, str2.length)

People often talk in circles about this thinking about efficiency, but that's generally a red herring. Modern compilers are pretty good at optimising, and the differences are likely to be minimal if they exist at all.
Instead, the number one reason for using a named function is readability. In the former example, I have to stop and piece together what it's actually doing. In the latter, I can see at a glance and continue to read the code fluently.
Following on from that, I can now see that it's the wrong check. Logically, a common prefix cannot be longer than the shorter of the two strings. So now that I can clearly see that the existing code is equivalent to a maxOf call, I realise it should probably instead be a minOf call.

The second thing that jumps out at me is the efficiencies of your loop. Every time you go through the loop, you are (1) comparing the whole prefix and (2) updating your return value. That is, the first time you're comparing "a" against "a" which is fine. By the third time round you're comparing "abc" against "abc", and so redoing the work of comparing "a" and "b". Then, you're taking your previous sRet object "ab", copying it and the "c" into a new string object, and assigning it back to sRet. If you're familiar with big O notation, that means that your overall function becomes O(n2) in the length of the prefix. It also means that you wind up creating and throwing away a lot of little temporary objects.
You don't need to do either. By the time you get to the third step in the loop, you already know that "ab" matches "ab" so you don't need to check again. Instead of using take to get the prefix, use get to get the actual letter. Then you can just check "c" against "c".
As to the problem of loads of throwaway sRet objects, the usual advice is to use a StringBuilder. Unlike a string, a StringBuilder is specifically made with the idea that you'll change it as you go. It's much more efficient for that purpose. However, in this case you don't need to do that because you don't need sRet at all! After all, both str1 and str2 contain the prefix you're after. You already have (and have used!) a function to get the prefix out. So just count along the two strings, comparing one character at a time. Once you know the number of characters that are the same, take it.

The final thing that I'd mention is testing. You've given one example pair of inputs to your function. That's a good thing, and it helps illustrate the problem. It's also worth thinking about what other examples are worth checking. In general for a function like this, I'd suggest it's worth testing at least the following:

str1
str2
reason

abc
xyz
It's easy to have a bug which messes up when the prefix is empty

a
b
It's easy to have a bug which messes up single character inputs

a
a
Same as above

abc
abc
It's easy to have a bug which breaks strings that are identical

abxyz
abc
You're trying to support inputs of different lengths, so this should be tested.

abc
abxyz
Same as above

abcde
abc
One string being a prefix of the other

Empty strings cause no end of problems and need to be tested

abc
Same as above


Generating absolute URIs behind a reverse proxy

This is based on a misunderstanding of the Origin header. Chrome and Safari add this header to their web requests, but other browsers don't necessarily. You only have to test this from a browser like Internet Explorer or Firefox to find out it won't work.

The Forwarded header is probably more what you're looking for.

This header-based approach could be a security issue as well, depending on your environment. If your server is accessed directly somehow, then you're basically giving the remote client control over what URLs will be generated. All the client would need to do is manipulate the right headers in the right way. Giving remote clients control over your internal URLs sounds like a very bad thing.

You're probably better off using a server-side setting (perhaps in Web.config) that contains the public URI, and using that server-side setting instead.


function swap 2 nodes in doubly linked list

Don't Return Values from void Functions

    if (!A || !B)
        return false;
    else if (A == B)
        return false;

The function void swapNode(List *listNode, char nameA[30], char nameB[30]) is declared void, which means it doesn't return a value, yet it attempts to return false in two places. Some compilers actually report this as an error. Rather than return false; it should just be return;.

The two if statements above could be rewritten as one if statement

    if ((!A || !B) || (A == B))
    {
        return;
    }

Missing Error Checking

The C programming memory allocation functions malloc(size_t size), calloc(size_t count, size_t size) and realloc( void *ptr, size_t new_size) may fail. If they do fail then they return NULL. Any time one of these functions are called, the result should be tested to see if it is NULL. Referencing fields through a NULL pointer yields unknown behavior and is generally a bug.

Node *safeMalloc(size_t size)
{
    Node* newNode = malloc(size);
    if (newNode == NULL)
    {
        fprintf(stderr, "Memory allocation failed in safeMalloc\n");
        exit(EXIT_FAILURE);
    }

    return  newNode;
}

Node *createNewNode(int point, char name[30], Node *prev, Node *next)
{
    Node *newNode = safeMalloc(sizeof(*newNode));
    newNode->point = point;
    strcpy(newNode->name, name);
    newNode->next = next;
    newNode->prev = prev;

    return newNode;
}

Declarations of Node Structs

It might have been easier to write the struct declarations as

typedef struct node
{
    int point;
    char name[30];
    struct node *next;
    struct node *prev;
} Node;

typedef struct list
{
    Node *head;
    Node *tail;
    int count;
} List;

Complexity

The function void swapNode(List *listNode, char nameA[30], char nameB[30]) can be simplified by breaking it into 2 functions, one that does the comparisons and then calls a swaping function as necessary:

void doSwap(Node *A, Node*B)
{
    Node p=*A;
    *A=*B;
    *B=p;

    B->next = A->next;
    B->prev = A->prev;

    A->next = p.next;
    A->prev = p.prev;
}

void swapNode(List *listNode, char nameA[30], char nameB[30])
{
    Node *A = NULL, *B = NULL;
    Node *temp = listNode->head;

    for (int i = 0; i < listNode->count; i++)
    {
        if (compareName(temp->name, nameA))
        {
            A = temp;
        }
        else if (compareName(temp->name, nameB))
        {
            B = temp;
        }
        temp = temp->next;
        if (A && B)
        {
            break;
        }
    }

    if ((A && B) && (A != B))
    {
        doSwap(A,B);
    }
}

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

A Good Habit for Programming in C and C++

For readability and maintainability a good good habit (best practice) to get into is to always put the actions in if statements and loops into braces ({ and }) as shown in the previous example. One of the major causes of bugs is to add a single line to the contents of an iff statement and to forget to add the necessary the necessary braces. This type of problem is very hard to track down when it doesn't result in a compiler error.

Leaks

  Are there any errors like memory leak in my code?

If the code was part of a larger project there would be memory leaks, the function free(void *ToBeFreed) is never called. It might be better if some linked list operations such as deleteNode() were added to the code.


numpy performance of norm calculation using variable dimension

Indeed, there is a better way. Exponentiation aside, we can see that this operation is equivalent to multiplication by an upper triangular matrix of 1. The former is about 100x faster. Here the code (Run it online !):

Source

from time import time as time
import numpy as np
n = 1000
m = 500
size = n * m

triu = np.triu(np.ones((m, m)))
x = np.arange(size).reshape((n, m))
y = np.zeros((n, m))

# Your implementation
tic = time()
for j in range(m):
    x_j = x[:, :j + 1]
    y[:, j] = np.linalg.norm(x_j, axis=1)
tac = time()
print('Operation took {} ms'.format((tac - tic) * 1e3))

# Optimized implementation
tic = time()
y1 = np.sqrt(np.dot(x**2, triu))
tac = time()
print('Operation took {} ms'.format((tac - tic) * 1e3))

# Optimized implementation using cumsum method
tic = time()
y2= np.sqrt(np.cumsum(np.square(x), axis=1))
tac = time()
print('Operation took {} ms'.format((tac - tic) * 1e3))

Output

Operation took 1690.1559829711914 ms
Operation took 18.942832946777344 ms
Operation took 6.124973297119141 ms


Readability of two rectangular point function samples

I'd say version A wins simply by being more succinct. Version B does however provide some extra detail, such as the fact that the point being added is being added on an edge (not inside a rectangle). Still, the structure of version A is a lot more straightforward to read.

Both version could use comments though!

I'd also replace the 1-line if..else with a simple ternary:

boxToUse = index % 2 ? box.p1 : box.p2;

Speaking of, shouldn't that be pointToUse instead of boxToUse? In either case, though, I'd ask "to use for what exactly?"

I don't know what this is used for, but I imagine a function that returns a random number in a given range would be useful elsewhere, so you might consider extracting it. Regardless, its name shouldn't be randomPoint, since it doesn't return a point - it just returns a number.

As for version B (just to give it a once over):

Using a constructor for Line is overkill. Just use an object literal: {p1: p1, p2: p2}
The switch is tricky. It has no default case and instead relies on its input being 0-3

All in all it's hard to say much more, since I don't know the context.

But a 3rd way might be better still. I'd recommend something like

// Returns a point lying on one of the rectangle's edges
// The edge is given as a number:
// 0: top edge
// 1: right edge
// 2: bottom edge
// 3: left edge
function makeRectanglePoint(rect, edge) {
  // generate a random number within the rect's height or length
  var rand = edge % 2 ? random(rect.p1.y, rect.p2.y) : random(rect.p1.x, rect.p2.x);

  switch(edge % 4) {
    case 0: return new Point(rand, rect.p1.y); // top
    case 2: return new Point(rand, rect.p2.y); // bottom
    case 1: return new Point(rect.p2.x, rand); // right
    case 3: return new Point(rect.p1.x, rand); // left
  }

  // handle errors (i.e. edge not being an integer or being negative)
  throw new Error("Edge index should be an integer between 0 and 3 (inclusive)";
}


Preparing a YouTube downloader based on Windows form

Perhaps it's a copy-paste error, but please reduce the blank lines in your code. Simply removing most of them reduces this example with one third.

Is there a reason why you use WinForms? Quite frankly I feel the technology is outdated; WPF offers you far better ways to do the same thing. For instance, you can use MVVM.

Why use Tuple<string, int, VideoType> when it would be far clearer to create a custom class? The next person to look at this code will first need to figure out what the string and the int represent, whereas if this had been a custom class they'd know the first was the URL and the second... well, I don't know what, but you get my drift.

Trunicate? Do you mean Truncate?

GlobalVariablesurlListCount is a horrible name. A property should never start with "GlobalVariables". Later on there's a GlobalVariables.urlList, so now I'm wondering if GlobalVariablesurlListCount is a typo.

Even if that's the case, having a class called GlobalVariables to pass data around indicates a bad design, and its properties don't seem to follow the capitalization guidelines: urlList should be PascalCase.

Also, urlList shouldn't be called "List", even if it is a List<T>. Just call it Urls.

I realize naming is often hard, but please avoid the temptation to name things "temp", e.g. tempTuple.

Also, why is the method named DownloadVideos when I assume it only downloads a single video?

And why would DownloadVideos return a tuple? Is this the same tuple it receives as a parameter?

(Note that I did not look at your full code at the link you provided.)

The string.Format that assigns a status to MainForm.StatusBar is 200+ characters long and contains a conditional operator. IMHO it is far to messy and far too hard to understand. Is there even a good reason to display "Final Try"? Why not simply have "(1/3)", which would also inform the user how many retries are being attempted?

Your method is called SetupDownloadingProcess but it does far more than that, doesn't it? It interacts with the UI, it logs urls that were downloaded, it even retries the download attempt. There's a lot here that looks like functionality that should be handled differently; it almost looks like you've stumbled upon mimicking a queue or a background worker.


Refreshing Google map until new data has been added to the database

In my opinion the best way to achieve what you want is to work with Event Listeners.

So basically, breaking it down to software design, you would fire a event if something is written to the database, so everytime you insert into the database. Maybe also when you update or delete something if you want to trigger these too.

Then you need an Event Listener which will run php code which runs and does what you want when new Data is added only when new Data is added.

Then you could send frequently requests to the PHP file, which gives you the message back if data is updated or not, but that would be counterproductive behavior because your already working event driven.

So you fire a Response to the JavaScript from the PHP file when the Event got fired. So your whole code will only run if it must, which depends only on if there's new data or not. Without continious requests whatsoever.

This would be the best attempt, you'll need some things for that, like the before mentioned Event Listeners, jQuery Ajax Calls or Plain JavaScript Ajax Calls.

Also some thougts to your SQL code

$count1 = $_POST['count']; //NEVER use data from Requests directly!

You're vulnerable to SQL Injection! Always escape the input and use prepared statements

$count2 = $count1+1; //Attempting to the above code there's no need for this line

And at least you can mix these 2 lines togther to one line:

$sql = mysql_query("SELECT id_history FROM tb_history");
$count3 = mysql_num_rows($sql);

Would be

$count3 = mysql_query("SELECT count(id_history) FROM tb_history");


Basic linked list stack implementation with go

Your code is a fairly good representation of a Stack, but has some issues. Some issues are in the technicalities of how your program is written, but others are in how you've used the tools available in Go.

Technicals

The exported Count value on the Stack is OK, but it should be named Size or something - Count is an ambiguous name.

There's no reason to have a capital Value. It's not an exported struct, so the field can't be exported either.

Given that you have the Count, though, you should probably use that instead of the pointer dereferences to check for an empty list.... for example, this code:

if stack.head == nil {
    return nil, errEmptyStack
}

can be

if stack.Count == 0 {
    return nil, errEmptyStack
}

Another nit-pick is that this code has redundancies:

var node = node{Value: value}
if stack.head == nil {
    stack.head = &node
} else {
    node.next = stack.head
    stack.head = &node
}

That could be written as:

stack.head = &node{Value: value, next: stack.head}

A common practice in Go is to use a boolean to indicate a success (receive on channels & values in maps). You are using an error instead. I would have written your signatures as:

func (stack *Stack) Pop() (value interface{}, ok bool)

When you have named return values in Go you should have a value-less return statement. Your Pop and Peek methods declare output parameters of value and err.... but you return specific values return nil, errEmptyStack and return stack.head.Value, nil.

You should instead have code like:

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, err error) {
    if stack.head == nil {
        err = errEmptyStack
        return
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    value = node.Value
    return
}

I would actually have bool outputs, and have.... (the zero-value for a bool is false):

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, ok bool) {
    if stack.head == nil {
        return
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    value = node.Value
    ok = true
    return
}

Go native structures

Now, the bigger issues with your stack is really about using the struct at all....

Because Go is statically typed, and has no forms of "generics" or "templates", you are forced to use interface{} as the value type. This is awkward, and requires lots of casting to use the output values from Pop and Peek.

Writing a stack on top of a Slice is what I would do.... and not have the Stack code at all. You peek the stack by reading the last element value := stack[len(stack) - 1] and push with stack = append(stack, value)


Can this JavaScript singleton be improved?

Once you start to chain properties or function calls, you incur performance penalty due to scope differences. It's best you keep the property/function depth to a minimum. This ain't Java or AS3 that needs deep namespacing.
What's the idea of getInstance()? Can't the singleton module itself be the instance?
Regarding the output image, it is correct. You get the first message at 440ms, then the singleton created the message at 442ms during init(). The next call you made is at 482ms. Since the instance was already created, the same message (the one created at 442ms) was used.

Here's a very short version of it. Basically, I just removed getInstance() and made DatapodManager the instance. No visible speed difference but you have shorter code. I also preserved the idea of it being a closure in case you ever needed private properties:

var DatapodManager = (function () {
    return {
        message: 'singleton message defined at: ' + getMilliseconds(),
        getMessage: function () {
            return this.message
        },
        id: '1234'
    }
}());


As you hinted in your question, when working with numpy, anytime you use a Python for loop when manipulating your matrices, there is a good chance there will be an opportunity to "vectorize" the operation, and speed it up.  Your code was actually a good start as it allowed you to get the right result with more familiar coding.
To convert it to a vectorized operation you then need to describe the loop in a vector style.  In this case it was as simple as removing the for and replacing the i loop variable with :
def expand(X):
    X_expanded = np.zeros((X.shape[0], 6))
    X_expanded[:, 0] = X[:, 0]
    X_expanded[:, 1] = X[:, 1]
    X_expanded[:, 2] = X[:, 0] ** 2
    X_expanded[:, 3] = X[:, 1] ** 2
    X_expanded[:, 4] = X[:, 0] * X[:, 1]
    X_expanded[:, 5] = 1
    return X_expanded

The above will almost certaily be much faster than the original.  And depending on your needs you might stop there.  But since you also asked about stacking, you can remove the intermediate np.zeros like:
def expand(X):
    return np.stack((
        X[:, 0],
        X[:, 1],
        X[:, 0] ** 2,
        X[:, 1] ** 2,
        X[:, 0] * X[:, 1],
        np.ones(X[:, 0].shape)
    ), axis=1)

Test Code:
def original_expand(X):
    X_expanded = np.zeros((X.shape[0], 6))
    for i in range(X.shape[0]):
        X_expanded[i, 0] = X[i, 0]
        X_expanded[i, 1] = X[i, 1]
        X_expanded[i, 2] = X[i, 0] ** 2
        X_expanded[i, 3] = X[i, 1] ** 2
        X_expanded[i, 4] = X[i, 0] * X[i, 1]
        X_expanded[i, 5] = 1
    return X_expanded

data = np.array(list(zip(range(10), range(1, 11))))
assert not (expand(data) - original_expand(data)).any()


Generate two random primes and find their totient

One problem, pointed out in comment by @chepner is that you are recomputing the primes twice. Save the primes, so you don't have to recompute.

Also, in your inner loop, you are unnecessarily dividing by every number up to v. Instead, you should skip all non-primes and only test divisibility by the primes, up to your largest known prime (because all other numbers up to there can be factorized into these primes). Only after that do you need to test divisibility for each integer max(primes) < i < v. Skipping all non-primes up to max(primes) saves a lot of looping/divisions/comparisons for large lim (especially given that the distance between consecutive primes tends to increase as lim increases). Something like this will give you a big speedup:

def primeGenFast(lim):
    fnl=[]
    primes=[2]

    fnl = list(range(2,lim+1))
    for v in fnl:
        p=1
        for n in primes:
            if v%n == 0:
                p = 0
                break

        if p==1:
            for i in range(primes[-1],v):
                if (v%i==0):
                    break
                if i==(v-1):
                    primes.append(v)

    return primes

This gives a speedup of nearly 10-20x on my machine, increasing as the size of lim increases:

In [3]: timeit(primeGenSlow(10000))
1 loop, best of 5: 465 ms per loop

In [6]: timeit(primeGenSlow(25000))
1 loop, best of 5: 3.98 s per loop

In [8]: timeit(primeGenSlow(100000))
1 loop, best of 5: 38.1 s per loop

----

In [2]: timeit(primeGenFast(10000))
10 loops, best of 5: 29.6 ms per loop

In [5]: timeit(primeGenFast(25000))
1 loop, best of 5: 307 ms per loop

In [7]: timeit(primeGenFast(100000))
1 loop, best of 5: 1.91 s per loop


Calculating the perfect squares between two given numbers

First things first. You have to organize your code and group functionality into methods. So I would suggest creating a method int[] getPerfectSquaresBetween(int start, int end).

Let's enhance your algorithm. The key idea is to get the square root of the next perfect square number. This can be achieved by ceil the sqrt of the starting point:

int candidate = (int) Math.ceil(Math.sqrt(start));

This variable is the basis for our calculations. All we have to do now is to check if the candidate squared is in the given range.

int square;
while ((square = candidate * candidate) < end) {
  //...
  candidate++;
}

Putting everything together looks like this:

public static int[] getPerfectSquaresBetween(int start, int end) {
  if (start > end || start < 0) {
    throw new IllegalArgumentException();
  }
  int[] perfectSquares = new int[end - start];
  int nr = 0;
  int candidate = (int) Math.ceil(Math.sqrt(start));
  int square;
  while ((square = candidate * candidate) < end) {
    perfectSquares[nr++] = square;
    candidate++;
  }
  return Arrays.copyOf(perfectSquares, nr);
}

Let's check the algorithm: getPerfectSquaresBetween(0, 101) (which completes in microseconds)

  [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


Update existing key value if present and then deserialize json to POCO efficiently

Even if ProcessValue is used as string in other objects, why you don't just deserialize it once across the class, then use the POCO object directly. Then, serialize it whenever needed.
So, in your question this would be valid :
ProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A

if (!string.IsNullOrWhiteSpace(ProcessValue))
{
    ProcCustomer = DeserializeJson<ProcCustomer>(ProcessValue);

    if (ProcCustomer != null && !string.IsNullOrWhiteSpace(ProcCustomer.ClientId))
    {
        ProcCustomer.ClientId = HttpUtility.HtmlEncode(ProcCustomer.ClientId);
    }
}

This way you only deserialized it once in this scope. Also, if the client_id is always needs to be encoded using HttpUtility.HtmlEncode you could modify the POCO and do this for instance :
public class ProcCustomer
{
    //.. other properties

    [JsonProperty("client_id")]
    public string ClientId
    {
        get => ClientId;
        set
        {
            if(!string.IsNullOrEmpty(value))
            {
                ClientId = HttpUtility.HtmlEncode(value);
            }
            else
            {
                ClientId = value;
            }
        }
    }
}

With this, your code will be shorter as you only need to deserialize, the rest will be updated according to the POCO logic!
Answering the comments :
working with ProcessValue as string, will make things difficult to handle. What I suggested is to use the deserialized object (which is the POCO in your case), then work with it like any object. When you want to pass it to the HttpClient header, just serialize it, to pass it as sting.
The main idea is to work with objects, and not with the strings! use the strings only when required. This way you'll have a better coding experience.
For example, we can modify the POCO and override the ToString method like this :
public class ProcCustomer
{
    public override string ToString() {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
}

Now, when we want to add it to the header we can do this (example) :
// assuming we've already updated the POCO values
// and we need to add it to the HttpClient header
using (var client = new HttpClient{ BaseAddress = baseAddress })
{
    client.DefaultRequestHeaders.Add("", ProcCustomer.ToString());

    using (var response = await client.GetAsync(Url))
    {
        var responseData = await response.Content.ReadAsStringAsync();
    }
}

If you can't modify the POCO, then you can add extensions like this :
// implement the extensions
public class JsonExtensions
{
    public T JsonDeserialize<T>(this string str) where T : class
    {
        try
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }
        catch (Exception e)
        {
            return default;
        }
    }

    public string JsonSerialize<T>(this T obj) where T : class
    {
        try
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject<T>(obj);
        }
        catch (Exception e)
        {
            return null;
        }
    }
}

You can use the extensions instead of ToString approach
// EXAMPLE :

ProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A

if (!string.IsNullOrWhiteSpace(ProcessValue))
{
    ProcCustomer = ProcessValue.DeserializeJson<ProcCustomer>();

    if (ProcCustomer != null && !string.IsNullOrWhiteSpace(ProcCustomer.ClientId))
    {
        ProcCustomer.ClientId = HttpUtility.HtmlEncode(ProcCustomer.ClientId);

        ProcessValue = ProcCustomer.JsonSerialize();
        // or do it directly in the httpClient instead of ProcCustomer.ToString()

    }
}


Passing a large amount of diverse information in JSON using Symfony 2.1 and Doctrine 2

I think that what you have is probably fine. Personally, I'd move the construction of the result array to a view but this is not that big of a deal. That might help with the "clunkiness".

With regards to your concern about the size of the json response: You say that all of the information in it is needed by the app. It doesn't look all that big to me. Unless you are actually experiencing problems as a result of the size, I'd leave it alone. If it were too big, you could consider implementing appropriate caching (allow the browser to cache the results and/or use etags) or pagination.

Regarding the number of individual sql calls: I'm sure you could put it all into one query if need be.

Both of these potential issues, response size and number of queries, seem to me to be pre-optimization concerns. In the past, I've spent lots of time pre-optimizing stuff and never realized any real gain. Now, I implement what is needed and only optimize when the real need arises. The bottom line: I don't see any problems with what you've got and unless the result is unacceptably slow or resource intensive, don't worry about it.

Hope it helps.


A beautiful and easy way of permutation with recursion

The simpler code would look something like this:

#include <string>
#include <algorithm>
#include <iostream>

int main() {
    std::string s = "abcde";

    while (std::next_permutation(s.begin(), s.end()))
        std::cout << s << "\n";
}

If you wanted to do something on the same general order as a Python generator, you'd use C++'s new coroutine support. What's currently included is (by intent) very low-level, so you need a fair amount of infrastructure on top of it before it's easy to write a Python-like generator.

To keep from getting buried in details you probably don't care a lot about (right now) I'll use Kenny Kerr's Generator class (the first 173 lines, transplanted into a header). Using it, we get something like this:

#include "generator.hpp"
#include <iostream>
#include <string>
#include <algorithm>

template <class T>
generator<T> perm(T initial) {
    while (std::next_permutation(initial.begin(), initial.end()))
        co_yield initial;
}

int main() {
    using namespace std::literals;
    for (auto const &i : perm("abcde"s))
        std::cout << i << "\n";
}

As to your code, a few points jump out:

Don't use std::endl. It flushes the stream, which you almost never want. Just use '\n'. On the rare occasion that you do want to flush the stream, use std::flush.
The C library reserves most names that start with str, so it's probably better to avoid using that as a name.
using namespace std; is widely considered a problem except under a small number of rather unusual circumstances.
If you really want to do this (more) on your own, you might want to take a look at std::rotate, which can replace both your swap2 and swap3. std::rotate will also typically be more efficient than your implementation.
swap2 and swap3 strike me as poor names. At first glance, it seems like rotate_left and rotate_right would probably be better names (but also see above).


Filter an array of objects by an array in AngularJS

welcome to CodeReview :-)

Firstly, I would mention that your $item and $model parameters should just be item and model. The dollar-sign prefix is conventionally reserved for official vendor libraries from Angular, and should not be used in your code to prevent confusion. I initially thought $model was a derivative of ngModel!

Secondly, do you need selectedIds? Can you not just use a function to extract those IDs? You do not need to watch a seperate array of IDs.

Thirdly - delete result.data[key] - this is not how you use delete. You use delete to remove properties from objects, not key/value pairs from collections. Instead, you should just set it to undefined.. with that said, you don't even need to use delete here anyway.

Fourthly.. what the hell is going on with for(key in result.data) if(result.data.hasOwnProperty(key)... that code is iterating the data then checking that the data has that property. wat. This works for circumventing prototypal inheritance, however you can just as easily use Object.keys(). Not to mention that the result of a $http request is only going to inherit from Object.

With that said, here's a refactor of your code. You will need lodash for this code to work, but no worries - lodash is probably the most handy library you will ever come across in JS. I use it on every project these days.

$scope.usersList = {
  items: [],
  search: function(term) {
    if(term.length > 2) {
      UsersService.lookup(term)
        .then(function(xhr) {
          return _.reject(xhr.data, function(item) {
            return _.contains($scope.usersList.items, item);
          });
        })
        .then(function(data) {
          $scope.usersList.items = data;
        });
    }
  }
};

I've removed the select, remove and extractId functions as they do nothing in my example (and they did nothing anyway!)

This could definitely be refactored even better in my opinion, but I would need more scope on the actual problem to do that. For example, there's no need to use the $scope here aside from exposing the results to the view. This would be much better done if it was encapsulated inside of a function and only the result was exposed. This should really be in two separate classes at least.


New regex

If you change your regular expression to the following you won't need to even do str.strip()

valuepattern = re.compile("'(\d+)'")

List Comprehension

Alternatively if you don't want to do that, you could do the following. Currently you have:

for item in l:
    li.append(item.strip("'"))

This can be replaced with a list comprehension:

l = [x.strip("'") for x in l]

Final Note

As you compile your regular expression, you can replace

re.findall(valuepattern, s)

with

valuepattern.findall(s)


There are a number of issues in your code that I can see:

Input validation.

public void createBinaryTree (Integer[] arr) {
    if (arr == null)  {
        throw new NullPointerException("The input array is null.");
    }

    root = new TreeNode(null, null, arr[0]);

You check the arr is not null, but you do not check that its arr.length > 0. An empty array will cause an ArrayIndexOutOfBounds exception.
AutoBoxing

You have the method:

public void createBinaryTree (Integer[] arr) { ... }

which takes an array of Integer[], which you then have to check for nulls in, and then you store the values away as:

current.left = new TreeNode(null, null, arr[left]);

where the constructor for TreeNode is an int value.

Why do you take an Integer[] array at all? it should all be int[]...

As a consequence, you have null-value issues in your code which make your code harder to read.
The inner iteration of your code is unnecessarily complicated. This code here:

    for (int i = 0; i < half; i++) {
        if (arr[i] != null) {
            final TreeNode current = queue.poll();
            final int left = 2 * i + 1;
            final int right = 2 * i + 2;

should not start with i = 0 because arr[0] was already included as the root. This is not obvious. You should have code that looks more like (note the + 1 and + 2 have been changed to  and + 1 respectively):

    // start at 1 because arr[0] is already processed.
    for (int i = 1; i < half; i++) {
        if (arr[i] != null) {
            final TreeNode current = queue.poll();
            final int left = 2 * i;
            final int right = 2 * i + 1;

In your recursion method, set is a really, really bad variable name, it should be dupcheck or something.
BUG your code does not find the least common ancestor (for whatever definition of Least you choose). This code here:

boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set);
boolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set);

means that if there is a (duplicate) match in both the left, and the right, that whatever happened in the 'left' side is kept, and whatever happens in the right side is 'forgotten' (because you later have the check && lcaData.lca == null ). As a result, you only identify the 'left-most' common ancestor.


Searching a list of an int arrays into another list of int arrays

The original code:

public List<int[]> GetDuplicates(List<int[]> pInputList1, List<int[]> pInputList2)
{
    var outputList = new List<int[]>();

    pInputList2.ForEach(x =>
    {
        outputList.AddRange(pInputList1.Select(j => j).Where(y =>
        {
            for (int i = 0; i < y.Length; i++)
                if (y[i] != x[i])
                    return false;
            return true;
        }));
    });

    return outputList;
}

I'd start with a few readability simplifications first:

Select(j => j) is a no-op and can be removed
The usage of ForEach is hurting readability (and performance, due to passing delegates around) a little bit
Moving the pInputList1.Where(...) outside of the AddRange also makes it clearer what's going on.

public List<int[]> GetDuplicates(List<int[]> pInputList1, List<int[]> pInputList2)
{
    var outputList = new List<int[]>();

    foreach (var x in pInputList2)
    {
        var duplicates = pInputList1.Where(y =>
        {
            for (int i = 0; i < y.Length; i++)
                if (y[i] != x[i])
                    return false;
            return true;
        });

        outputList.AddRange(duplicates);
    }

    return outputList;
}

Next, as mentioned in the comments, the intention is to filter the second list according to whether an identical array appears in the first list. The method and its arguments (and derived local variables) should be renamed to reflect that. I'd also swap the parameters over, because pInputList2 is the important part of the method, while pInputList1 is the set against which pInputList2 is checked.

public List<int[]> FilterByWhitelist(List<int[]> testArrays, List<int[]> whiteListedArrays)
{
    var outputList = new List<int[]>();

    foreach (var testArray in testArrays)
    {
        var duplicates = whiteListedArrays.Where(whiteListedArray =>
        {
            for (int i = 0; i < whiteListedArray.Length; i++)
                if (whiteListedArray[i] != testArray[i])
                    return false;
            return true;
        });

        outputList.AddRange(duplicates);
    }

    return outputList;
}

Using the same point in the comments: we don't need to find every matching array in whiteListedArrays - we only need to know whether there is one. As such, we can use Any instead of Where:

public List<int[]> FilterByWhitelist(List<int[]> testArrays, List<int[]> whiteListedArrays)
{
    var outputList = new List<int[]>();

    foreach (var testArray in testArrays)
    {
        var isWhiteListed = whiteListedArrays.Any(whiteListedArray =>
        {
            for (int i = 0; i < whiteListedArray.Length; i++)
                if (whiteListedArray[i] != testArray[i])
                    return false;
            return true;
        });

        if (isWhiteListed)
        {
            outputList.Add(testArray);
        }
    }

    return outputList;
}

Another bug in this implementation is: what if one of your testArrays is longer than one of the whiteListedArrays? You're accessing x[i] while only ensuring that i is less than the length of y. You'll probably get an ArgumentOutOfRangeException from this. Because two arrays can't be equal if their lengths don't match, this should be checked first.

On the other hand, Linq has a nice built-in method for checking whether two sequences are equal:

public List<int[]> FilterByWhitelist(List<int[]> testArrays, List<int[]> whiteListedArrays)
{
    var outputList = new List<int[]>();

    foreach (var testArray in testArrays)
    {
        var isWhiteListed = whiteListedArrays.Any(
            whiteListedArray => testArray.SequenceEqual(whiteListedArray));

        if (isWhiteListed)
        {
            outputList.Add(testArray);
        }
    }

    return outputList;
}

This method now iterates once over its main argument, and returns a subsequence of that argument. This sounds like an ideal scenario for an extension method on IEnumerable.

public static IEnumerable<int[]> FilterByWhitelist(this IEnumerable<int[]> testArrays, List<int[]> whiteListedArrays)
{
    foreach (var testArray in testArrays)
    {
        var isWhiteListed = whiteListedArrays.Any(
            whiteListedArray => testArray.SequenceEqual(whiteListedArray));

        if (isWhiteListed)
        {
            yield return testArray;
        }
    }
}

This would be called like:

var originalList = new List<int[]> { ... };
var whiteList = new List<int[]> { ... };

var filteredList = originalList.FilterByWhitelist(whiteList).ToList();

One final performance improvement I can see is pre-grouping the whiteListedArrays by length, and only testing for sequence equality where the lengths are already known to be equal:

public static IEnumerable<int[]> FilterByWhitelist(this IEnumerable<int[]> testArrays, List<int[]> whiteListedArrays)
{
    var lengthGroupedWhiteListedArrays = whiteListedArrays
        .GroupBy(arr => arr.Length)
        .ToDictionary(group => group.Key, group => group.ToList());

    foreach (var testArray in testArrays)
    {
        List<int[]> lengthMatchedWhiteListedArrays;

        if (!lengthGroupedWhiteListedArrays.TryGetValue(testArray.Length, out lengthMatchedWhiteListedArrays))
        {
            continue;
        }

        var isWhiteListed = lengthMatchedWhiteListedArrays.Any(
            whiteListedArray => testArray.SequenceEqual(whiteListedArray));

        if (isWhiteListed)
        {
            yield return testArray;
        }
    }
}

At this point, we're only iterating over whiteListedArrays once, so that too can become an IEnumerable:

public static IEnumerable<int[]> FilterByWhitelist(this IEnumerable<int[]> testArrays, IEnumerable<int[]> whiteListedArrays)
{
    var lengthGroupedWhiteListedArrays = whiteListedArrays
        .GroupBy(arr => arr.Length)
        .ToDictionary(group => group.Key, group => group.ToList());

    foreach (var testArray in testArrays)
    {
        List<int[]> lengthMatchedWhiteListedArrays;

        if (!lengthGroupedWhiteListedArrays.TryGetValue(testArray.Length, out lengthMatchedWhiteListedArrays))
        {
            continue;
        }

        var isWhiteListed = lengthMatchedWhiteListedArrays.Any(
            whiteListedArray => testArray.SequenceEqual(whiteListedArray));

        if (isWhiteListed)
        {
            yield return testArray;
        }
    }
}

We could, at this point, extract the array-specific code into a class that encapsulates the whitelist:

public class Whitelist
{
    private readonly IReadOnlyDictionary<int, List<int[]>> _lengthGroupedWhiteListedArrays;

    public Whitelist(IEnumerable<int[]> whitelistedArrays)
    {
        _lengthGroupedWhiteListedArrays= whitelistedArrays
            .GroupBy(arr => arr.Length)
            .ToDictionary(group => group.Key, group => group.ToList());
    }

    public bool Contains(int[] item)
    {
        List<int[]> correctLengthFilterArrays;

        if (!_lengthGroupedWhiteListedArrays.TryGetValue(item.Length, out correctLengthFilterArrays))
        {
            return false;
        }

        return correctLengthFilterArrays.Any(filterArray => item.SequenceEqual(filterArray));
    }
}

...

public static IEnumerable<int[]> FilterByWhitelist(this IEnumerable<int[]> testArrays, Whitelist whitelist)
{
    foreach (var testArray in testArrays)
    {
        if (whitelist.Contains(testArray))
        {
            yield return testArray;
        }
    }
}

Although by doing this, FilterByWhitelist has more or less become Linq's Where:

var originalList = new List<int[]> { ... };
var whiteList = new Whitelist(new List<int[]> { ... });

var filteredList = originalList
    .Where(arr => whiteList.Contains(arr))
    .ToList();

This way, the pre-grouping of array lengths can be used in many places.


Permutation 1...N. Answer queries "How many numbers between [X,Y] position are in the interval [L,K]"?

I believe the problem lies in the initialization time. If I am not wrong it is like O(n^2 log n) which might be a problem for tests with large n and small sample size.

To fix it you'll have to redo the whole algo if I am not mistaken.

There is a method that doesn't have the same long initialization problem while retaining the same O(log n) (at least on average, O(log^2 n) at worst) time per iteration - simply build a two dimensional segment tree. Since we work with a permutation it will be rather sparse.


Just a few comments:

std::vector<Vector2f> make_bezier(const std::vector<Vector2f>& anchors, double accuracy=10000.0)

You're using float for all your other floating point variables. Unless there's some really good reason to use double here (for accuracy) I'd consider changing it to a float as well.

std::vector<Vector2f> end;
end.push_back(anchors[0]);

for(float i=0.f; i<1.f; i+=1.f/accuracy)

I'd write this a bit differently. As it stands, i can accumulate rounding errors from one iteration of the loop to the next. I'd prefer to do something like:

for (int j=0; j<accuracy; j++) {
    float i = 1.0f/j;
    // ...

This way, each value of i is computed independently, and rounding from one iteration doesn't affect its value in the next.

    std::vector<Vector2f> temp;
    for(unsigned int j=1; j<anchors.size(); ++j)
        temp.push_back(Vector2f(interpolate(anchors[j-1].x, anchors[j].x, i),
                                interpolate(anchors[j-1].y, anchors[j].y, i)));

Literally all your calls to interolate (at least in this code) happen in pairs. That being the case, I think I'd rewrite it a bit to take a couple of vector2fs as parameters, and return a vector2f containing the interpolation on both the x and y components of the inputs. It also uses i as a third input. My immediate reaction would be to define interpolate as a lambda that captured i, and took the other two parameters as inputs.

vector2f interpolate(vector2f in1, vector2f const &in2) {
    in1.x = /* ... */;
    in1.y = /* ... */;
    return in1;
}

With that in place, the loop above can be reduced to a fairly simple application of std::transform, something like this:

 std::transform(anchors.begin(), anchors.end(),
                anchors.begin()+1,
                std::back_inserter(temp));

Of course, pretty much the same would happen here:

        for(unsigned int j=1; j<temp.size(); ++j)
            temp2.push_back(Vector2f(interpolate(temp[j-1].x, temp[j].x, i),
                                     interpolate(temp[j-1].y, temp[j].y, i)));

...as well.


Semantic HTML5 structure and Google penalty

Semantically, a heading should contain text, not an image.

Also, somewhat more important from an SEO perspective, the
 element should relate to the specific page. Unless this site is a single page, having the same
 on every page would be a very bad idea.

Generally, ranking for the company name is a given (unless the company is called 'Cheap Viagra Cialis Online ltd"...).

I would remove the heading tag from the page header:

            <svg id="header-logo" class="header-logo" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title desc" viewBox="0 0 158 24.7">
                <title id="title" itemprop="headline">Brand Name</title>
                <desc id="desc" itemprop="description">- brand description</desc>

            </svg>

And swap the
 in the content section for an
:

Main content header


Increase performance of removing character from String

Learn from existing implementations, they usually have solutions to corner cases, common pitfalls and performance bottlenecks. For example, Apache Commons Lang StringUtils also has a remove function. It's implementation is quite simple and similar to yours:

public static String remove(final String str, final char remove) {
    if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
        return str;
    }
    final char[] chars = str.toCharArray();
    int pos = 0;
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] != remove) {
            chars[pos++] = chars[i];
        }
    }
    return new String(chars, 0, pos);
}

Anyway, there are some differences:

It uses char array. Strings are immutable, the following concatenation creates a new String object:

newstr = newstr + str.charAt(i);

I guess it's slower than changing a value in an array.

  Using the string concatenation operator
  repeatedly to concatenate n strings requires time quadratic in n.

Source: Effective Java, 2nd edition, Item 51: Beware the performance of string concatenation
At the first line it checks whether the String contains the removed character at all. If it doesn't contain it remove saves the creation the char array. It might help but it depends on your input.
The code in the question calls String.charAt() in the comparison which checks the given index:

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

The StringUtils implementation skips this test since it knows that the index is valid.

(See also: Effective Java, 2nd edition, Item 47: Know and use the libraries)


Finding prime numbers in user specified array

Indentation

Your indentation in run() and other methods can be improved:

boolean prime = true;
       for (int j = 2; j < n; j++) {
               if (n%j == 0){
                   prime = false;
                   break;
                     }
       }

At first, I thought that was another level of nesting.  You should write it like this.

boolean prime = true;
for (int j = 2; j < n; j++) {
    if (n%j == 0){
        prime = false;
        break;
    }
}

Naming

Don't name loop variables any random number:

for (int n = start; n <= end; n++) {
    for (int j = 2; j < n; j++) {

You should give them a name describing what they are:

for (int potential_prime = start; potential <= end; potential++) {
    for (int divisor = 2; divisor < n; divisor++) {

Algorithm

When you check whether any number n is prime, you check the divisors j from 2 to n.  If a divisor j is greater than the floor (sqrt (n)), you need not check it.  This is because once you get above this number and less than n / 2, you are only checking for the reverse pairs you checked before (4 * 5 == 5 * 4), and any number greater than n / 2 cannot go into n more than once.  Eliminating these extra checks could greatly speed your algorithm up on very large numbers.


The variable names you chose are quite bad. I can't seem to figure out what r and c are as constructor input.

Creating such views only for vectors (of ints) is a bit wasteful. You are basically wrapping an iterator pair, so why not make the code generic so that it woks with iterators of any type of container?

Boost, for example, provides Boost.Range for doing just this.

When you implemented a specialized container, you create specialized iterators that know how to traverse it. The view/range stays the same, it's job is still to wrap a pair of iterators.


Replacing all keys found in a dictionary for its value in a list

The main suggestion I'd make is to use Dictionary<char,char>.  This allows to work with char collections and convert them to strings rather than continuously concatenating strings.

This also allows you to leverage LINQ to do the replacement and shorten your code tremendously.

It could look like this:

public Dictionary<char, char> Chars { get; set; } = new Dictionary<char, char>();

// Called in my constructor
public void CreateDictionnary()
{
    Chars.Add('\u001b', ' ');
    Chars.Add('\u0000', ' ');
    // Multiple other characters that I have to replace
}
public List<string> ReplaceSpecialCharacters(List<string> lines)
{
    for(int i = 0; i < lines.Count; ++i)
    {
        lines[i] = new string(lines[i].Select(x => Chars.ContainsKey(x) ? Chars[x] : x).ToArray());
    }
    return lines;
}

Incidentally this lowers the complexity from O(n²m),the total number of characters squared times the number of entries in the dictionary, to O(n²).  Which since you're dealing with strings is probably about the best you can get.  If you want it better, storing the data as char arrays instead of strings allows the replacement to be in-place instead of creating new strings.  This could be done in O(n) complexity.


Well, I believe the second one is more obvious what's going on...

if( that.indexOf('hello') != -1 ) {
}

That's all to it however, both expressions are valid and perfectly ok.


URLIfy a character array using Python - follow-up

\$O(n)\$ time with \$O(1)\$ space is a hard, and somewhat extreme requirement.
Sure the \$O(n)\$ can be achieved easily. But the \$O(1)\$ is not.

Using lists, to achieve \$O(1)\$ means you have to change the list in-place.
This means any slicing or helper methods are instantly not an option.
This was pointed out by 200_success.
Take:

>>> a = 'abc  '
>>> id(a)
51272544
>>> id(a.strip())
48713152
>>> id(a[:-2])
44833440
>>> del a[-2:]
TypeError: 'str' object does not support item deletion
>>> a = list('abc  ')
>>> id(a)
51232040
>>> id(a.strip())
AttributeError: 'list' object has no attribute 'strip'
>>> id(a[:-2])
51246424
>>> del a[-2:]
>>> a
['a', 'b', 'c']
>>> id(a)
51232040

So to achieve the requirements you need is hard.
And I'd say unreasonable in the real world.

I also agree with Phrancis that your functions input is bad.
To achieve what you want, we'd want to manually implement strip.
And we're only allowed to make in place changes to the array.
This means the function will be, using type hints, inplace_strip(data: list).

Since strip removes just spaces at the front and back of the list, it's easy to implement efficiently.
Just count the amount of places to remove from the front and back, and then delete them.

def inplace_strip(data: list):
    for i in range(len(data)):
        if data[i] != ' ':
            break
    else:
        del data[:]
        return None
    if i:
        del data[:i]

    for i in range(len(data)-1, -1, -1):
        if data[i] != ' ':
            break
    if i != len(data):
        del data[i+1:]

Is this still \$O(n)\$ time? Yes.
If we look at the time complexity of the list operations I used, then we should see that they are all \$O(n)\$ or smaller.
And so the function is \$O(n)\$.

After this we need to mutate the list so that we can change all ' ' to '%20'.
There are three ways we can do this:

Set Item, changes the return to ['a', 'b', '%20', 'c'].
Set Slice, has the time complexity of \$O(k+n)\$.
Generator, you're going to change the space complexity outside of this function to \$O(n)\$.

So it's really a hard choice.
I'd use a generator as the function 'has no problems', it's you who's changing the space complexity to \$O(n)\$.
And so when ever you get a ' ' you'll yield the '%20'.
But you'll split it up so that there's three yields.

This makes the function simply:

def urlify(data: list):
    inplace_strip(data)
    for char in data:
        if char == ' ':
            yield '%'
            yield '2'
            yield '0'
        else:
            yield char

A function which will always have the usage as, ''.join(urlify(data)).
And so wastes all that hard work.
Instead I'd say to use str.strip and str.translate, this makes the code much simpler, which allows you to change the function to:

def urlify(data: list):
    return data.strip().translate({ord(' '): '%20'})


Computing even huger Fibonacci numbers in Java - follow-up

Theory

As described in a related Python answer, it's possible to refactor the recursion into a for loop and to use matrix arithmetics without using matrices.

Code

import java.math.BigInteger;

public class LargeFibonacciNumbers
{

    public static BigInteger fibonacci(int n) {
        BigInteger f_n = BigInteger.ZERO;
        BigInteger f_n_plus_1 = BigInteger.ONE;
        BigInteger two = BigInteger.valueOf(2);
        BigInteger f_n_plus_1_squared, f_2n, f_n_squared, f_2n_plus_1;
        for (int i = Integer.SIZE - Integer.numberOfLeadingZeros(n); i >= 0; i--) {
            f_n_squared = f_n.multiply(f_n);
            f_n_plus_1_squared = f_n_plus_1.multiply(f_n_plus_1);
            f_2n = f_n.multiply(f_n_plus_1).multiply(two).subtract(f_n_squared);
            f_2n_plus_1 = f_n_squared.add(f_n_plus_1_squared);
            if ((n >> i & 1) == 1) {
                f_n = f_2n_plus_1;
                f_n_plus_1 = f_2n.add(f_2n_plus_1);
            } else {
                f_n = f_2n;
                f_n_plus_1 = f_2n_plus_1;
            }
        }
        return f_n;
    }

    public static void main(String[] args) {
        int n = 10000000;
        long start = System.nanoTime();
        System.out.println(fibonacci(n).bitLength());
        long finish = System.nanoTime();
        System.out.println((finish - start) / 1000000 + " ms");
    }
}

Comments

bitLength() isn't defined for ints, so this method has been used instead.

Performance

This code calculates the 10-millionth Fibonacci number in less than 1.5s on my computer. In comparison, the matrix version needs almost 4s.

Note that the test code only displays the bit length of the result, not the result itself. fibonacci(1E7) has more than 2 million digits, and it takes much longer to display it in the console than to calculate it.


Argument-parsing class in Python to handle a --force flag

In my opinion, no, this isn't any better than just making use of the tools that argparse provides out of the box and a class is overkill. argparse.ArgumentParser operates in a very similar way, so it should be just as easy to call it straight-up:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "--force",
    default=False,
    help="Force the program to run, even if the timer returns False.",
    action="store_true"
)
args = parser.parse_args()
# ...
if args.force:
    # ...


Project Euler #14 - Longest Collatz Sequence in Python

Memoization

Storing results that have already been computed is known as memoization. Your current function's structure wouldn't work very well since collatzSeq isn't recursive, and you only call it with unique values. After all, the real time savers would be with all the intermediate collatz sequence values.

Restructuring your code to be recursive would make setting up the memoization a lot easier:

def collatz_seq(n):      # no space after function, snake case preferred in python
    if n == 1:           # base case
        return 1
    elif n % 2 == 0:     # recursive definitions
        return collatz_seq(n // 2) + 1     # integer division
    else:
        return collatz_seq(3*n + 1) + 1

Recusion is where you define a function in terms of itself and a base stopping condition.

Now we can easily set up memization using a dictionary:

memo = {}                               # initialize the memo dictionary
def collatz_seq(n):
    if not n in memo:                   # check if already computed
        if n == 1:                      # if not compute it
            memo[n] = 1                 # cache it
        elif n % 2 == 0:
            memo[n] = collatz_seq(n // 2) + 1
        else:
            memo[n] = collatz_seq(3*n + 1) + 1
    return memo[n]                      # and return it

So what's going on here? First we create an empty dictionary called memo. It's crated outside the function so that it persists through each function call. Next check if collatzSeq(n) has already been computed. If not compute the value, and then store it in the memo. Finally return the chached result.

This is great since once a number's collatz sequence length is computed, it never needs to be computed again. This really saves on computation time!

For more memoizaiton info check out this great SO question.

Maximum Stack Depth

Python has a maximum stack depth of 1000 (by default) which sometimes messes with recursive functions if they go too deep. I don't how long the longest collatz sequence under 1000000 is, so I don't know if this is relevent to your problem. But if you run into issues, you can change the maximum depth.


Formatting

First, the way you wrote this makes it difficult to understand what you are trying to do. Here are a few points to improve it:

Use indentation and line breaks that illustrates your nesting. I provided an example below.
Use all caps for keywords (or all lower case, just be consistent).
Back ticks are not required unless you have a space or reserved operator in your code. It makes the code easier to follow without them.

Here is an example, this:

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 7 DAY) group by `itemID`), '0') as `sold7`,

Could be:

IFNULL(
    (SELECT SUM(history.quantity)
    FROM history
    WHERE history.itemID = items.id
    AND history.date > DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY itemID
    ), 0
) AS sold7,

Performance

The first problem I see is the excessive use of IFNULL() and subqueries within them. I'm not sure as to why you are replacing NULL with 0 as your aggregate functions will factor NULLs out anyways. But I suppose you have a reason to do this that I don't understand.

I have at least three recommendations:

If your dataset is very large, you may want to break it down into smaller steps using a temporary table.
You would likely want to use a LEFT JOIN instead of subqueries.
I would strongly suggest to create a stored procedure as this looks like the type of query that is run regularly. That way the execution plan will saved with your query.

Here you go:

DELIMITER $$
    CREATE OR REPLACE PROCEDURE proc_MyProcedure() AS -- pick a meaningful name
    BEGIN
    INSERT INTO TEMPORARY TABLE temp_MyTable -- pick a meaningful name
     SELECT items.id AS itemID,
      history.quantity AS historyQty,
      history.date AS historyDate,
      supply.supply AS supplyQty,
      supply.date AS supplyDate
     FROM items
     LEFT JOIN supply ON items.id = supply.itemID
     LEFT JOIN history ON items.id = history.itemID
     WHERE history.date > DATE_SUB(NOW(), INTERVAL 180 DAY)
     OR supply.date  > DATE_SUB(NOW(), INTERVAL 180 DAY)
    ;
    -- here we set nulls to 0
    UPDATE temp_MyTable
    SET historyQty = 0
    WHERE historyQty IS NULL;
    UPDATE temp_MyTable
    SET supplyQty = 0
    WHERE supplyQty IS NULL;
    -- finally we aggregate on the temp table
    SELECT  (SELECT SUM(historyQty) FROM temp_Mytable WHERE history.date > DATE_SUB(NOW(), INTERVAL 7 DAY)) AS sold7,
     (SELECT ROUND(supply) FROM temp_MyTable WHERE supplyDate > DATE_SUB(NOW(), INTERVAL 7 DAY)) AS listed7,
    -- etc.
    FROM temp_MyTable
    GROUP BY itemID;
    END$$
DELIMITER ;

Then just CALL proc_MyProcedure(). You will notice the first time takes longer, but any subsequent calls should be much faster.


Simple program that simulates StackOverflow post

Just keeping a count is fine for the example app, you don't want to go mad with your implementation. Consider that in real life, you need to know who voted and when. There are various rules about when you can change your vote and when it's locked in. So although your code is fine for the simple 'show me the score' question there are some that you can't answer:

How many votes has the post had in the last day?
What is the split of up and down votes?
Am I allowed to change my vote now?
Have I already voted?

All of those questions (and more) would need to be supported by your final design. If you just wanted to support 2 for now, you could track the up and down votes separately.

As for your code, I'd split out the up and down votes and add a get only property called Score.

Worth noting, if you plan on supporting multiple regions you have to store you dates and times unambiguously. Usually, that means storing in UTC.

so

  DateTime.Now

Should have been

DateTime.UtcNow

If you just used the first, consider what would happen around any Daylight Saving Time transitions. When the clock goes back there is an entire hour of repeated local times. You won't be able to say which instant in UTC that the time corresponded to.

Edit

The minimal change I'd make to your code is:

public class Post
{
    public string Title { get; set; }
    public string Description { get; set; }

    // C#6 syntax for readonly property
    public DateTime CreationDateTime { get; } = DateTime.UtcNow;

    public int UpVoteCount { get; private set; }
    public int DownVoteCount { get; private set; }

    // C#6 expression bodied member
    public int Score => UpVoteCount - DownVoteCount;

    public void UpVote()
    {
        UpVoteCount++;
    }

    public void DownVote()
    {
        DownVoteCount++;
    }
}


C++ implementation of quicksort with iterators (unstable sorting)

Two problems with the code that I see immediately:

if (std::distance(begin, end) <= 2) is wrong since it leaves an array like {2,1} untouched. This means that the code can screw up every time it recurses to an array of size 2.
Iter partition(Iter begin, Iter end, const T& pivot): Passing pivot as const T& is a bad idea. When passed as const reference, when you perform the iter_swap, the value pointed to by begin changes and so does pivot. Hence running your code gives me a segfault but changing const T& to T takes care of the segfault.

Even if these are fixed, there is something more subtle. Suppose you try to sort an already sorted array like {1,1,1}. Partitioning this will return mid = begin. So unless you make an explicit check for a sorted array you will recurse infinitely on qsort(mid,end).


Validate destinations of a piece in a board game

Yes, you can simplify the implementation of your algorithm by introducing the notion of direction, like you find in mathematics…

In Djanbi game, a token can move in 8 directions. You can define a vector d(d_x, d_y) which defines this notion of direction:

North: d = (0, 1),
East: d = (1, 0),
South: d = (0, -1),
West: d = (-1, 0),
North-East: d = (1, 1),
South-East: d = (1, -1),
North-West: d = (-1, 1),
South-West: d = (-1, -1).

First you can define the Point tuple to simplify coding:

import collections

Point = collections.namedtuple('Point', 'x y')

Then, you can use this named tuple to construct all possible directions:

import itertools

directions = [
    Point(*coord) for coord in itertools.product([-1, 0, 1], [-1, 0, 1])
]
directions.remove(Point(0, 0))

You get:

[Point(x=-1, y=-1), Point(x=-1, y=0), Point(x=-1, y=1), Point(x=0, y=-1), Point(x=0, y=1), Point(x=1, y=-1), Point(x=1, y=0), Point(x=1, y=1)]

For each direction, you can search for the possible moves. But before you need to calculate the next position of a token in a given direction. You can use a simple generator for that:

def next_pos(p, d):
    p0 = p
    while 0 <= p.x < 9 and 0 <= p.y < 9:
        if p != p0:
            yield Point(p.x, p.y)
        p = Point(p.x + d.x, p.y + d.y)

Then you can loop as follow:

# coordinates of the position of the chip
chip = Point(2, 4)

for direction in directions:
    print('In the direction: {0}'.format(direction))
    for pos in next_pos(chip, direction):
        ...

Here, pos is a Point instance that you can use to check if a position is valid…