Implementing your own smart pointer is very hard please don't try.

If it is just to try and learn then fine you may learn something but after practicing go back to one that has been tested and is know to work.

20 seconds into looking Bug 1:

int main()
{
    auto_<int>   x;
    auto_<int>   y(x);
    auto_<int>   z(x);
}

Problem caused by this line:

auto_(const auto_<T> &o)
   : pValue(o.pValue)
   , pPrev(&o)
   , pNext(NULL)
{
    o.pNext = this;   // Here you are overwriting x.pNext when building z
}                     // It may or may not cause a bug but it was definitely
                      // not what you intended to do.

You now have

pNext List
[X] -> [Z] -> |    Y/Z point at nothing
       [Y] -> |    X   points at Z

pPrev List
[Y] -> [X] -> |    Y/Z point at X
[Z] ----^          X   points at nothing.

                   One assumes you are trying to create a circular list!

Don't use hungarian notation

pValue

Do you really want to bind your object to always using pointers?
Just use logical names for the members try not to encode type information into the name of the member it already has that information in its type.

Style Tip

Don;t do this:

    const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;

It really hard to read. You are doing complex enough stuff try and make it easy to read

    auto_<T> const* const pPrev = this->pPrev
    auto_<T> const* const pNext = this->pNext;

Don't do pointless work

    this->pPrev = this->pNext = NULL;
    this->pValue = NULL;

This does nothing. This object is going to be destroyed. Therefore these variables do not exist after the destructor exists. So little point in playing with their values just before destruction.

Don't manually call the destructor

        this->~auto_();

Nobody expects people to do this. Its just confusing. Move the code in the destructor into another method and call that.

Broken link

If sombody inserts a NULL pointer into your smart pointer you are asking for trouble when they de-reference it.

auto_<int>  x(NULL); // valid constructor

This is going to blow up

operator   T&() /*also const version*/ { return  *this->pValue; }

You either need to check the ptr on construction (to make sure it is never NULL) or if you allow NULL pointers then you need to check when the object is used.

Specialization

To avoid repeating yourself allow your code to be specialized by a second template parameter that understands how to reclaim the resources of different types. The default version just calls delete but this allows you to use specialize it for handles etc.

Circular lists are easier with no NULL pointers.

template<typename T>
struct Deleter
{
    void operator()(T* ptr) const { delete ptr;}
};

template<typename T, typename D = Deleter<T> >
class my_auto
{
    T *value;
    mutable const my_auto<T>* prev;
    mutable const my_auto<T>* next;

    public:
    // set up the chain to be circular pointing at just itself.
    // This way next/prev will never be NULL and we don't need to test
    my_auto()           : value(new T()),  prev(this), next(this) { }
    my_auto(T *value)   : value(value),    prev(this), next(this) { if (value == 0) throw int(1);}
    my_auto(const T &v) : value(new T(v)), prev(this), next(this) { }

    // insertInto() will do that appropriate set up.
    // We are currently not in a chain and have no value to release.
    my_auto(const my_auto<T> &o)
    {
        insertInto(o);
    }

    my_auto<T>& operator=(const my_auto<T>& other)
    {
        // Check for assignment to self
        if (this != &other)
        {
            testAndDestroy();
            removeFromChain();
            insertInto(other);
        }
        return *this;
    }

    ~my_auto()
    {
        testAndDestroy();
        removeFromChain();
    }

    private:
        // If next == this then this is the only node in the chain
        // So we destroy the data portion.
        void testAndDestroy()
        {
            if (next == this)
            {
                D     deleter;
                deleter(value);
            }
        }
        // Unlink this node from the chain.
        // If we are the only link in the chain it still works
        // we just remain linked to ourselves.
        void removeFromChain()
        {
            // Remove this node from the chain
            prev->next  = next;
            next->prev  = prev;
        }
        // Insert into another chain.
        // Assumes that we are not part of another chain
        // and that our data has already been released as required.
        void insertInto(const my_auto<T>& other)
        {
            value           = other.value;

            next            = other.next;
            other.next.prev = this;

            prev            = other;
            other.next      = this;
        }
};

If you want to use a non circular list (then you need to fix the constructor)

auto_(const auto_<T> &o)
    : pValue(o.pValue)
    , pPrev(&o)
    , pNext(o.pNext)                      // Fix this line
{
    if (o.pNext) { o.pNext.prev = this;}  // Add this line
    o.pNext = this;
}
// Your code assumes the node is always added to the end of the list
// You can not guarantee this. So you need to take account of being
// inserted into the middle.


Chan sounds like the abbreviated name for Channel and apparently it's a channel. So I'd use Channel or maybe even GoChannel.
The most commonly used naming convention I have seen for private members is to prefix them with an underscore. This way you can see at the first glance whether it's a local variable or a class member. This also means you can get rid of this. most of the time.
I really prefer to spell out the access modifier even if private is default but YMMV.
Method names should describe actions or operations (because they operate on data and sometimes modify the state of the object). To and From are not actions or operations. That being said: The channel seems to have fixed size queue semantics (FIFO) so I'd consider calling the operations Enqueue and Dequeue which would make it immediately clear how the data is being processed. (The semantic of the underlying data structure should not be exposed. Don't know what I was thinking there.) Rather use the Send and Receive semantics from the go definition.
Given the previous point it could be useful to have a Peek method to check what will come next.
_head and _tail are longs and access is not guaranteed to be atomic so you should use Interlocked.Read to obtain them.
Also the implementation is actually broken. Assume two threads A and B, A calls Send() and B calls Receive(), first execution _head == _tail == -1:

A: execute Interlocked.Increment(_tail) (_tail is now 0)
B: _tail - _head > 0 is true (0 - -1 == 1), leaves spinlock
B: execute Interlocked.Increment(_head) (_head is now 0)
B: read _buffer[_head]
A: write _buffer[_tail]
B has read from buffer before element was written.
This problem can be easily reproduced with this test case (almost every iteration results in dupes):

[TestCase]
public void TestSPSC()
{
    int numItems = 10000;
    int numIterations = 100;

    for (int i = 0; i < numIterations; ++i)
    {
        var channel = new Channel<int>(100);
        var writer = Task.Factory.StartNew(() => { foreach (var num in Enumerable.Range(1, numItems)) { channel.Send(num); } channel.Close(); });
        var reader = Task.Factory.StartNew<List<int>>(() => {
            var numbers = new List<int>(numItems);
            for (int idx = 1; idx <= numItems; ++idx)
            {
                int num;
                var res = channel.Receive(out num);
                numbers.Add(num);
            }
            return numbers.OrderBy(x => x).ToList();
        });
        Task.WaitAll(writer, reader);
        var dupes = reader.Result.GroupBy(x => x).Where(g => g.Count() > 1).ToList();
        if (dupes.Count > 0)
        {
            Console.WriteLine("{0}: {1} DUPES!", i, dupes.Count);
        }
    }
}

I changed the implementation to use .NET's BlockingCollection<T> wrapped around a ConcurrentQueue<T>:

public class Channel<T>
{
    private BlockingCollection<T> _buffer;

    public Channel() : this(1) { }
    public Channel(int size)
    {
        _buffer = new BlockingCollection<T>(new ConcurrentQueue<T>(), size);
    }

    public bool Send(T t)
    {
        try
        {
            _buffer.Add(t);
        }
        catch (InvalidOperationException)
        {
            // will be thrown when the collection gets closed
            return false;
        }
        return true;
    }

    public bool Receive(out T val)
    {
        try
        {
            val = _buffer.Take();
        }
        catch (InvalidOperationException)
        {
            // will be thrown when the collection is empty and got closed
            val = default(T);
            return false;
        }
        return true;
    }

    public void Close()
    {
        _buffer.CompleteAdding();
    }

    public IEnumerable<T> Range()
    {
        T val;
        while (Receive(out val))
        {
            yield return val;
        }
    }
}

The code is much easier to read and has probably less bugs than your self implemented one. It's also fast. I can pump 10,000,000 items (I tested with int) through a channel (buffer size 100) with single producer single consumer in 5sec. That's 0.5ns per item.

    [TestCase]
    public void TestSPSC_Performance()
    {
        int numItems = 10000000;
        int numIterations = 10;

        var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < numIterations; ++i)
        {
            var channel = new Channel<int>(100);
            var writer = Task.Factory.StartNew(() => { foreach (var num in Enumerable.Range(1, numItems)) { channel.Send(num); } channel.Close(); });
            var reader = Task.Factory.StartNew<List<int>>(() => { var res = new List<int>(numItems); foreach (var num in channel.Range()) { res.Add(num); } return res; });
            Task.WaitAll(writer, reader);
        }
        stopWatch.Stop();

        var elapsedMs = stopWatch.Elapsed.TotalMilliseconds;
        Console.WriteLine("SPSC N = {0}: {1:.00}ms/iteration, {2:.00}ns/item (tx+rx)", numItems,  elapsedMs / numIterations, elapsedMs * 1000.0 / numItems / numIterations);
    }


Bounded spigot algorithms for e and pi in Python

About the first function. If you are so inclined, apply these ideas to the second one too.
Generally I'd love to see more descriptive variable names, comments, a docstring.
I tried to stick to your algorithm/implementation as much as possible, i.e. I'm just playing the role of a linter here.
That being said.
Why
while True:
  ....
  if len(estr) > n:
     break

instead of
while len(estr) <= n:
  ....

?
Why
        asum = carover + y
        remainders.insert(0, asum % x)
        tsum.insert(0, asum)
        multq = asum // x
        carover = multq

instead of
        asum = carover + y
        tsum.insert(0, asum)
        divx, modx = divmod(asum, x)
        remainders.insert(0, modx)
        carover = divx

?
Why not move
    (carover, asum) = (0, 0)
    (remainders, tsum) = ([], [])

to the start of the loop, so that you can remove these from before the loop.
Why not write e.g.
carover, asum = 0, 0

instead, and lose the parens?
Why build an inner list in
x10 = [prec * x for x in list(reversed(remainders))]

instead of just using the iterator
x10 = [prec * x for x in reversed(remainders)]

?
Why cast to int after integer division? You shouldn't need the int in the following:
int(tsum[0] // 2)

Why reverse b, remainders? Why not construct them so that they are "reversed" by default:
b = list(range(n, 1, -1))

remainders.append(asum % x)

To maintain symmetry, let us do the same to tsum:
estr += str(tsum[-1] // 2)

tsum.append(asum)

Why do we need multq = 0? Why do we need multq at all?
You don't use tsum, only its first value. I don't think there's a need to build b either.
OK, so far we have something like the following:
def espig(n):
    estr = '2.'
    prec = 10 ** n
    ys = [1 for _ in range(2, n + 1)]

    while len(estr) <= n:
        carover, asum, remainders = 0, 0, []

        for x, y in zip(range(n, 1, -1), ys):
            asum = carover + prec * y
            carover, remainder = divmod(asum, x)
            remainders.append(remainder)

        ys = remainders
        estr += str(asum // 2)

    return estr


I don't think that makes it easier (or cleaner)
You are injecting pointers (which begs to ask ownership)
You should be preferring encapsulation over inheritance.

If I was doing it normally:

class component
{
    Scene&   scene;
    Entity&  entity;
    Foo&     foo;
    public:
    component(Scene& s, Entity& e, Foo& f)
        : scene(s)
        , entity(e)
        , foo(f)
    {}
    virtual ~component(){};

    void method()
    {
        scene->method();
        foo->method();
    }
};

int main()
{
    scene s;
    entity e;
    foo f;
    component c(s, e, f});

    c.method();
}

This seems much cleaner than your method (where you introduce another level of inheritance).


I think this will work you have to use an inline select statement to get the running total, essentially this is what SUM() OVER function does in 2012+ except the engine was designed to handle the function faster.

WITH C AS (
    SELECT EmployeeID
            ,PlanCode
            ,IssCost
            ,(SELECT SUM(IssCost) FROM Payroll as b WHERE a.EmployeeID = b.EmployeeID AND a.PlanCode >= b.plancode) as YTD
    FROM Payroll as a
)
SELECT  EmployeeID
    ,PlanCode
    ,IssCost
    ,YTD
    ,(YTD - 400 + abs(IssCost - 400))/2 AS OutOfPocket
FROM C
ORDER BY EmployeeID, PlanCode


Find and replace consecutive string values in a list

Don't mutate input and return.

If I need to pass columns unedited to two different functions, than your function will seem like it's not mutating columns and I wouldn't have to perform a copy of the data. But this isn't the case.
You may want to potentially error if there are no values before the first "Unnamed" value.
You may want to make pattern an argument, to allow reusability of the function. And instead use change it to a callback to allow even more reusability.

Overall your function's pretty good. I don't think it can be made much shorter.

def value_or_previous(iterator, undefined, default=None):
    prev_item = default
    for item in iterator:
        if not undefined(item):
            prev_item = item
        yield prev_item

def rename_unnamed(columns):
    return list(value_or_previous(columns, re.compile(r'^Unnamed:\s\d+$').match))


A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

Proper constraints

Is it a good idea to set the type constraint like std::enable_if_t<std::is_arithmetic<T>::value, int> = 0, std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>?

It is not a good idea to constrain the value type to the arithmetic ones. It will only match primitive integer and floating point types. There are many more types that you can sum together, either ones from the STL (like std::complex) or custom types.
Also, the constraint on the overload that sums over containers is incorrect. You only restrict it to classes that have a value_type, but that doesn't necessarily mean it is a container. Again, std::complex is an example of a class that has a value_type but isn't a container. Instead, you want to restrict it to something that has the properties of a container that you are actually using: that it has a begin() and end() for example. See this question for some ideas of how to check for a container type.
Return type
If you pass a container to Sum(), the result is always long double. But what if I want to sum integers, or std::complex numbers, or something completely different like std::strings? You want the return type to match the value_type of the inner-most container. Have a look at how std::accumulate() handles this.
Summing non-container types
Normally I'm all for handling corner cases properly, and the case of summing over something that has zero nested containers, but just a single value, can be considered such a corner case. But in this case, I think it will most likely be a programming error if you tried to sum a single value. So consider whether it makes sense to have an overload that handles the sum of a single value.
Redundant calls to std::to_string()
Not related to Sum(), but in your example you are converting the results to a string with std::to_string(), but the immediately writing it to std::cout. This is unnecessary, std::cout already knows how to format a long double.


Palindromes that are sum of consecutive squares

The key problem with the performance of your code is get_quadratic_sums. This returns all sums of consecutive squares each of which is individually below the limit. But the vast majority of this work is wasted, because we are only interested in in sums of consecutive squares where the sum is below the limit.

So a very simple change to your code massively improves its performance. Where the code iterates over sums of squares:

for partial in partial_sums[0:i-1]:
    val = partial_sums[i] - partial
    dic[val] = 1

Iterate in reverse order (so that val is increasing) and stop when val is too large:

for partial in partial_sums[i-2::-1]:
    val = partial_sums[i] - partial
    if val >= limit:
        break
    dic[val] = 1

Now it runs in less than a second on my laptop:

>>> timeit(lambda:palindromic_square_summable(10**8), number=1)
0.7864874959923327

But we can do even better than that. Slicing a list in Python makes a copy of the sliced part of list. We can avoid the copy by iterating over the indices instead:

for j in xrange(i-2, -1, -1):
    val = partial_sums[i] - partial_sums[j]
    if val >= limit:
        break
    dic[val] = 1

Now it runs in less than half a second:

>>> timeit(lambda:palindromic_square_summable(10**8), number=1)
0.40678663086146116

A few more improvements:

int rounds towards zero, so you can write int(limit ** .5) instead of int(floor(limit ** .5)).
Since there have to be at least two squares in the sum, we only need to check up to int((limit / 2) ** .5).
get_quadratic_sums returns a dictionary whose keys are sums and whose values are always 1. But the values are never used, so it would make more sense to use Python's built-in sets:

def get_quadratic_sums(limit):
    """Return set of sums below limit of two or more consecutive squares."""
    max_square = int((limit / 2) ** .5) + 1
    partial_sums = [0] * max_square
    sums = set()
    _add = sums.add
    total = 0
    for i in xrange(1, max_square):
        total += i * i
        partial_sums[i] = total
        for j in xrange(i - 2, -1, -1):
            val = total - partial_sums[j]
            if val >= limit:
                break
            _add(val)
    return sums

Note the use of the local variable _add to remember the sums.add method: this avoids looking it up again on each loop iteration.
Similarly, all_palindromes can be changed to return a set instead of a dictionary:

def all_palindromes(limit):
    """Return set of palindromes below limit."""
    palindromes = set()
    _add = palindromes.add
    for p in get_palindrome():
        if p >= limit:
            break
        _add(p)
    return palindromes

Now that both of these functions return sets, you can just take their intersection, like this:

def palindromic_square_summable(limit=10**8):
    """Return the sum of palindromes below limit that are sums of two or
    more consecutive positive integers.

    """
    return sum(get_quadratic_sums(limit) & all_palindromes(limit))

This is even faster:

>>> timeit(palindromic_square_summable, number=1)
0.29244883195497096


Understand the dependency levels of makefiles

I have not divided up the header files into their .h and .c files because they are very small header files.

I would advice against this. Dividing into header and source files is just something you do. If something deserves an own source file, it also deserves an own header file. If nothing else, future readers of your code will expect .h files to only contain declarations. If you really don't want to split them up, then include the .c files instead. That's not good, but at least you're not hiding what you're doing.

Also, I don't really see the need to manually write dependencies. If your project is big, look into CMake or something. If it is small, use a generic Makefile. Here is a small example that basically contains everything you'll ever need before it's time to move on to CMake:

# Configuration

EXE = play
CFLAGS = -g -Wall -Wextra -std=c11
LDLIBS = -lm
LDFLAGS =

# Don't touch anything below

# Every .c is a source file (dough)
SRC = $(wildcard *.c)
# Every source file should be compiled to an object file
OBJ = $(SRC:.c=.o)
# Every object file should have a dependency file
DEP = $(OBJ:.o=.d)

# Link the exe from the object files
$(EXE): $(OBJ)
    $(CC) $(LDFLAGS) $^ -o $@ $(LDLIBS)

# Generate dependencies for the object files
%.o: %.c
    $(CC) -MMD -MP -c $< -o $@

# https://stackoverflow.com/q/2145590/6699433
.PHONY: clean

clean:
    $(RM) $(OBJ) $(DEP) $(EXE) *~

# Include the generated dependencies
-include $(DEP)

Note that you don't need to pass $(CFLAGS) to the CC commands. It's done automatically.

I used the above Makefile on this:

$ cat *.c *.h
/* bar.c */

#include "bar.h"
#include <math.h>

int bar(int a, int b) { return a*pow(b,3); }
/* foo.c */

#include "foo.h"
#include "bar.h"

int foo(int a, int b) { return a+bar(a,b); }
/* main.c */

#include "foo.h"

int main() { foo(1,2); }
/* bar.h */

#ifndef __BAR_H__
#define __BAR_H__

int bar(int a, int b);

#endif
/* foo.h */

#ifndef __FOO_H__
#define __FOO_H__

int foo(int, int);

#endif

I sacrificed a bit of readability to keep number of lines down. After running make I have a couple of .d files.

$ cat *.d
bar.o: bar.c bar.h

bar.h:
foo.o: foo.c foo.h bar.h

foo.h:

bar.h:
main.o: main.c foo.h

foo.h:


Nearest Neighbor Algorithm (general nearest, forward-nearest, or backward-nearest)

code

Some of your program is copy-n-pasted code; there is an opportunity to refactor.

Your docstring offers little guidance on valid direction values. Consider using enum.Enum. If None becomes 0, then 1 and -1 could represent the directions, with delta multiplied by the sign, killing two cases with one stone.

The identifier res for result is pretty OK, but consider using an abbreviation like idx for index, clarifying that it is not the "value" that the docstring said would be computed. Better yet, turn it into a function that is documented to return an index, and push the print statements into a calling function.

crd = 'forward'

I'm willing to believe that "d" denotes "direction", but the "cr" part of that identifier is obscure.

algorithm

  if there are better approaches (in terms of speed) to achieve the same output

Your main function suggests that you will repeatedly interrogate a large (70k) sample with diverse search values. In which case your data structure is not well suited to your task.

You are forcing pandas to read all N values on each query. Don't do that.

Build a two-column copy of the input that stores (index, value). Sort it by value. So far the cost is N log N.

Now for each query, binary search for search_value to land on result_index, at cost of log N. The desired answer is at result_index, or the entry before it, or the entry after it. Then use the stored index to report the corresponding index in the original input data.


So I would recommend to not extend the CSV parser from the Database class.
Instead The CSV parser should get the Database per dependency injection through
the constructor. Also I would not recommend to access gobal vars like $_SERVER
in a class. Here an example how you could do that:

class CSVParser
{
    protected $file;
    protected $database;

    public function __construct($file, Database $db)
    {
        $this->file = $file;
        $this->db = $db;
    }

    public function saveCSVtoDB()
    {
        // @TODO import CSV to DB
    }
}

And you could use the class with:

$file = isset($_SERVER["argv"][1]) ? $_SERVER["argv"][1] : "stock.csv";

$parser = new CSVParser($file, Database::getInstance());
$parser->saveCSVtoDB();


What is the security issue in this code?

Off the top of my head:

Those parameters don't seem to be escaped before being stitched into a query (opening up SQL injection attacks)
The database seems to be keeping passwords in plaintext rather than as salted hashes (which is an especially bad combo with the previous point)

You'd really want to

escape the username and password before dropping them into a SELECT statement
keep the password stored as a hashed value at minimum (you'd then want to verify the users' input by hashing the password you get from them and comparing that to what you have stored). Ideally, you'd salt them too.

It wouldn't hurt to accept the login info as a POST parameter either (just to reduce the number of logs username/password combos would end up in).


Optimization of Javascript Function swapping out images for gifs

I think you could reduce a loot your code and do it in a way that it is more clear and effective.

First of all this part you could just remove without concerns:

$(document).ready(function () {
    onHover();
    offHover();
    onHover1();
    offHover1();
    onHover2();
    offHover2();
    onHover3();
    offHover3();
});

The reason, is because those functions are intended to be called on events triggering. This is the logic reason.
The functional reason, is that at the end you have the same situation of the beginning.

If your intention was to provide some sort of effect here, it is better to have a dedicated function to this. First of all because those kind of effects could change in time for different reasons than the event handlers.
Second reason is because the meaning is much evident.

I thin you could put all the url in your HTML using the data attribute:

<figure>
 <img src="#" alt="" class="img-ford"
   data-out="/tasha/style/images/gifs/giphy.gif"
   data-out="/tasha/style/images/stills/FORD-SUPER-BOWL.jpg"/>
</figure>

You can avoid to place the event handlers directly in HTML code, this could be done in the $(document).ready() section on startup.

Now you can have a function to initialize your images:

function initImages() {
    $('img').each(function(img) {
        $(img).prop('src', $(img).data('out'));
     });
}

Maybe you have to take care of the selector to get only and all the images you want to operate on.

Than start the initialization:

$(function() {
     initImages();
     $('img').on('mouseover', imageMouseOver);
     $('img').on('mouseout', imageMouseOut);
 });

This is the short version of $(document).ready() in jQuery.

Then your functions:

function imageMouseOver(event) {
    $(this).prop('src', $(this).data('over'));
}

And the same for out:

function imageMouseOut(event) {
    $(this).prop('src', $(this).data('out'));
}

Of course you can reduce more with a sort of toggle function, but have used 2 just for sake of clarity.


Project Euler - Problem 1 Multiples of 3 and 5 (Java)

You used the inclusion-exclusion principle here…

sumOfMultiples(3,limit) + sumOfMultiples(5,limit) - sumOfMultiples(15,limit);

… which is good.  The name of the function sumOfMultiples(…) is pretty clear.  (The only uncertainty is whether it includes or excludes the upper bound.  JavaDoc would help in that regard.)

There is a way to compute sumOfMultiples() in constant time.  Since

$$ 1 + 2 + 3 + \ldots + n = \frac{n(n+1)}{2}$$

you can derive a formula for

$$ k + 2k + 3k + \ldots + nk = k \frac{n(n+1)}{2} $$


Your code does not handle negative numbers.  As it is, it will print nothing.  The code should be changed to either handle the negatives properly, or take number as an unsigned where it is not an issue.

Your use of base as the length of the array to store the converted number in is incorrect.  A 32-bit integer will potentially need 32 characters to display the entire number, assuming no zero byte terminator (see below).  buffer should be declared as a fixed size, large enough to hold the longest possible string.  You could then eliminate the i < base check from your while loop.

The initial check of if (!number) can be eliminated by changing your while loop into a do/while look.

If you're looking for brevity in code lines, the body of the loop can be reduced to two statements, although it is more readable with three or four.

The assignment of a 0 byte to the end of buffer is unnecessary in this context since you never pass buffer to a function that requires it.


I would strongly consider adding a Comparable abstract class with two implementations (one containing a MyClass1, and the other a MyClass2). At that point you can use all the normal collection framework methods to process this. Alternatively you could transform both sets into something like HashMap<String,HashMap<String,List<MyClassX>>>, then just lookup by the name and id.

Additionally, if the lists are sorted, we could do this much more efficiently, by getting two iterators, then simply getting the next element of the one that is behind at each stage.


Extracting filenames from a URL by splitting a string

Abstract the implementation into a function. This makes it easy to catch mistakes if you want to use this capability in more than one location. GetUpperBoundElemenentFromDelimitedString takes the required arguments you give it and returns the UBound result. The name may be cumbersome but typing getup and then pressing Ctrl+J will 'List Properties/Methods', the same going to Edit and choosing that option.

Public Function GetUpperBoundElemenentFromDelimitedString(ByVal inputValue As String, ByVal delimiter As String, Optional ByVal compare As VbCompareMethod = VbCompareMethod.vbTextCompare) As String
    Dim temp As Variant
    temp = Split(inputValue, delimiter, compare:=compare)
    GetUpperBoundElemenentFromDelimitedString = temp(UBound(temp))
End Function

Now when you are using it the descriptive name lets you immediately know what's happening.

Public Sub Foo()
    Dim bar As String
    bar = "This,is,going,to,return,an,element,at,a,specific,position."
    Debug.Print GetUpperBoundElemenentFromDelimitedString(bar, ",")
End Sub

The same could be done for a specific position

Public Function GetArrayElemenentFromDelimitedString(ByVal inputValue As String, ByVal delimiter As String, ByVal zeroBasedPosition As Long, Optional ByVal compare As VbCompareMethod = VbCompareMethod.vbTextCompare) As String
    GetArrayElemenentFromDelimitedString = Split(inputValue, delimiter, compare:=compare)(zeroBasedPosition)
End Function


Just a couple things:

sieve_list = list(range(end+1))

You don't actually need your list to be [0, 1, 2, ... ]. You just need an indicator of whether or not it's true or false. So it's simpler just to start with:

sieve_list = [True] * (end + 1)

That'll likely perform better as well.

When you're iterating over multiples of primes, you're using:

range(each_number*2, end+1, each_number)

But we can do better than each_number*2, we can start at each_number*each_number. Every multiple of that prime between it and its square will already have been marked composite (because it will have a factor smaller than each_number). That'll save a steadily larger increment of time each iteration.

As an optimization, we know up front that 2 and 3 are primes. So we can start our iteration at 5 and ensure that we only consider each_number to not be multiples of 2 or 3. That is, alternate incrementing by 4 and 2. We can write this function:

def candidate_range(n):
    cur = 5
    incr = 2
    while cur < n+1:
        yield cur
        cur += incr
        incr ^= 6 # or incr = 6-incr, or however

Full solution:

def sieve(end):
    prime_list = [2, 3]
    sieve_list = [True] * (end+1)
    for each_number in candidate_range(end):
        if sieve_list[each_number]:
            prime_list.append(each_number)
            for multiple in range(each_number*each_number, end+1, each_number):
                sieve_list[multiple] = False
    return prime_list

Impact of various changes with end at 1 million, run 10 times:

initial solution       6.34s
[True] * n             3.64s (!!)
Square over double     3.01s
candidate_range        2.46s

Also, I would consider every_multiple_of_the_prime as an unnecessary long variable name, but YMMV.


DO.dom: Creating large DOM structures in Javascript

A more typical approach these days, if you have to create a lot of DOM objects in javascript, is to use a templating system, such as Mustache (see also iCanHazjs), and thus translate javascript objects into HTML.
The advantages are readable javascript and optimised DOM object creation. The disadvantage of this vs. your library is that this doesn't deal with the event binding.

Your library certainly seems powerful, but I would say that this might be very hard to read if you have are creating a lot of DOM objects.
What you'd end up with is a lot of .js code that essentially replicates an HTML document fragment, but with less readability.

This is the advantage of using HTML templates; that you can read the HTML structure easily, but in the javascript code, you don't have more than a line or two of code that does the DOM element creation.  Also, templating systems generally build DOM objects in an efficient manner.

Also, I'd look into something like jQuery entwine as a possibility for easy-to-read event binding.


C# Asp.net core middleware for redirecting URLs

If you add IWebHostEnvironment as a dependency to the middleware class, you can simplify the environment check by this:
if (webHostEnvironment.IsDevelopment())
{

}


I see a number of things that may help you improve your code.

Fix your formatting

The code as posted has inconsistent indenting which makes it hard to read.  Choose a particular style and apply it consistently to make your code easier to read.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Validate the input

The code does not seem to be able to handle negative numbers as in the expression:

-3+2

If it's not intended to handle negative numbers, it would be good to let the user know.  If it is, then there's a bug that should be fixed.

Don't use std::endl if you don't really need it

The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Don't use system("PAUSE")

There are two reasons not to use system("cls") or system("PAUSE").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named PAUSE or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example:

void pause() {
    getchar();
}

General portability

This code could be made portable if you omit the Windows-only include files #include "stdafx.h".  If you must have stdafx.h, consider wrapping it so that the code is portable:

#ifdef WINDOWS
#include "stdafx.h"
#endif

Separate input, output and calculation

To the degree practical it's usually good practice to separate input, output and calculation for programs like this.  By putting them in separate functions, it isolates the particular I/O for your platform (which is likely to be unique to that platform or operating system) from the logic of the program (which does not depend on the underlying OS).  So for example, the main program might call a function to fetch and validate the input, a second function to actually perform the mathematical operations and then a third to emit the results.

Omit spurious parentheses

The argument to a case statement or return statement does not need parentheses, so instead of this:

 case('#'):

One could write this:

 case '#':

Consolidate strings

Right now, the string "Input not recognized" appears four times in the program.  I'd recommend creating a const variable instead and then using that instead of repeating the string.


Using reduce twice in a row for Run Length Encoding

Algorithm

Your algorith is quadratic for no good reason because last and length
are linear in list length.

I suggest that you add new elements to the beginning instead of the
end of the return value in compress-reduce and
nreverse
it in compress.

Style

Avoid nth 0 in favor of car.

(= (char-int last-char) (char-int curr)) is better written as (char= last-char curr).

Avoid mixing and and push: keep conditions in and and side-effects
(like push) in progn.

Repeated reduce and map

Each map
(and mapcar et al)
allocates a fresh list, so doing a repeated map can waste memory (and
garbage collection cycles), so either using
map-into
or an explicit function composition is a good idea: instead of

(mapcar #'foo (mapcar #'bar my-list))

use either

(let ((res (mapcar #'bar my-list)))
  (map-into res #'foo res))

or

(mapcar (lambda (x) (foo (bar x))) my-list)

However, no such allocation happens with reduce
so there is no reason to avoid nested reduces.

Note that the proverbial "sufficiently smart compiler" should be able to
handle these problems (but not necessarily the quadraticity above!), so
you should only worry about this if you discover it to be the
performance bottleneck.

Remember (SICP):

  ... a computer language is not just a way of getting a computer to
  perform operations, but rather ... it is a novel formal medium for
  expressing ideas about methodology


Auctioneer calling "Going once… going twice… sold!"

Definetely not. The loop is useless (and un-optimizing) here.

As far as I can see, the index i is only used to calculate some constants' values. Realise that your original loop has the same effect than dropping off the loop and the ifs clauses, and hard-code the values computed from i:

setTimeout(function(){console.log(objekt + " zum ersten")},1000);
setTimeout(function(){console.log(objekt + " zum zweiten")},2000);
setTimeout(function(){console.log(objekt + " zum dritten")},3000);
setTimeout(function(){console.log(objekt + " verkauft!")},4000);

Or, another valid alternative could be taking advantage of the resembling of the actions and generalize them by using data:

var messages=[" zum ersten", " zum zweiten", " zum dritten", " verkauft!"];

This would be more comprehensive and flexible, since it allows to add more messages without changing the logic a little.

Update

I recommend RobH's answer, which is based upon arrays, and works fine.


Node function to walk through file system and make sure it has a matching db record

./content/userstyles/' + style._id + '/style.css

This appears to be a very brittle convention. It assumes the styles live in a specific directory. Not following the convention, it might lead to more unsynced files. You need a more robust way to handle this. For instance, ID'ing the file using its path.

fs.access('./content/userstyles/' + style._id + '/style.css', function(err) {
    if (err && err.code === 'ENOENT') {
      //Can't find the style file, i need to delete it
      Style.remove({_id: style._id}, function(err, result) {

Instead of a back-to-back filesystem and DB operation, why not operate in batches. Like first get a list of files from DB. Next, check if you can access them all. Only after then do you wipe the DB with missing ones. This way, you have a much more linear set of operations instead of one step doing too many at a time.

It can even be simplified into something like similar to this pseudo-code implementation:

db.getStyles()                                      // Get all styles
  .map(path => { path, hasAccess: hasAccess(path)}) // Get access
  .filter(file => !file.hasAccess)                  // Get unaccessible
  .forEach(path => db.delete(path));                // Delete

Now if I rememer correctly, fs-plus has a method to list down all the possible paths under a given path. I think it was listTreeSync. This way, instead of having a callback run on every file and directory, you can simply analyze the array of paths returned by the function. Equates to lesser filesystem operations.

fsp.listTreeSync(dir)
   .map(path => extractId(path))
   .forEach(id=> storeOrDeleteId(id));

Also, I recommend writing it in a synchronous manner. Unless you're multiplexing other operations in the same app together with this, you'll see no benefit from writing this in an asynchronous manner if this is the only operation that runs at a given time.


Redacting everything in a string except a particular word

Manipulating Strings directly is a bad idea, especially when you are doing it repeatedly.  Java strings are immutable, so every time you do s += …, you are making a copy of the entire provisional result.  Anytime you need to do a substantial amount of editing on a string, use a StringBuilder.

To look for the next occurrence of word, use String.indexOf() or StringBuilder.indexOf().  It's a lot easier than extracting substrings and checking for equality.  When extracting the substring, your code crashes if word is longer than three characters.  Using .indexOf() is one way to eliminate that problem.

Here is an example of a more efficient solution:

public String plusOut(String str, String word) {
    StringBuilder s = new StringBuilder(str);

    // Find substrings to redact, from index i (inclusive)
    // to index j (exclusive)
    for (int i = 0; i < s.length(); i += word.length()) {
        int j = s.indexOf(word, i);
        if (j < 0) {
            // word not found; redact the rest of the string
            j = s.length();
        }

        while (i < j) {
            s.setCharAt(i++, '+');
        }
    }
    return s.toString();
}


Sorting a file with three-line blocks by the second word of the first line in each block

Usability

Hardcoded input and output filenames are not easy to use.
This script only works with one specific input file name,
and it may inadvertently overwrite a file.
It would be better to take the input file as a command line argument,
and write the output to stdout,
letting the user to redirect to any file.

Error handling

If the input file doesn't exist, the script prints a bunch of error messages:

cat: my-file.txt: No such file or directory
sort: open failed: output.txt: No such file or directory
script.sh: line 29: output.txt: No such file or directory
rm: output.txt: No such file or directory

It would be better to check first that the file exists and fail early.

Keep in mind that after an error in one of the commands,
the script continues to run and execute the rest of the commands anyway.
I've seen cases when this cause real damage,
for example with rm -fr commands that assumed to be in a different directory, which was not the case due to earlier errors.
So it's important to look out for possible errors, check the exit code of commands and halt execution early.

You could do something like this:

input=$1

if ! test -f "$input"; then
    echo fatal: input file argument missing or not a file: $input
    echo usage: $0 input
    exit 1
fi

Bash arithmetic

The -gt operator in [ ... ] is obsolete, a better way is to use the modern ((...)). Instead of:

until [ "$x" -gt "$lines" ]; do

You can write like this:

until (( x > lines )); do

Simpler quoting

You can simplify the quoting here:

    block=$(awk 'NR=="'"$x"'",NR=="'"$y"'"' "$input")

Like this:

block=$(awk "NR==$x,NR==$y" "$input")

Initializing output.txt

In the until loop, you append to output.txt.
What if the file already existed before running the script?
You will get funny results.

To make sure the file is empty, you can do this:

> output.txt

But this is still not great. A file with that name may exist, and now its content will be destroyed.

Instead of using a temporary file in the current folder,
it would be better to use one in $TMP/output.txt.
And to avoid clashing with other scripts that might do the same,
you can add the process ID to the filename, for example $TMP/output-$$.txt.
But the best solution is to use the mktemp command:

tmpfile=$(mktemp)

Deleting temporary files at the end

One problem with deleting temporary files at the end of the script like you did with rm output.txt is that you might forget to do it.
Another problem is the end of the script might not be reached,
if the command gets interrupted due to an error or signals or the user pressing Control-C.
You can protect against these by using the trap builtin:

tmpfile=$(mktemp)
trap "rm -f '$tmpfile'; exit 1" 1 2 3 15

I copied again the line creating the temporary file,
because it's best to put the trap command right after that line,
so it won't be forgotten.

The first parameter of trap is a command to run,
typically more than one commands,
and it's important that the last one is exit.
The other parameters are signals that will be trapped.
1, 2, 3, 15 are typical signals to trap, for example 2 is SIGINT,
it is sent when the user presses Control-C while the script is running.

More Bash arithmetic

Instead of this:

    x=$((x+4))
    y=$((y+4))

You can simplify to:

((x+=4))
((y+=4))

Fewer variables

y is not really necessary. Instead of incrementing it by 4 in parallel with x, you can just increment x, and use x + 2 in awk:

Fewer redirections

Instead of redirecting output in every iteration of the until loop,
you could redirect the entire loop, just once:

until (( x > lines )); do
    block=$(awk "NR==$x,NR==$x+2" "$input")
    echo $block
    ((x+=4))
done > "$tmpfile"

Fewer processes

Instead of running an awk process for every block in the file in an until loop,
you could move the same logic inside awk itself,
and achieve the same using a single process:

awk '{printf "%s ", $0} NR % 4 == 0 {print ""}' "$input" > "$tmpfile"

In the while loop too, there is some waste.
Multiple commands are on one line separated by ;,
and enclosed within (...).
It's equivalent to this:

while read i; do
    echo "$i" | awk '{ print $1 " " $2 }'
    echo "$i" | awk '{ print $3 }'
    echo "$i" | awk '{ print $4 }'
    echo
done < "$tmpfile"

Note that i is a poor name for a variable that contains a line.

But the bigger issue is that a single line with awk could replace the 4 lines of echo:

echo $line | awk '{ print $1 " " $2; print $3; print $4; print ""; }'

Even better, a single awk process could replace the entire loop:

awk '{ print $1 " " $2; print $3; print $4; print ""; }' "$tmpfile"

Putting it together

At this point, we have:

An until loop that creates $tmpfile
A sort that sorts $tmpfile
An awk command that processes $tmpfile

We can chain them all into a pipeline, and get rid of $tmpfile altogether.

With the above changes and unnecessary elements removed,
the script becomes:

#!/bin/bash

input=$1

if ! test -f "$input"; then
    echo fatal: input file argument missing or not a file: $input
    echo usage: $0 input
    exit 1
fi

awk '{printf "%s ", $0} NR % 4 == 0 {print ""}' "$input" | \
sort -k2 | \
awk '{print $1 " " $2; print $3; print $4; print ""}'


Using AJAX to secure sessions and save messages

Consider adding User Agent check

Adding a User Agent check will add another layer of security. This will slow down Session Hijacking a bit.

AJAX alone is not a security issue

AJAX is no more vulnerable then regular access when it comes to sessions.

SES_LENGHT is not defined

The constant SES_LENGHT is not defined anywhere. Is your code snippet complete?


Is there anything to improve in this MergeSort code in Java?

Generics

In Java, it is not safe to create an array of a generic type. This is what you are doing...

Comparable is really Comparable<T>, and you are creating an array of Comparable[].

Because the generic types get removed when you compile the code (see Type Erasure), there is no safe way for Java to ensure that you have the same types of data in your array.

For example, you could have specified your input as:

Integer[] data = new Integer[10];

Then, even though it is an array of Integer, the java compiler only knows it is an array of Comparable, so it can allow you to say data[0] = "broken";, but that will fail, at runtime, because you cannot put a String in to an array of Integer. because Java can only tell at runtime whether the data is valid input to a Generically typed array, it warns you whenever you use one.

This leads to ugly warnings. The right solution is to use an appropriately typed collection List<Integer> data will be type-checkable at compile time, and java can 'do things right'.

An alternate solution is to specify the full type of the Comparable as part of the method definition (a Generic Method... ):

public static <T extends Comparable<?>> void sort(T[] a){
    ....
}

... and then follow that same generic method in to your inner methods

It is complicated. There is some reference material here:

Cannot create arrays of Parameterized Types
Generic Methods

Style

You are not using white-space to help make things readable. Consider this line of code:

    int mid = lo+(hi-lo)/2;

This should be:

    int mid = lo + (hi - lo) / 2;

See the java Code-Style guidelines for this:

  All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands

Additionally, you have a number of complex 1-liners that should be split on to multiple lines:

       if(i>mid && j<=hi) {b[k]=a[j++];continue;}

That should be:

        if(i > mid && j <= hi) {
            b[k]=a[j++];
            continue;
        }

Algorithm

MidPoint

You have also copied your code from some reference texts, or otherwise done some mid-point research:

int mid = lo+(hi-lo)/2

This mechanism for getting the mid point of the array is the right pattern to use. Anyone who does it this way is either copying the code, has run in to the bug, or has been well-educated. This is a good thing, but, in case you did not know why you were doing it this way, now you know.

Bug

I believe you have a bug in the code when you have two values the same, one in each part of the merge....

... part of the reason this is hard to see is because your code is often doing more than one thing on each line:

            if(a[i].compareTo(a[j])>0) {b[k]=a[j++];continue;}
            else if(a[i].compareTo(a[j])<0) {b[k]=a[i++]; continue;}
            else {
                b[k]=a[i++];
                j++;
                continue;
            }

If I space out that code block, there are a number of things in there that are apparent:

            if(a[i].compareTo(a[j]) > 0) {
                b[k]=a[j++];
                continue;
            } else if(a[i].compareTo(a[j]) < 0) {
                b[k]=a[i++];
                continue;
            } else {
                b[k]=a[i++];
                j++;
                continue;
            }

First up, for some Comparable classes the compareTo method can be expensive. and, you will be doing it twice for many checks. You should do it once, and save away the result:

int comparison = a[i].compareTo(a[j])
if (comparison > 0) {
    ...
} else if (comparison < 0) {
    ...
} else {
    ...
}

OK, back to the bug.... in the final else block, you have:

            } else {
                b[k]=a[i++];
                j++;
                continue;
            }

This block increments both the i and the j pointers, but it only adds the i value to the merged set, which means the equal value at j is 'lost'.

There are two ways to solve this, but I prefer treating the equals values as if the one is larger than the other.... if you convert the one comparison check to be >= 0 instead of just > 0, you will successfully merge results.... then you can get rid of the whole last block entirely....

it also means you only need one compareTo check:

            if(a[i].compareTo(a[j]) >= 0) {
                b[k]=a[j++];
                continue;
            } else {
                b[k]=a[i++];
                continue;
            }

ReWrite

I am not one of those people who thinks 'continue' is a bad thing. I like it for the job it can do, but your use of the continue is excessive.... Every path through the loop is a 'continue... this is something easily solved with a little planning. Consider this rewrite:

private static void merge(Comparable[] a, Comparable[] b, int lo, int hi,
        int mid) {
    int i = lo;
    int j = mid + 1;

    for (int k = lo; k <= hi; k++) {
        if (i <= mid && j <= hi) {
            if (a[i].compareTo(a[j]) >= 0) {
                b[k] = a[j++];
            } else {
                b[k] = a[i++];
            }
        } else if (j > hi && i <= mid) {
            b[k] = a[i++];
        } else if (i > mid && j <= hi) {
            b[k] = a[j++];
        }
    }

    for (int n = lo; n <= hi; n++) {
        a[n] = b[n];
    }
}


Generic message in Elm for simple model updates

I think the general consensus is to avoid functions in Msg constructors when possible.

The one certain thing that will break is the Msg history import/export of the Elm debugger, since functions cannot be serialized.

Evan included this comment in his Sortable Tables example:

  One of the core rules of The Elm Architecture is never put functions in your Model or Msg types. It may cost a little bit of extra code to model everything as data, but the architecture and debugging benefits are worth it.

Here's some commentary by Zoul on Discourse:

  Generally speaking, in Elm you model an app with explicit state modified by a pure function based on messages with clear semantics. This makes it very easy to reason about the state changes: it’s quite obvious what state the app is in and what state transitions lead to this state.

  Once you start using functions in messages, this model gets much more powerful, but much less transparent. You lose the clear distinction between data and code – the messages no longer describe what you want done, they implement a part of it. You cannot see the behaviour just by looking at the update function anymore. And comparing or serializing the messages gets more complicated.

  In the end, it’s probably not worth it.

Besides breaking the debugger for yourself (and for others, in case you publish a package violating this principle), I don't know of any kind of language problems you may run into if you go down this path, and the above comments are the norm for this question: vague warnings about never putting functions in messages but not much specificity into the why not of the question besides the debugger issue.

But in the end, if the language designer says to never put functions in your Model or Msg types, in bold text nonetheless, I'd defer to their judgment on the matter.


In your strided filter2, x1 is (1014, 1014, 11, 11).  You are iterating over the 1st 2 dimensions in order to sum on on the last 2.  Let sum do all the work for you, res = x1.sum((2,3))

def filter2(window, x):
    range1 = x.shape[0] - window.shape[0] + 1
    range2 = x.shape[1] - window.shape[1] + 1
    x1 = as_strided(x,((x.shape[0] - 10)/1 ,(x.shape[1] - 10)/1 ,11,11), (x.strides[0]*1,x.strides[1]*1,x.strides[0],x.strides[1])) * window
    res = x1.sum((2,3))
    return res

In my tests this gives a 6x speed improvement.

With numpy iteration, especially nested ones over large dimensions like 1014 is a speed killer.  You want to vectorize this kind of thing as much as possible.

Traditionally Matlab had the same speed problems, but newer versions recognize and compile loops like yours.  That's why your numpy is so much slower.


Taking action on a webpage(select checkbox or enter textbox or select from a list)

Multiple things should be fixed:

Stylistic/Code Style issues:

consistent indentation - per PEP8, use 4 spaces
follow the variable naming guidelines (PEP8 reference) - in particular, fix the "camel case" names and add underscores between the words in your variable names in upper case
truthiness checks can be simplified, e.g. if checkboxUncheck instead of checkboxUncheck == True
do not use bare except clause - it really makes things less understandable - catch specific exception and let it fail in all other situations

Selenium specific issues:

your XPath expressions are quite fragile - you are going up and down the tree relying on the depth level and HTML markup too much. Think about using meaningful data-oriented id, class or other attributes to get to the desired elements. And, XPaths are generally less readable and more error-prompt. There are many other location techniques.
clicking elements via JavaScript might lead to problems, see if you can use regular click() method (WebDriver click() vs JavaScript click())
you may benefit from a "Page Element" page object abstraction
I think you should not actually need the "action chains" here:

actions = webdriver.ActionChains(self.driver)
actions.move_to_element(elemtwo)
elemtwo.clear()
actions.send_keys(enterValue)
actions.perform()

and can replace it with just:

elemtwo.clear()
elemtwo.send_keys(enterValue)

Code review and refactoring is a continuous process - if you would apply all the suggested fixes, I bet we'll see more things to improve.


the variable holding the DirectoryInfo object should be named using lower case.
you should always use Sytem.IO.Path.Combine() to combine a folder with a filename.
you could use DirectoryInfo.EnumerateFiles combined with the Select() and assign the returned IEnumerable to the DataSource property of the Repeater control.
you should add spacing to the property FolderPath. Instead of

public string FolderPath {get;set;}

you should use

public string FolderPath { get; set; }

Repeater1 is an ugly name which isn't decsriptive either. Change it to something more descriptive.


Generating sorted array in descending order

The easiest way to accomplish this is to call the first method that generates a sorted array and then reverse it. I believe the simplest way to reverse the array is to call Collection.reverse() while the array is still an Array List.

Instead of sorting first and then reversing later, it's better to combine those two steps:

Collections.sort(list, Collections.reverseOrder());

Sorting efficiently

As already discussed in your previous question, it would be more efficient to populate a list with random values first, and then sort it in a second step. This will actually help cleaning up your current logic, keep reading.

Single responsibility principle

The randomArrayList does 2 things now: it generates a list of random values that is sorted. You could change this to do only one thing: generate a list of random values. Let's rename it generateRandomList.

private static List<Integer> generateRandomList(final int length, final int minVal, final int maxVal) {
    List<Integer> randomList = new ArrayList<>(length);

    for (int i = 0; i < length; i++) {
        int rndNum = getRandomVal(minVal, maxVal);
        randomList.add(rndNum);
    }

    return randomList;
}

Next, generateSorted could use generateRandomList and then sort it. Likewise, generateReverseSorted could also use generateRandomList and then sort it in reverse, as I mentioned in the first point.

public static int[] generateSorted(final int length, final int minVal, final int maxVal) {
    List<Integer> list = generateRandomList(length, minVal, maxVal);
    Collections.sort(list);
    return listToArray(list);
}

public static int[] generateReverseSorted(final int length, final int minVal, final int maxVal) {
    List<Integer> list = generateRandomList(length, minVal, maxVal);
    Collections.sort(list, Collections.reverseOrder());
    return listToArray(list);
}

Is generateRandomList starting to look like a helper method? I think so.

And still sticking to the single responsibility principle, and to reduce copy-paste coding, generateSorted and generateReverseSorted should not have to worry about converting the List to array, that functionality could be extracted to its own method:

private static int[] listToArray(List<Integer> list) {
    return list.stream().mapToInt(i -> i).toArray();
}

Your other questions

  The other thing is I'm having trouble knowing how to name the array that is to be filled with random values, I can't think of a better name than data.

I renamed the randomArrayList method to generateRandomList, and it felt quite natural to rename the data variable to randomList.

  Last thing, should the variable data be in the local scope of the method or should it be a member variable of the class? I would never have more than one array I'm using at a time, for example I wouldn't have sorted and reverse sorted array I need to hold on to the values to after I use them once.

Local scope, as it is now. I'm not sure if you can gain anything at all by not recreating the ArrayList everytime. The performance difference should be negligible, and unless micro optimization is absolutely critical for your use case, you don't need to worry about it.

Suggested implementation

I'm pasting this here mainly for the unit tests. Before refactoring your methods I wrote the tests to make sure I'm not breaking anything. Having these tests in advance are a real time saver, I recommend you start using them.

class GenerateRandomIntArray {

    private static Random random = new Random();

    public static void setRandom(Random random_) {
        random = random_;
    }

    /**
     * @param length length of array to be generated
     * @param minVal minimum value (inclusive) that may be used in array
     * @param maxVal maximum value (inclusive) that may be used in array
     * @return array with random values but in sorted order
     */
    public static int[] generateSorted(final int length, final int minVal, final int maxVal) {
        List<Integer> list = generateRandomList(length, minVal, maxVal);
        Collections.sort(list);
        return listToArray(list);
    }

    public static int[] generateReverseSorted(final int length, final int minVal, final int maxVal) {
        List<Integer> list = generateRandomList(length, minVal, maxVal);
        Collections.sort(list, Collections.reverseOrder());
        return listToArray(list);
    }

    private static int[] listToArray(List<Integer> list) {
        return list.stream().mapToInt(i -> i).toArray();
    }

    /**
     * @param length length of arrayList to generate
     * @param minVal minimum value (inclusive) that can appear in list
     * @param maxVal maximum value (inclusive) that can appear in list
     * @return arrayList containing elements in sorted order
     */
    private static List<Integer> generateRandomList(final int length, final int minVal, final int maxVal) {
        List<Integer> randomList = new ArrayList<>(length);

        for (int i = 0; i < length; i++) {
            int rndNum = getRandomVal(minVal, maxVal);
            randomList.add(rndNum);
        }

        return randomList;
    }

    private static int getRandomVal(int minVal, int maxVal) {
        return minVal + random.nextInt(maxVal - minVal);
    }
}

public class GenerateRandomIntArrayTest {
    @Test
    public void testSorted() {
        GenerateRandomIntArray.setRandom(new Random(0));
        assertArrayEquals(new int[]{3, 3, 3, 4, 5, 7, 7, 8, 9, 9},
                GenerateRandomIntArray.generateSorted(10, 1, 10));
    }

    @Test
    public void testReverseSorted() {
        GenerateRandomIntArray.setRandom(new Random(0));
        assertArrayEquals(new int[]{9, 9, 8, 7, 7, 5, 4, 3, 3, 3},
                GenerateRandomIntArray.generateReverseSorted(10, 1, 10));
    }
}


I see a number of things that may help you improve your code.

Use the required #includes

The code uses ifstream which means that it should #include <fstream>.  It was not difficult to infer, but it helps reviewers if the code is complete.  In this case, the code needs the following:

#include <string>
#include <iostream>
#include <fstream>

Separate concerns

Instead of having the single routine extract field and print them, I'd recommend separating those into separate functions.  It makes the code clearer and allows flexibility if, for example, you wanted to sort the entries before printing them.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  I don't know that you've actually done that, but it seems so because the code within main omits the namespace in several places.

Fix the bug

Right now, the code reports the BSSID without the first character.  That's a bug caused because the first "-2" in the last line of GetSSIDAndBSSID should actually be -3.  Also, as pasted, your main is missing a closing }.

Be sure of your inputs

We are left to infer, from the sample and from your code, the format of the file that is to be parsed.  Perhaps you had to figure it out from samples yourself.  Either way, it's very helpful to document, as comments, just exactly what the code is expecting so that if any of those assumptions ever need to change, it will be clear what needs to be changed.  For example, it appears that there is an implicit assumption that the last ":" on the line is used to figure out the substring length that includes the two fields of interest.  However, it appears to me that the fields are of fixed width, which would make it very efficient to simply used a fixed index into the string.  Also, your code seems to assume but doesn't test that the first character on the line is "'".

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.


C program to write 5 lines to a file then print the lines except the second line

You have the right idea in write_to_file(), but print_file() is awkward.

There is no need to work a character at a time in print_file(). You can read a line at a time using fgets(buffer, sizeof(buffer), in_file).

Avoid flag variables. Here, you could use a for loop to track the line number instead.

char buffer[MAX_SIZE];
for (int i = 0; fgets(buffer, sizeof(buffer), in_file) != EOF; ++i) {
    if (i != 1) puts(buffer);
}


Having a string representing items in a cart, elaborate taxes and totals. Interview task in Python

That really depends on how the task is stated. If it's stated like your code, just in English, with four different (and possibly independent) values, then I'd say your way is actually ok. Because then if one of them changes, you only need to change the value, not rewrite logic.
But the task description says:

Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.

So it is in fact stated as two separate taxes that should be determined separately and just added. Make the code's logic reflect the real logic.
For extra clarity, use the proper names as well. For example:
def get_row_tax_percentage(product_name: str):
    basic_sales_tax = 10 if not is_exempt(product_name) else 0
    import_duty = 5 if is_imported(product_name) else 0
    return Decimal(basic_sales_tax + import_duty) / 100

Or maybe with 0 if is_exempt(product_name) else 10, I can't decide which I find clearer and/or closer to how the task says it.


Remove words from an exclude list in each row of a pandas.Series

You currently have to loop over all exclude words to check if it is equal to the current word. If your exclude was a set, you could just do if j in exclude. This change alone should speed up your code a lot (how much depends on how large your list of exclude words actually is).

In addition, you could simplify getting the exclude words:

from collections import Counter
form itertools import takewhile

THRESHOLD = 25

words = Counter(whatever_generates_your_words())
exclude = set(t[0] for t in takewhile(lambda t: t[1] <= THRESHOLD,
                                      reversed(words.most_common())))

This uses the fact that collections.Counter.most_common is sorted by frequency, so reversing it starts with the least common words. itertools.takewhile stops taking when the condition is no longer true, so you don't need to go through all words in the Counter.

For the filtering you should probably use some list comprehensions. All three of the following functions are doing the same thing:

from itertools import filterfalse

def remove_nonfrequent(note):
    sentences = []
    for sentence in note.split('. '):
        sentence_ = []
        for word in sentence:
            if word not in exclude:
                sentence_.append(word)
        if sentence:
            sentences.append(" ".join(sentence))
    return ". ".join(sentences)

def remove_nonfrequent(note):
    return ". ".join(" ".join(filterfalse(exclude.__contains__,
                              sentence.split(" ")))
                     for sentence in note.split('. '))
                     if sentence)

def remove_nonfrequent(note):
    return ". ".join(" ".join(word for word in sentence.split(" ")
                              if word not in exclude)
                     for sentence in note.split('. ') if sentence)

I personally prefer the last one, as it is the most readable one to me.

Note that Python has an official style-guide, PEP8, which recommends using 4 spaces as indentation and surrounding operators with spaces.

Since you are using this function with pandas later, a different approach might actually be faster. There is a pd.Series.replace method that can take a dictionary of replacements. You can use it like this:

from itertools import repeat

replacements = dict(zip((fr'\b{word}\b' for word in exclude), repeat("")))
df.NOTES.replace(replacements, regex=True, inplace=True)
df.NOTES.replace({r' +': ' ', r' +\.': '.'}, regex=True, inplace=True)

The first replace does all the word replacements (using \b to ensure only complete words are replaced), while the latter one fixes multiple spaces and spaces before a period.


Contrary to Julien Rousé and you, I'm rather against the "1 point of return" policy. It doesn't make it more readable. It might make it a bit easier to formally prove correctness of the code, but I have never seen someone do that outside of an academic context.

As it is now, when looking at what would happen if the json == null you'd first encounter the if(json != null) line. Then you scroll down 20 or more lines to find the end of that if block finding that there's no else block. But the method doesn't end here yet. There's another if (message != null) line where I forgot if I had encountered any initialisation in the meantime so I have to go over the entire method again to see if it is null or not ...

Compare that with a method that starts with:

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {
    if (json == null) {
        return;
    }

By writing in this "return as early as possible" style, you immediatly see that empty json objects are always valid. If at some point it's clear what the result of the method should be, then I want that to be clear explicitly at that point. I don't want to tire myself constantly looking up and down the method to see if I didn't miss anything (for example: was this message really still null when we got here?).

That's why I would prefer to structure the method like this:

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {
    if (json == null) {
        return;
    }

    if(jsonSchema == null) {
        throw new InvalidRequestException("json exist in request but there is no schema to validate it against");
    }

    try {
        JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(jsonSchema);
        ProcessingReport processingReport = jsonSchema.validate(json);

        if (!processingReport.isSuccess()) {

            StringBuilder sb = new StringBuilder();
            processingReport.forEach(jsonError -> sb.append(String.format("[%s] ", jsonError)));

            throw new InvalidRequestException(String.format("json validation failed. Errors: %s", sb.toString()));
        }

    } catch (ProcessingException e) {
        throw new InvalidRequestException(String.format("json validation threw ProcessingException. Error Message: %s", e.getMessage()));
    }
}

I'd say this is more readable and especially easier to find out what the result is of the special cases. Not that I had any trouble reading/understanding your code ofcourse. I just prefer the way that takes a little bit less effort to understand completely.


Convert Extension methods to generic methods

Have you considered using in Interface on MyObject?

public static IQueryable<T> JoinWhere(this IQueryable<T> initialObject, IQueryable<TJoinOn> joinOn, IEnumerable<string> types)
where T : IMyObject
{
    return (from myObject in initialObject
                                               //Here                      //Here
        join myObjectResourceType in joinOn on myObject.ResourceKey equals myObjectResourceType.ResourceKey
                             //Here
        where types.Contains(myObjectResourceType.ResourceType)
        select myObject);
}


Use const and let

You're using ES6, so use these features. These are better than var as they communicate their intent better and are not hoisted.

Don't mix promises and callbacks

This one I can't really understand: You use a promise in one method (generateHash) but then try to use callbacks afterwards. Promises compose much better than callbacks for a little extra overhead and are much more readable (and would also make a huge improvement to your code). If you still want to use callbacks, that's completely fine, but try to stick to one - don't mix.

I've chosen to use Promises in the code I'm giving back to you, so I've wrapped your users.list function in a Promise. If you'd prefer to use callbacks, that's perfectly fine, but you may want to use async or a similar library to prevent the hacks you made with callbacked = false etc. That sort of thing is very brittle and does not scale very well at all, and makes it hard to read.

userExists return value

This makes things stringly typed. I've left it in as I'm not sure what you would prefer to use, but may I suggest using false to indicate register was unsuccessful (but did not error), such as when the user already exists, or return a Promise.reject(error) when there is actually an error. On the note of returning false, I'm not sure why you return false when registration was a success, but I'd advise against it.

Promises chain

You can return promises from inside of a then "callback" and that value will be resolved and then passed to the next promise in the chain. This means you can simplify your generateHash method to not have so much cyclomatic complexity. This is further improved by not using callbacks.

Don't split your functions into private and public

There's no need to attach these functions to these objects, and they have no bearing on what is actually exported or imported. To simplify things, you could let generateHash be a free function and then just export an object with register in.

Use function statements where possible

Unless you transpile with Babel, using function expressions will cause those functions to lose their names. This is fine for adhoc functions like arrow functions passed to map, but for library functions it may be more helpful to have those names in a stack trace.

Note that newer engines automatically assign the binding name to the function, but that can't be relied upon.

Reviewed code

const argon2 = require('argon2')
const nano = require('nano')('http://127.0.0.1:5984')

const users = nano.db.use('users')

function generateHash(password, callback) {
  return argon2.generateSalt()
    .then((salt) => argon2.hash(password, salt))
    .then(callback)
}

// Reviewers note: this wraps users.list in a promise. You
// may want to consider using Bluebird for this instead.
function listUsers() {
  return new Promise((resolve, reject) => {
    users.list((error, body) {
      if (error) {
        return reject(error)
      }

      return resolve(body)
    }
  })
}

function insertUser(userObject) {
  return new Promise((resolve, reject) => {
    users.insert(userObject, (error) => {
      if (error) {
        return reject(error)
      }

      // Reviewers note: I am not sure why you return false on success?
      return resolve(false)
    })
  })
}

module.exports = {
  register(username, password) {
    return listUsers()
      .then(body => body.rows.some(value => value.id === username))
      .then(doesUserExist => {
        if (doesUserExist) {
          return 'userExists'
        }

        return generateHash(password)
          .then(hash => insertUser({ _id: username, hash })
      })
  }
}


Simulation of Conway's Game of Life with periodic boundary conditions

Nice implementation, few suggestions:
Naming conventions
In Java methods should be verbs and classes should be nouns.

method randomGridMaker can be renamed to makeRandomGrid (or similar)
method liveNeighborCounter can be renamed to countAliveNeighbors
method gridDrawer could be drawGrid, etc..

Java Naming Convetions
Input validation
The program needs two arguments to start, better to provide a message to the user:
if(args.length != 2) {
    System.out.println("Size and probability not provided");
    System.exit(1);
}

Encapsulation
The grid is passed around in almost every method. Would be better to have the grid as state of GameOfLife:
public class GameOfLife {

    private boolean[][] grid;
    private int n;
    private double p;

    public GameOfLife(int n, double p) {
        grid = new boolean[n][n];
        this.n=n;
        this.p=p;
    }
//...
}

This will also make GameOfLife easier to reuse.
Main loop
while (true)
    {
        StdDraw.clear();
        gridDrawer(a);
        StdDraw.show();
        StdDraw.pause(50);
        StdDraw.clear();
        b = gridUpdater(a);
        gridDrawer(b);
        StdDraw.show();
        StdDraw.pause(50);
        a = gridEqualizer(b);
    }

The method gridDrawer already knows how to use the library StdDraw, so the the methods clear and show can be moved there

There is no need of gridEqualizer if a new grid is already created in gridUpdater

The two calls to pause(50) can now become pause(100)

The result would be:
GameOfLife gol = new GameOfLife(n,p);
gol.initRandom();
while (true){
    drawGrid(gol.getGrid());
    StdDraw.pause(100);
    gol.update(); // this is gridUpdater
}

Notice that:

GameOfLife doesn't know how to draw itself, therefore is independent of the library StdDraw
Only GameOfLife can modify the grid

Performance
There are no big issues about performances, just few suggestions.
There are many operations in liveNeighborCounter:
public static int liveNeighborCounter(boolean[][] a, int i, int j)
    {
        int counter = 0;
        int n = a.length;
        if (a[(i-1)%n][(j-1)%n]) counter++;
        if (a[(i-1)%n][j%n]) counter++;
        if (a[(i-1)%n][(j+1)%n]) counter++;
        if (a[i%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][j%n]) counter++;
        if (a[(i+1)%n][(j-1)%n]) counter++;
        if (a[i%n][(j-1)%n]) counter++;
        return counter;
    }

I noticed that there is no need to use % so often, but only when the index oveflows.
It can be simplified like this:
private int countAliveNeighbors(int i, int j) {
    int counter = 0;
    for(int x=i-1 ; x<=i+1; x++) {
        for(int y=j-1; y<=j+1; y++) {
            // Skip given position
            if(x==i && y==j)
                continue;
            if(isAlive(castIndex(x),castIndex(y))) {
                counter++;
            }
        }
    }
    return counter;
}

private boolean isAlive(int i, int j) {
    return grid[i][j];
}

private int castIndex(int i) {
    if(i>=n) return 0;
    return i<0 ? n-1 : i;
}

Regarding memory, I noticed that there are some initializations that can be avoided like:
boolean[][] a = new boolean[n][n];
a = randomGridMaker(n, p);

The initialization is already done in the method randomGridMaker, so you can directly have:
boolean[][] a = randomGridMaker(n, p);

Same for other parts in the code. I will just paste here the code refactored.
Refactored code
public class GameOfLife {

    private boolean[][] grid;
    private int n;
    private double p;

    public GameOfLife(int n, double p) {
        grid = new boolean[n][n];
        this.n=n;
        this.p=p;
    }

    public void initRandom() {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (Math.random() < p)
                {
                    grid[i][j] = true;
                }
            }
        }
    }

    private boolean isAlive(int i, int j) {
        return grid[i][j];
    }

    private int castIndex(int i) {
        if(i>=n) return 0;
        return i<0 ? n-1 : i;
    }

    private int countAliveNeighbors(int i, int j) {
        int counter = 0;
        for(int x=i-1 ; x<=i+1; x++) {
            for(int y=j-1; y<=j+1; y++) {
                // Skip given position
                if(x==i && y==j)
                    continue;
                if(isAlive(castIndex(x),castIndex(y))) {
                    counter++;
                }
            }
        }
        return counter;
    }

    private boolean[][] cloneGrid(){
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = grid[i][j];
            }
        }
        return b;
    }

    public void update() {
        boolean[][] b = cloneGrid();
        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                int liveNeighbors = countAliveNeighbors(i,j);
                if(isAlive(i,j)) {
                    if (liveNeighbors == 1 || liveNeighbors > 3) {
                        b[i][j] = false;
                    }
                } else if (liveNeighbors == 3){
                    b[i][j] = true;
                }
            }
        }
        grid=b;
    }

    public boolean[][] getGrid(){
        return grid;
    }

    public static void drawGrid(boolean[][] a)
    {
        int n = a.length;
        StdDraw.clear();
        StdDraw.setXscale(0,n);
        StdDraw.setYscale(0,n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);
            }
        }
        StdDraw.show();
    }
    public static void main(String[] args)
    {
        if(args.length != 2) {
            System.out.println("Size and probability not provided");
            System.exit(1);
        }
        int n = Integer.parseInt(args[0]);
        double p = Double.parseDouble(args[1]);
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.enableDoubleBuffering();
        GameOfLife gol = new GameOfLife(n,p);
        gol.initRandom();
        while (true)
        {
            drawGrid(gol.getGrid());
            StdDraw.pause(100);
            gol.update();
        }
    }
}


Getting the index of a character within the alphabet

The alphabet would be simpler if it were written as a string, and it should be const.  I'd also name it ALPHABET to emphasize that it is constant.

Using three statements to stuff a string into an array is too cumbersome.  In my opinion, there is not much value in verifying that a non-array parameter is a string, since you'll validate each element of the array anyway.  Does it really matter that the error message is slightly different?

The validation of each array element can be rolled into the map callback.  In keeping with JavaScript's duck-typing philosophy, I would check that it has a .toLowerCase() method, rather than that it is of type string.

I find it weird that the function returns an array even if the input is a single character.  I suggest renaming the function to getIndexesInAlphabet to make it clear that it returns an array.

function getIndexesInAlphabet(chars) {
  const ALPHABET = 'abcdefghijklmnopqrstuvwxyz'.split('');

  if (!Array.isArray(chars)) {
    chars = [chars];
  }

  return chars.map(function(char, i) {
    if (!char.toLowerCase) {
      throw new Error('Element ' + i +
                      ' invalid because it is not a string.');
    }

    var ret = ALPHABET.indexOf(char.toLowerCase()) + 1;

    if (ret === 0) {
      throw new Error('Element ' + i + ' invalid because' +
                      ' not an alphabetic character.');
    }

    return ret;
  });
}

Also consider whether you really want to accept arrays at all.  Unless you plan to be able to support spreadsheet-style coordinates (e.g. AA to represent column 27), every coordinate will be a single character.  You could rationalize the interface by accepting only strings:

// Maps alphabetic characters to their 1-based index within the alphabet.
// --------------------------------------------
// @param { string } chars - String
//  consisting of a one or more alphabetic characters.
// @throws Error if the input contains a non-alphabetic character.
// --------------------------------------------
// @returns { array } with 1-based indexes. The indexes
//  of the characters within the alphabet.
//
// ------- Usage examples ----------
// getIndexesInAlphabet('i'); // Result : [9]
// getIndexesInAlphabet('aBc')[1] // 2
// getIndexesInAlphabet('aGz'); // [1, 7, 26]
function getIndexesInAlphabet(chars) {
  const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';

  return chars.split('').map(function(char, i) {
    var index = ALPHABET.indexOf(char.toLowerCase());
    if (index < 0) {
      throw new Error(char + 'is not a valid alphabetic character.');
    }
    return index + 1;
  });
}

If what is passed is not a string, it would be standard JavaScript programming practice not to bother trying to make sense of it or throwing a custom error.


N-Layer using MEF dependency injection on MVC project

Security

MEF is a lightweight framework for discovering plugins at runtime. Be wary that plugins are loaded using the same security and evidence of the container code. Anyone deploying malicious TreeOfMana*.ddl in your output folder has the same access rights to the system as your application.

var files = Directory.GetFiles(
    AppDomain.CurrentDomain.BaseDirectory, "TreeOfMana*.dll",
        SearchOption.AllDirectories)
            .Where(o => !o.Replace(AppDomain.CurrentDomain.BaseDirectory,
                 "").Contains("obj\\"));

MAF comes with built-in functionality to provide separate and limited permissions for addins. But I'm not sure whether or to which degree this framework is still supported. If you keep using MEF, make sure no malicious code could get access to the system. Some considerations:

Assembly Security
Create a dedicated Application Domain for running plugins
You could create custom authentication with DLL license keys


Prim's algorithm via Priority Queues to print the minimum spanning tree of an adjacency matrix undirected graph

I'll comment on code style, mainly.
printPrimsMST() method
It both computes the MST and prints it to System.out. This way you can't reuse it if you want to do some additional processing with its results.
So, change it to return Collection<Edge> without printing anything, and introduce a print() method that takes Collection<Edge>.
For printing, you wrote:
System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);

That's unneccessarily complex, as you defined a toString() method in the Edge class, giving exactly that format. So it's enough to use
System.out.println(edge);

Curly braces
I'd recommend to always surround blocks with curly braces (you do most of the time, but not always):
    while (visited.contains(edge.destination)) {
        if (edgeQueue.isEmpty())
            return;
        edge = edgeQueue.remove();
    }

Someone editing the code might be tempted to insert an additional instruction before returning, e.g.
    while (visited.contains(edge.destination)) {
        if (edgeQueue.isEmpty())
            doneIt = true;
            return;
        edge = edgeQueue.remove();
    }

That's a nasty trap. By indentation, it looks like a block of two statements, but it isn't (in your specific case, it's not that bad, as the compiler will flag the edge = edgeQueue.remove(); statement as unreachable, but you get the idea). So, make it a habit to always write
    while (visited.contains(edge.destination)) {
        if (edgeQueue.isEmpty()) {
            return;
        }
        edge = edgeQueue.remove();
    }

Restricting field access
class Edge implements Comparable<Edge> {
    int source;
    int destination;
    int weight;
    ...
}

The internals of a class should only be visible to the class itself. The idea of OOP is that a class defines an API visible to the outside world, and is free to decide on (and change) its inner workings. That's close to impossible if outside code directly accesses instance fields.
For that reason, make all fields private, unless you have good reason otherwise. And add only the necessary public getters and setters. And if you don't intend to change a field's value after construction of the instance, make it final as well.
You might argue that Edge is a class only meant for local use. Then make Edge a private class.
Argument checks
You are talking about undirected graphs represented as adjacency matrix. Depending on who will be calling your method, you might want to include a test whether the matrix is valid:

All rows must have the same length.
The matrix must be square.
The matrix must be symmetric.

If any of these conditions are violated, you should throw an IllegalArgumentException.


The two things I would change:

The Map you're returning should have type parameters.
The key is best to be a Character rather than a String.

Other than that, I don't see much more to it than what you've got there already.


Project Euler Problem 530: sum of sum of greatest common divisors

Special Cases and Branching

If you look at your prime checking, your code is:

if (prime(i) == true) {
    // ...
}
else if (prime(i) == false) {
    // ...
}

This ends up with you checking composite numbers for primality twice! Once in each branch! The second part could have just been else. Additionally, explicitly checking for == true is an anti-pattern. Prefer:

if (prime(i)) {
    // ...
} else {
    // ...
}

That said, why is being prime a special case? Your non-prime logic would've worked just fine on primes too! And for 1! So just drop all the branches completely and simply iterate.

Need a better algorithm

10^15 is simply too big to brute force the answer. Even dropping all the unnecessary extra work you're doing is likely insufficient. You'll have to try to come up with some optimal substructure this problem has so that you can use dynamic programming.


This version tries not to change functionality. Added two functions that reduce code duplication, both methods make use of javascript's [](square bracket) property accessor syntax which allows the functions to call different functions based on the parameter passed in.

var addListener = function(selector, method, listener) {
    var selected = visualModules.activeModuleContainer.querySelector('.js-' + selector);
    selected[method + 'EventListener']('click', listener);
    return selected;
};
var showOrHide = function (method, direction) {
    var moduleOptions = visualModules.activeModuleContainer.querySelector('.module-options');

    if (moduleOptions) {
        moduleOptions.classList[method]('module-options--active');
    }

    removeBtn = addListener('remove', method, deleteModule);

    moveUp = addListener('index-up', method, move);

    moveDown = addListener('index-down', method, move);

    if (direction) {
        moveUp.direction = 'up';
        moveDown.direction = 'down';
    }
};
var toggleModuleOptions = {
    show: function() {
        showOrHide('add', true);
    },
    hide: function() {
        showOrHide('remove', false);
    }
};

This version could change some things but very minor.  This one always sets the direction properties even on the one that wasn't being set before to avoid needing conditional logic for setting those properties. It also does not assign values to variables from outside the scope of the code shown which was only left in above in case it was necessary.

var addListener = function(selector, method, listener, direction) {
    var selected = visualModules.activeModuleContainer.querySelector('.js-' + selector);
    selected[method + 'EventListener']('click', listener);
    selected.direction = direction;
};
var showOrHide = function (method) {
    var moduleOptions = visualModules.activeModuleContainer.querySelector('.module-options');

    if (moduleOptions) {
        moduleOptions.classList[method]('module-options--active');
    }

    addListener('remove', method, deleteModule);

    addListener('index-up', method, move, 'up');

    addListener('index-down', method, move, 'down');
};
var toggleModuleOptions = {
    show: function() {
        showOrHide('add');
    },
    hide: function() {
        showOrHide('remove');
    }
};


Use braces {}! Can't say this enough. PHP has made many mistakes, but allowing this syntax is by far the worst. Adding those braces only increases file size by 2 bits! And it increases readability so much!

if ( !isset(self::$instance) ) { self::$instance = new self(); }

I'd check out the magic setter and getter methods (__set() and __get() respectively). Instead of calling a set or get method manually you just pass the variable you want. So...

$sessObj->set('var', 'value');
$sessObj->set('array', 'value', TRUE);
var_dump($sessObj->get('var'));
var_dump($sessObj->get('array'));
//compared to
$sessObj->var = 'value';
$sessObj->array[] = 'value';
var_dump($sessObj->var);
var_dump($sessObj->array);

Why are you not using $this? I mean, I don't use static methods at all really so correct me if I'm wrong, but from what I understand you can still access the internal instance by just using $this. So replace all Session::open() with $this. Even if you can't I would just dump all those static methods just for that alone. Why is everything static? If its not necessary, and I can't imagine why it would be, it shouldn't be static.

$this->set($key, $single_property);

Because my suggestions would change this code so drastically I will finish the review here. Hope this helps!


MVC
If you're trying to make a CMS, then there's a possibility that this CMS will become bigger than you first though. More pages, more modules, more code. You might want to consider doing an MVP approach to splitting code (rather than MVC).
A good reference framework for this is CodeIgniter. Presenter (CodeIgninter calls it the Controller) receives a request, then operates the data on the model (the model layer + database), then grabs a view (A template, your HTML) and renders it ("echo" the template).
SQL Injection
Then I notice this part:
$sql    = 'SELECT * FROM utilizatori ';
$sql   .= 'WHERE user = "'.self::$_user.'" AND password = "'.self::$_password.'" ';

You should read more about SQL injection. In a gist, it allows users to run arbitrary SQL, even be able to fake logins, see through existing usernames and passwords, as well as drop entire databases.
Sessions
Then there's sessions. For simple situations, that's fine. But for security, there's a lot to consider. If I can shoot malicious code through the forms, then I just might be able to fake my session. Read on this post for things to consider with sessions.
Validation
I see you use strip_tags() but it only does what it does, strip tags. It does not strip the other stuff, like backticks and quotes which can still be used to break in. A good example is the story of Little Bobby Tables. No tags, still broke through the database.
Redirect
window.location = "admin.php"

This operates on the browser. This means that index.php is actually served before redirecting, possibly rendering the page before this runs. I suggest you do a header redirect. It does not serve the page to the browser. It just tells the browser directly to load another page instead.


Converting from MySQLi to PDO account activation

The Good

You use bound parameters. You handle errors.

The Bad

You filter the email address but then pass the unfiltered value to the select and update queries. What are you trying to achieve with the check of the filtered email?

You are not checking the validity of the 'y' param (which I assume is an activation token). Isn't the point of this kind of activation to ensure that the real person at that email is doing the activation? The way you have it, an attacker could register an account using any email address. Here is how:

1) Attacker goes to your registration page and enters someone else's email address (i.e. notme@example.com)

2) Attacker crafts and visits the url: yoursite.com/activation.php?x=notme@example.com&y=12345678901234567890123456789012 (where the y value is some random string, 32 chars in length)

Attacker now has an activated account using an email they do not own, having never received the activation email.

The Ugly

Your logic and presentation are mixed together. Perhaps for this relatively simple script, it's not that big a deal. But, over time, these things have a habit of growing and getting very messy. Look into mvc.

One try catch block should be all you need.

Example Rewrite

try {
    //initialize and filter $x and $y
    if (!$x || !$y) {
        throw new Exception("$x or $y invalid");
    }

    //run select query. It's where clause should be something like:
    $where = 'email = :email AND '
           . 'confirm = :token AND '
           . 'confirmExpiration <= :expiration AND '
           . 'activated = false';
    $params = array(
        ':email' => $x,
        ':token' => $y,
        ':expiration' => date('Ymd His'),
    );

    //check results of select query
    if (/* select was not successful */) {
        throw new Exception("Invalid request. x: $x y: $y");
    }

    //Update the account so that it is now active

    //redirect to a success page
} catch (Exception $e) {
    //if production, log it and redirect to a friendly error page
    //if development, redirect to some debug page
}