Hovering over images to show another image whilst fading in & out

You need to fix your indentation.

Code inside blocks gets one more level of indentation.

Here is what your indented JavaScript would look like:

$(document).ready(function () {

    $('img').hover(
    function () {
        $(this).stop().fadeOut(function () {
            var $temp = $(this).attr('src');
            $(this).attr('src', $(this).attr('data-alt-src'));
            $(this).attr('data-alt-src', $temp);
        });

        $(this).fadeIn();
    },

    function () {
        $(this).stop().fadeOut(function () {
            var $temp = $(this).attr('data-alt-src');
            $(this).attr('data-alt-src', $(this).attr('src'));
            $(this).attr('src', $temp);
        });

        $(this).fadeIn();

    });
});

Your CSS also has poor indentation.

Here is your indented CSS:

#main-wrapper {
    width: 970px;
    margin: 0 auto;
    text-align: center;
}

img {
    width: 200px;
}

In the two functions that you are passing to $('img').hover, you are doing pretty much the same thing. I recommend creating a separate function that takes two parameters for the data to swap.

Here is what I came up with:

/*
    Sets the .stop().fadeOut of an element to swap two properties of that element
    @param(jQuery Object) elem -- the element
    @param(string) oldSrc -- one element to swap
    @param(string) newSrc -- another element to swap
*/
function fadeSwapSrc(elem, oldSrc, newSrc) {
    elem.stop().fadeOut(function() {
        var $temp = elem.attr(oldSrc);
        elem.attr('src', elem.attr(newSrc));
        elem.attr(newSrc, $temp);
    }
}

Now, your code simply becomes:

$(document).ready(function () {

    $('img').hover(
    function () {
        fadeSwapSrc('src', 'data-alt-src');
        $(this).fadeIn();
    },

    function () {
        fadeSwapSrc('data-alt-src', 'src');
        $(this).fadeIn();
    });
});


Extract unique terms from a PANDAS series

It doesn't look like you really need regular expressions.  This construct just using basic string operations is about 10x faster than the construct with the regular expressions:

present_colors = set()
for value in ex_df['colors'].values:
    for color in [x.strip() for x in value.split(';')]:
        present_colors.add(color.split('x')[-1])

And a bit faster yet, go with the same code as a generator using itertools:

import itertools as it
present_colors = set(it.chain.from_iterable(
    ([color.split('x')[-1].strip() for color in value.split(';')]
     for value in ex_df['colors'].values)))


Descriptive quantity (one, two, many) from number

You can instead use a dictionary to define your n values:

nums = {1: 'one', 2: 'two'}

Then, when you want to use this, you can use .get(). .get() has a default argument which is returned when a dict doesn't have a key you've requested; here we use 'many' to be returned.

def oneTwoMany(n):
    nums = {1: 'one', 2: 'two'}
    return nums.get(n, 'many')

If you really want to be concise you can stop defining nums:

def oneTwoMany(n):
    return {1: 'one', 2: 'two'}.get(n, 'many')

As an aside to the downvoters of the question; it may be a simple question but I don't see how it breaks any rules.

EDIT: incorporating some other answers which (quite rightly) suggest catching certain invalid inputs.

def oneTwoMany(n):
    if type(n) is not int:
        raise TypeError('Invalid input, value must be integer')
    elif n < 1:
        raise ValueError('Invalid input, value is below 1')
    else:
        return {1: 'one', 2: 'two'}.get(n, 'many')


Your function is called FlipACoin(), but you are doing more than just flipping the coin. A more appropriate name might be FlipACoinAndCountConsecutiveHeadRolls().

I would suggest keeping the function as simple as the name suggests and return a string (or boolean) from FlipACoin(), then examine the result outside the function. This will also allow you to make the counter a local variable to the run function, which will make the class smaller.


You already mentioned the duplication, so let's address that issue.

First, I'd move the assignment to a common block so it's clear that
you're toggling the visibility.

Then for toggling the CSS class I found the
toggleClass function, so maybe
go with that.

After that moving the assignment to the top, then working based on the
new state gives me this:

onNavTriggerClick: function(event) {
  this._navOpen = !this._navOpen;
  Backbone.Events.trigger(this._navOpen ? 'show:menu' : 'hide:menu');
  $(event.currentTarget).toggleClass('is-active', this._navOpen);
}

Looks a bit more concise.


Hash code collisions

There's a problem with Commit: matching hash codes do not mean that two objects are equal ('pigeonhole principle'). For example, both [1, 0] and [0, 31] have hash code 31. You can only be sure that objects are not equal when their hash codes don't match - the inverse is not true.

Also, are you sure that reusing arrays is worth the effort? If filesCount is small, then the savings are small as well, and if filesCount is large, then the likelyhood that a specific state has occurred before is probably very small.

Multiple smaller arrays

One alternative is to divide the state into multiple smaller arrays. This limits the impact of individual changes: you only need to copy a 'sub-array' (and create a new 'array-of-arrays'), instead of copying the full state. This also increases the likelyhood that a particular sub-array has occurred before, although I do not think that is something you need to be concerned about.

In Git terms, this is similar to using multiple files instead of a single large file. Committing changes to a single file only creates a new blob for the modified file and a new tree object that references the new blob (and older blobs for unmodified files).

Change-sets

Another alternative is to store a change-set for each value, using a binary search to find the value for a particular commit number. This can save a lot of space, but it'll make checkouts slower. Whether that trade-off is worth it depends on the intended use of this class.

Other notes

Instead of Clone() as int[], you can use Linq's ToArray() method.
I'd put the last 4 lines of Commit inside an else statement, to make it clearer that these are two mutually exclusive paths.
On the other hand, I would not use an else statement in Checkout - the if check is an 'early-out' guard clause, not a full-blown separate path.
In Checkout, an ArgumentOutOfRangeException might be better suited. You may also want to guard against negative values. And why not check for invalid file numbers as well?


In both versions, your policy on printing newlines is inconsistent.  With fizzBuzzBetter(), all of your cases are mutually exclusive, so they should all be System.out.println(...) calls, and there is no need to prepend "\n".

Your fizzBuzzBad() is wrong: it won't print "fizzbuzz" for multiples of 15.

Anything that can easily be parameterized ought to be.  Instead of hard-coding 20, your functions should take a max parameter that is passed from main.


Summations zu.mpfr and zstar based on a probability sample

First suggestion would be to write a function for the high precision conversion because you keep using mpfr(..., precBits = precBits) over and over:

Z <- function(x) mpfr(x, precBits = 1000000)

It won't make your code faster but it will save you a lot of typing and make it easier on the eye.

Next, if you do not know why your code is slow, you need to learn to use the profiler:

Rprof(tmp <- tempfile())
[INSERT_YOUR_CODE_HERE]
Rprof()
summaryRprof(tmp)
unlink(tmp)

It will show you that 90% of the time is spent doing the division in your prod = prod * ... line of code. So a solution would be to compute the numerator (num) and denominator (den) by iteration, then do a single division at the end:

zu.mpfr <- function(freq, u) {
  tot <- Z(0)
  n <- sum(freq)
  for (i in seq_along(freq)) {
    num <- Z(1)
    den <- Z(1)
    for (j in (0:(u-1))) {
      num <- num * Z(freq[i] - j)
      den <- den * Z(n - j)
    }
    prod <- num / den
    tot <- tot + prod
  }
  return(tot)
}

This alone makes your code three to four times faster.

Next, I would recommend looking for places where you can vectorize. I understand that your code is dealing with high precision numbers so maybe there is no other way than using for loops if only the simple operators (+, *, /) are available... However, it appears that if x is a vector of mpfr numbers, prod(x) also returns a mpfr number so I am ready to trust it is doing the right thing. If so, then you could do:

zu.mpfr <- function(freq, u) {
  tot <- Z(0)
  n <- sum(freq)
  J <- 0:(u-1)
  for (i in seq_along(freq)) {
    tot <- tot + prod(Z(freq[i] - J)) / prod(Z(n - J))
  }
  return(tot)
}

Have you noticed that we are computing the same denominator over and over? Move it outside the loop to save a little more:

zu.mpfr <- function(freq, u) {
  tot <- Z(0)
  n <- sum(freq)
  J <- 0:(u-1)
  den <- prod(Z(n - J))
  for (i in seq_along(freq)) {
    tot <- tot + prod(Z(freq[i] - J)) / den
  }
  return(tot)
}

Last, if memory size is not an issue (i.e. K remains small), you could save even more time by working with matrices. It's a bit harder to digest (including the computation of row-wise cumulative products), but it's elegant how short your code becomes (notice we don't need zu.mpfr anymore). This version is 5 to 6 times faster than your original one:

  sample <- c(rmultinom(1, n, asNumeric(p)))
  x <- Z(outer(sample, 0:(K-1), FUN = "-"))
  y <- Z(sum(sample) - 0:(K-1))
  z <- apply(x, 1, cumprod) / cumprod(y)
  zstar <- tail(rowSums(z), -1)


Fastest method of getting the bounding box containing all value ranges

This should work. It's pretty simple method. I cannot test with your sheet as mine is not nearly that large, but you can try it.

IMPORTANT NOTE: This MUST be called as a Sub if it is a function that is called from a cell then, it will not work. (because excel uses the active range to perform the start of the SpecialCells I believe).

I have tested this code with your picture of cells and it works well.

It also works with other versions of cell combinations and locations that I have tested.

The reason to use the following code is because it is simple and can save valuable programming time.  The SpecialCells Method is reliable if used correctly just like any other programming language and function. It is worth a try and also worth timing with your larger data.

In addition, the OP also uses SpecialCells in his code, just not the same way that I have.

I hope this helps.

    Option Explicit

    Sub RunIT()
        'Input range must be the first cell of where the data starts
        GetAllCells Range("A1")
    End Sub

    Public Sub GetAllCells(rngInStartingRange As Range)
        Dim strTemp As String

        strTemp = Range(rngInStartingRange, rngInStartingRange.SpecialCells(xlLastCell, xlTextValues)).Address
    End Sub


Design review
This code is symptomatic of a lot of the problems I see in concurrent code these days:

There is just too much synchronization cruft. Just take a look at showCalibration(): there are roughly 10 functional lines, and 6–8 of them are dealing with synchronization.
There is an over-reliance on fancy synchronization. Quite often I see code that uses mutexes, condition variables, futures, semaphores, and more, when literally a single atomic flag could do the same job. (Condition variables in particular seem to be all the hype these days; everybody is using them when there’s no real need.)
The entire program is designed around the synchronization, rather than around what it’s actually supposed to be doing. The actual algorithm is an afterthought. (Quite literally in this case.)

Good concurrent code doesn’t look like synchronization spaghetti, with the actual algorithm buried in a mess of locks and waits. Good concurrent code looks more or less the same as non-concurrent code. If you can’t figure out the actual algorithm being performed because it’s obscured by synchronization mess, then you are not writing good concurrent code.
Take a step back and look at what you’re actually trying to do. You have two threads, one producing values (pupil points), and one consuming them. Ignoring all synchronization (and stop tokens, etc.), your producer thread is basically just:
auto producer_thread()
{
    while (not done)
    {
        auto point = /* figure out point somehow */;

        points.push(std::move(point));
    }
}

And your consumer thread is basically just:
auto consumer_thread()
{
    while (not done)
    {
        if (auto const point = points.try_pop(); point)
        {
            // use *point somehow
        }
        else
        {
            // there are no points ready, so just give up our time (unless
            // there is some other computation we could do while waiting)
            std::this_thread::yield();
        }
    }
}

That’s it. That’s all you need.
Notice there are no visible locks, or condition variables, or any other such garbage. There is nothing in the code that isn’t clearly for the purpose of getting new points, or using them. (Well, except for that else block in the consumer thread, and that’s optional, though it makes a huge perfomance difference because your consumer loop won’t be wasting time spinning when there are no points available. And you could just do a pop() rather than try_pop(), and just block and wait for points instead.)
So is it actually possible to write the ideal code shown above, and still get highly performant and correct concurrency? Yes, yes indeed, and the key is right there in the code. Mutexes, locks, and condition variables are the wrong abstraction. What you want is a concurrent queue.
Now there is no concurrent queue in the standard library (yet! there is one proposed!), but you could write your own (bad idea), or use an existing one—there are several excellent implementations in Boost, TBB, and more.
I am going to make a very simple concurrent queue just for illustration. DO NOT DO THIS. Use a properly-written concurrent queue, do not roll your own. The one below will “work”, but it is terribly non-performant. It is just for illustration:
template <typename T, typename Allocator = std::allocator<T>>
class concurrent_queue
{
    std::deque<T, Allocator>    _data;
    std::mutex                  _mutex;

public:
    concurrent_queue() noexcept = default;
    concurrent_queue(Allocator const& a) : _data(a) {}

    auto push(T t)
    {
        auto lock = std::scoped_lock(_mutex);
        _data.push_back(std::move(t));
    }

    auto try_pop()
    {
        auto result = std::optional<T>{};

        auto lock = std::scoped_lock(_mutex);
        if (not _data.empty())
        {
            result = std::move(_data.front());
            _data.pop_front();
        }

        return result;
    }
};

And now your whole program basically just becomes this:
// define these to do what you actually want
auto CaptureFrame() -> cv::Point2d;
auto showCalibration(cv::Point2d) -> void;

auto producer_thread(std::stop_token stop_token, concurrent_queue<cv::Point2d>& points)
{
    while (not stop_token.stop_requested())
    {
        auto point = CaptureFrame();

        points.push(std::move(point));
    }
}

auto consumer_thread(std::stop_token stop_token, concurrent_queue<cv::Point2d>& points)
{
    while (not stop_token.stop_requested())
    {
        if (auto const point = points.try_pop(); point)
        {
            showCalibration(*point);
        }
        else
        {
            std::this_thread::yield();
        }
    }
}

auto main() -> int
{
    auto points = concurrent_queue<cv::Point2d>{};

    std::jthread cal_thread{consumer_thread, std::ref(points)};
    std::jthread cap_thread{producer_thread, std::ref(points)};

    // automatic clean shutdown and cleanup
}

This is just the most basic structure. Rather than getting a single point in the consumer thread, you could also try to pump the queue to get a whole bunch of points in a single go, then process them all at once. But with a really well designed concurrent queue—especially one with a non-blocking interface—there’s really no need for that.
Also, note that I’ve used C++20 jthreads and stop_tokens. If you can’t use C++20, no big deal. Just replace the stop_tokens with an atomic<bool>, and pass a reference to it in the thread constructors, then replace the jthreads with regular threads and manually set the atomic<bool> to signal shutdown, and manually join the threads:
auto producer_thread(std::atomic<bool>& done, concurrent_queue<cv::Point2d>& points)
{
    while (not done) // maybe using acquire or relaxed semantics
    {
        // ... [snip] ...
    }
}

auto consumer_thread(std::atomic<bool>& done, concurrent_queue<cv::Point2d>& points)
{
    while (not done) // maybe using acquire or relaxed semantics
    {
        // ... [snip] ...
    }
}

auto main() -> int
{
    auto points = concurrent_queue<cv::Point2d>{};

    auto done = std::atomic<bool>{false};
    std::thread cal_thread{consumer_thread, std::ref(done), std::ref(points)};
    std::thread cap_thread{producer_thread, std::ref(done), std::ref(points)};

    done = true; // maybe using release or relaxed semantics
    cal_thread.join();
    cap_thread.join();
}

Same diff, just more manual work.
HOWEVER!
Even that might be too much for this job!
The point of a concurrent queue is that one (or more than one!) thread can produce values while another (or several!) use those values… and—and this is the key point—none of those values are lost. But! If you are processing a video feed, and the camera frames are being generated at, say, 25 per second, while you can only process 10 per second… then usually it’s okay for you to just drop a few frames here or there. So you might not even need a queue at all. You might be able to get away with a single shared value. Something like this:
auto producer_thread(std::mutex& mutex, std::size_t& sequence_number, cv::Point2d& point)
{
    while (not done)
    {
        auto p = /* figure out point somehow */;

        auto lock = std::scoped_lock(mutex);
        point = std::move(p);
        ++sequence_number;
    }
}

auto consumer_thread(std::mutex& mutex, std::size_t& sequence_number, cv::Point2d const& point)
{
    auto last_sequence_number = sequence_number;

    while (not done)
    {
        auto has_point = false;
        auto p = cv::Point2d{};

        {
            auto lock = std::scoped_lock(mutex);

            // if the sequence number is unchanged, then the point data is old
            //
            // if it has changed, then there is new point data, so copy it,
            // update the sequence number, and then release the lock right
            // away
            if (sequence_number != last_sequence_number)
            {
                last_sequence_number = sequence_number;
                p = point;
                has_point = true;
            }
        }

        if (has_point)
        {
            // use p somehow
        }
        else
        {
            std::this_thread::yield();
        }
    }
}

And that’s without any kind of optimization whatsoever. If you wanted to get clever, then you might even be able to make a really compact type that encodes the point and sequence number in just, say, 8 bytes (like, 1 byte for the sequence number (0–255), 3 bytes each for the two coordinates (0–16777215 each), with a byte to spare for something else), and squeeze all that into a single 64-bit atomic value. That will be freakin’ fast, especially if you leverage C++20 atomic wait and notify:
class your_type
{
    std::fast_uint64_t _data;

public:
    constexpr your_type() noexcept = default;

    constexpr your_type(std::size_t sequence_number, cv::Point2d point)
    {
        // compact sequence number and point into _data
    }

    explicit constexpr operator cv::Point2d() const noexcept
    {
        // extract the point
    }
};

auto producer_thread(std::atomic<your_type>& data)
{
    auto sequence_number = std::size_t{};

    while (not done)
    {
        auto point = /* figure out point somehow */;

        data = your_type{sequence_number, point}; // maybe with release
        data.notify_one();
    }
}

auto consumer_thread(std::atomic<your_type>& data)
{
    auto last_data = your_type{};

    while (not done)
    {
        data.wait(last_data); // maybe with acquire

        auto const point = cv::Point2d{data};
        // use point somehow
    }
}

Note the code above doesn’t take into account how to detect that there is no more data. But that’s trivial to add: just use that last unused byte to signal “closed”.
Code review
std::vector<cv::Point2d> temp_pupil;
std::mutex mu;
std::condition_variable cond;

Global variables are bad. There’s no reason you can’t have these as local variables in main() (for example), and then pass references to them to the thread functions.
Also mu isn’t a great name for a variable… especially a global one.
In showCalibration():
for (int i = 0; i <= 9; i++)//plot 9 points sequentially

Reeeaaaallllyyy? Did you test that it plots 9 points sequentially?
Here’s what happened when I tested it:
for (int i = 0; i <= 9; i++)//plot 9 points sequentially
    std::cout << "plotting point #" << (i + 1) << " sequentially\n";

// Output:
plotting point #1 sequentially
plotting point #2 sequentially
plotting point #3 sequentially
plotting point #4 sequentially
plotting point #5 sequentially
plotting point #6 sequentially
plotting point #7 sequentially
plotting point #8 sequentially
plotting point #9 sequentially
plotting point #10 sequentially

Hm, that’s not 9 points. 10 ≠ 9.
There are two important lessons here, a small one and a big one.
The small lesson is that the standard form for a for loops is for (auto i = 0; i < N; ++i). Note the condition: it’s i < N… not i <= N.
The big lesson is that this is why the experts say not to write naked loops. Naked loops are error-prone. They’re also unclear. You have no idea what a loop is doing without reading the body of the loop (and even then it’s sometimes not clear). A MUCH better practice is to use algorithms. For example, if you wrote an rigorously tested a repeat<N>() function, you could use that, and it would be clear and safe:
template <std::size_t N, std::invocable F>
auto repeat(F&& f)
{
    for (auto i = std::size_t(0); i != N; ++i)
        f();
}

template <std::size_t N, std::invocable<std::size_t> F>
auto repeat(F&& f)
{
    for (auto i = std::size_t(0); i != N; ++i)
        f(i);
}

void showCalibration()
{
    repeat<9>([&](auto i) // self-documenting that you just want to repeat something 9 times
    {
        std::unique_lock<std::mutex> lk(mu);
        // ... and so on ...
    });
}

Now the biggest problem in showCalibration() (and in general) is that you go a little lock-crazy. You lock too often, hold the locks for too long, and reuse locks (which is generally a terrible idea, because it makes it harder to reason about when a lock is held or not).
Take a look at the first few lines of showCalibration():
std::unique_lock<std::mutex> lk(mu);
{
    temp_pupil.clear();//prepare for get new data
}
lk.unlock();

Okaaaay… but… why not this:
{
    auto lock = std::scoped_lock(mu);
    temp_pupil.clear();
}

That’s not only one line shorter, it’s also clearer about what the lock is really for, and how long it’s being held.
Now, this line is baffling, for several reasons:
cond.notify_one();//signal CaptureFrame() to capture data

The first problem is they you notify on this condition… but CaptureFrame() doesn’t actually wait on that condition.
Nor does it make any sense that it should. If CaptureFrame() is capturing frames from a camera, it doesn’t really need the consumer thread’s permission to capture the next frame. It should just capture the next frame as soon as it can; waiting on the processing of the previous frame or whatever defeats the purpose of doing this concurrently.
The other big problem with this is that you’re abusing condition variables. A condition variable should represent a single condition. But you are using cond (which is a terrible name for a condition variable, because it leads to exactly this kind of problem) for two conditions: “ready for the next frame to be captured” and “the next frame has already been captured and is ready for processing”.
If you actually wanted to wait on both those conditions, you would need two condition variables. But of course… you don’t really want to wait for permission to capture the next frame. (And you don’t even need to wait on the condition that the next frame is ready for processing, either.)
lk.lock();
{
    while (temp_pupil.empty())
    {
        cond.wait(lk);//wait CaptureFrame() to end current point
    }
    std::string cal = std::to_string(temp_pupil.size()) + "Cali" + std::to_string(i) + "\n";
    std::cout << cal;//print
}
lk.unlock();

Okay, reusing locks is bad. But the larger problem is that your function is complex enough that it needs to reuse a lock. If your function locks, unlocks, then relocks, and unlocks… that’s usually a sign that it should be two functions.
while (temp_pupil.empty())
{
    cond.wait(lk);//wait CaptureFrame() to end current point
}

Never wait on condition variables like this. Writing a loop like this is just an invitation to confusion and bugs.
Instead, do this:
cond.wait(lk, [] { return not temp_pupil.empty(); });

This is clean, self-contained, and impossible for any future maintainer to misunderstand or fuck up.
So, overall, this block of code can become:
{
    auto lock = std::unique_lock(mu);
    cond.wait(lock, [] { return not temp_pupil.empty(); });

    std::cout << temp_pupil.size() << "Cali" << i << '\n';
}

But let’s look at the big picture in this function:
void showCalibration()
{
    repeat<9>([&](auto i)
    {
        {
            auto lock = std::scoped_lock(mu);
            temp_pupil.clear();
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(100));

        {
            auto lock = std::unique_lock(mu);
            cond.wait(lock, [] { return not temp_pupil.empty(); });

            std::cout << temp_pupil.size() << "Cali" << i << '\n';
        }
    });
}

Does it really make sense for the processing thread to clear the queue, then go to sleep, then wake up and start processing data? Doesn’t it make more sense to just wake up, process the data, clear the queue when done with the data, then go back to sleep?
void showCalibration()
{
    repeat<9>([&](auto i)
    {
        auto lock = std::unique_lock(mu);
        cond.wait(lock, [] { return not temp_pupil.empty(); });

        // process the data somehow...
        std::cout << temp_pupil.size() << "Cali" << i << '\n';

        temp_pupil.clear();
    });
}

But this holds the lock way too long, so, even better would be:
void showCalibration()
{
    repeat<9>([&](auto i)
    {
        auto data = std::vector<cv::Point2d>{};

        {
            auto lock = std::unique_lock(mu);
            cond.wait(lock, [] { return not temp_pupil.empty(); });

            std::swap(data, temp_pupil);
        }

        // process the data somehow...
        std::cout << data.size() << "Cali" << i << '\n'; // you may have to synchronize std::cout
                                                         // but I know it's just being used and example, so I'll ignore it
    });
}

And if you wanted to be more efficient and reuse the allocated memory, you could move data out of the loop, and manually clear it before swapping (or at the end of the loop). (If you wanted to simulate a processing delay, you could insert the sleep operation where the processing comment is, I suppose.)
void CaptureFrame()
{
    cv::Point2d pupil;

You generally shouldn’t declare variables until you need them.
for (int i = 0; i <= 500; i++)

Is this meant to be for (int i = 0; i < 500; i++)?
std::unique_lock<std::mutex> lk(mu);
{
    // ... [snip] ...
}
lk.unlock();

There is no reason to use a unique lock, or to manually unlock here. Just do:
{
    auto lock = std::scoped_lock(mu);
    // ... [snip] ...
}

Now, take a step back, and look at the big picture in CaptureFrame(). What this function should do is:

create the data
push the data to the shared data store
notify the waiters that there is data

The lock on the shared data is only necessary for step 2.
That means:
void CaptureFrame()
{
    repeat<500>([&](auto i)
    {
        auto pupil = cv::Point2d(i, i); //create data

        std::cout << temp_pupil.size() << "Captue" << i << '\n'; // don't forget to synchronize std::cout

        {
            auto lock = std::scoped_lock(mu);
            temp_pupil.push_back(std::move(pupil));
        }

        cond.notify_one();
    });
}

The moral of the story is that concurrency and synchronization shouldn’t swallow up your entire program. Merely doing a bunch of stuff concurrently is not the point of your program: your program is (presumably) doing something actually useful. So focus on that, design your program around that functionality, and only add concurrency and synchronization sparingly, and don’t let it become the whole focus of the program.
And also, don’t look at what’s in the standard library, and then design your synchronization around that. Look at what your program needs, and then see what the standard library offers. And if it doesn’t offer something (which is very common), then look at third party libraries. The point is: figure out what your program needs and then look for the tools that will accomplish that… don’t figure out what tools you have on hand and then jigger your program around in order to use them.
And don’t bother with condition variables. They’re inefficient and difficult to use correctly. You almost never really need them.


Get latest jsons with respect to [version and name] key in subjson in java

First of all, you have a grouping operation by process name, then you have the task of finding the maximum by version number per group.

Thus, instead of using nested loops and somehow mashing it all together, simply perform those operations.

As standard operations like grouping and finding a maximum are alreay presenet in the java stream api, all we need is a few helpers to extract the name and the version:

Function<Map<String, Object>, String> extractName = m -> (String) ((Map<String, Object>) m.get("SUBTASK")).get("name");
ToDoubleFunction<Map<String, Object>> extractVersion = m -> Double.parseDouble((String) ((Map<String, Object>) m.get("SUBTASK")).get("version"));

Then, first group by name:

Map<String, List<Map<String, Object>>> byName = taskList.stream()
    .collect(Collectors.groupingBy(extractName));

... which gives you a list of each task type in the value lists.

Now, we can disregard the grouping keys and extract the maximum per list:

List<Map<String, Object>> result = byName.values().stream()
    .map(l -> l.stream().max(Comparator.comparingDouble(extractVersion)))
    .map(Optional::get)
    .collect(Collectors.toList());

Note: the stream.max returns an optional, which would be unset for an empty list. As we cannot generate empty lists here, it is save to simply map via Optional::get to retrieve the value.

All is left is to encode the result list back to json, e.g.

String jsonResult = new GsonBuilder().setPrettyPrinting().create().toJson(result);

Note however, that you should better use a method which operates directly on the data structures, i.e. input and output are List<Map<String, Object>> and another outer wrapper method to do the decoding and encoding. Do one thing in a method.


Instead of fgets, you can use fread to read directly into the file_out:

int totalRead = 0;
int size;
while( fileSize > total_read && (size = fread(file_out + totalRead, 1, fileSize - totalRead, file) != 0) {
    totalRead+=size;
}
if(totalRead < fileSize){
    //couldn't read entire file
}
file_out[total_read] = '\0';

return file_out;

This avoids the \$O(n^2)\$ complexity of doing strncat on a growing string.

Doing an exit from within a helper function is not recommended because the calling code cannot recover from it. Instead, return a special value that specifies something went wrong.

Also, make up your mind about the naming convention of camelCase vs. snake_case.


Not sure why you complicated it, a simple set of operators could do the same:

Observable<SlowComponent> mSlowComponent;

SerialDisposable mDisposable;

@Override
public void onCreate() {
    super.onCreate();

    mDisposable = new SerialDisposable();

    mSlowComponent = Observable.fromCallable(() ->
        DaggerSlowComponent.builder()
        .contextModule(new ContextModule(this))
        .build()
    )
    .subscribeOn(Schedulers.io())
    .replay(1)
    .autoConnect(0, mDisposable::set);
}

@Override
public void onDestroy() {
    super.onDestroy();
    mDisposable.dispose();
    mSlowComponent = null;
}

Main points:

Use fromCallable for a single element result
replay(1) will keep replaying a that single result
autoConnect(0) will start the sequence immediately, even without subscribers yet
mDisposable will allow the sequence to be cancelled if the activity gets disposed while the slow component is still being created.

Edit:

I almost forgot, SequentialDisposable is internal to RxJava, the public version is SerialDisposable.


Over-all, you say you are a beginner programmer, but you are off to a very nice start!  All my suggestions focus around one concept: the Interface.
You are definitely ready to read Joshua Bloch's "Effective Java 2nd Edition" which is all about creating great interfaces.

+1 using generics with collections

-1 import wildcard - Though it's a pain, you should really specify each import.

Prefer interfaces for return types:

OK:

public ArrayList<Account> addAcc(Account acc)...

Better:

public List<Account> addAcc(Account acc)...

Now you can use any kind of List without breaking client code.  Heck if you can get away with it, it gives you even more freedom to use:

public List<Collection> addAcc(Account acc)...

Careful with Static...

Static means this variable exists on the Bank class instead of having one for each object (instance).  I think you want one list of accounts for each Bank which means you don't want Static.

Prefer Private to Public

Public means all clients can access it.

Not so good:

public static ArrayList<Account> bankAccounts = new ArrayList<Account>();

Private means you have to provide get/set methods for users of your API to access this variable.  Final means you can never create a new ArrayList for bankAccounts.

private final List<Account> bankAccounts = new ArrayList<Account>();

Favor Interfaces over Inheritance

They are a little more work up front, but inheritance forces you to make variables and constructors protected instead of private.  But if you want to use inheritance, then give Account a constructor to take on some of the work:

public abstract class Account {
    private String owner; // person or business
    private int balance;

    protected Account(String own, int cash) {
        owner = own;  balance = cash;
    }

    public String getOwner() { return owner; }
    public void setOwner(String own) { owner = own; }

    public int getBalance() { return balance; }
    public void setBalance(int cash) { balance = cash; }

    public abstract String getAccountType();

    public String toString() {
        return new StringBuilder("Account Type: ")
                .append(this.getAccountType())
                .append(" | Account owner: ").append(this.owner)
                .append(" | Account balance: $").append(this.balance)
                .append(" | Account active for: ").append(timeOpened)
                .append(" days").toString();
    }
    ...

You notice I use a StringBuilder instead of string concatenation with plus.  This can make a big speed and memory difference if the concatenation is ever done in a loop.  In some situations what you did is OK, but I'm not sure about this one.  Better safe than sorry.

Then:

public class SavingsAccount extends Account {
    public final static String SAVINGS_ACCOUNT = "Savings Account";
    public SavingsAccount(String own, int cash) {
        // Call account constructor...
        super(own, cash);
        ...
    }
    public String getAccountType() { return SAVINGS_ACCOUNT; }
}

This assumes you are going to add functionality to the individual Account sub-classes.  If not, just make AccountType an enum inner class of Account:

public abstract class Account {
    public enum AccountType {
        PERSONAL("Savings Account"),
        BUSINESS("Business Account");
        private final String name;
        AccountType(String n) { name = n; }
        public String getName() { return name; }
    }
    private String owner;
    private int balance;
    private AccountType type;
    protected Account(String own, int cash, AccountType t) {
        owner = own;  balance = cash; type = t;
    }
    ...
}

Interest Calculation

I think your interest calculation is done for fun, but having worked for a bank, it is a little disturbing.  :-)  For one thing, I can get very rich by just making repeated withdrawls and deposits to increment the time counter.  For another, I can create a second bank Bank getRich = new Bank();  Every transaction I make there, affects all accounts at myBank because time is static, thus has a single copy on the Bank class, not on the individual Bank object instances.

Worse yet, Bank.time is public, so without making a new bank, I can just call Bank.time = (Integer.MAX_VALUE - 1) - (myAccount.balance * 0.15);  Then call myAccount.getInterest();  myAccount.withdraw(myAccount.balance);

Conclusion

Over-all, you are well on your way to becoming a great programmer.  A code review necessarily focuses on the things you should change, but this is an excellent beginner effort.  Actually, I think you are being humble calling yourself a beginner.

To take it to the next level, I'd recommend you read Josh's book or find other sources for API design.  The more you can make private, the less you can expose for clients of your API, the easier it is to make changes to your implementation down the road, and the fewer problems they'll have with it.  Good luck!

P.S.

I'd recommend you spend some time with JavaDoc.  Not only is it good to comment your code in general, but it makes you focus on the way someone else will view your classes - makes you view your work as an API.  When I read my own generated JavaDocs, I always have, "Oh, that's public?  That's accessible?" moments that end up making my code better.


Python random number generator between 1 and 9

Without dwelling too deep into your code there are a few alternatives. After a very quick google search, I stumbled upon this question on SO.

They propose two different solutions.

import random
print random.sample(xrange(1, 10), 3)

This will create three distinct numbers with values ranging from 1 to 9. If you do not want the three numbers to be different, you could try the following

import random
print [random.randrange(1,10) for _ in range(3)]


Emulate Java 8 predicate chaining in JavaScript

I believe you could retain the same level of flexibility without managing extra objects by using higher order functions. This also has the advantage of treating the predicates as functions and nothing more.

const records = [
  { name: 'Andrew' , age: 21, position: 'Developer' },
  { name: 'Bill'   , age: 26, position: 'Developer' },
  { name: 'Chris'  , age: 45, position: 'Manager'   },
  { name: 'Dave'   , age: 30, position: 'Developer' },
  { name: 'Eric'   , age: 32, position: 'Manager'   }
];

const display = ({ name, age, position }) =>
     `${name} (${age}) [${position}]`;

const not = condition => (...args) => !condition(...args);

const and = (...conditions) => (...args) =>
    conditions.reduce(
        (a,b)=>a&&b(...args),true
    )

const or = (...conditions) => (...args) =>
    conditions.reduce(
        (a,b)=>a||b(...args),false
    )

const ageOver21 = ({age}) => age > 21
const isDeveloper = ({position}) => position === 'Developer';
const ageOver21AndIsDeveloper = and(ageOver21,isDeveloper);

console.log(records.filter(ageOver21AndIsDeveloper).map(display).join(', '));

const billOrManager = or(
    ({name}) => name === 'Bill',
    ({position}) => position === 'Manager'
)

console.log(records.filter(billOrManager).map(display).join(', '));

const notUnder30 = not(({ age }) => age < 30)

console.log(records.filter(notUnder30).map(display).join(', '));

console.log(
    records.filter(
        or(billOrManager,ageOver21AndIsDeveloper)
    )
    .map(display).join(', ')
);


The main problem IMO is, that you cram it all into a single method which is not helpful to organize your thoughts.

When I tried this for comparison, I came up with the following in pseudo code:

// outer logic
compress(s)
    rle = doRunLengthEncoding(s)
    if rle.length < s.length return rle
    else return s

// base algorithm
doRunLengthEncoding(s)
    res = empty String buffer
    char[] characters = s.toCharArray
    int startIndex = 0
    while startIndex < characters.length
        int endIndex = findEndOfCurrentSequence(startIndex, characters)
        res.append(currentChar).append(endIndex - startIndex)
        startIndex = endIndex
    return res

// return the first index i, where c[i] != c[start], return
// c.length if there is no such index
findEndOfCurrentSequence(start, c)
    ... // simple enough

This way, you divide the problem into manageble pieces, give you thoughts a place to stop every once in a while, and should get rid of this nervousness.

BTW: from an interviewer's point of view (at least I you want into my team in my country ;-)) a well thought pseudocode algorithm is worth more than working code. If you apply for a programmer's job, I just assume that you have the basic skills to use an IDE and kick against some piece of code until it compiles and produces the correct result. What I am looking for is organized thoughts and problem solving skills.

One last thing: there is one and only one correct exception to throw for a null parameter that must not be null: NullPointerException. Ideally by simply using Objects.requireNonNull.


Summing the Product of Array-member combinations

Your performance problem here is related to a number of things, but the most significant is the algorithm you use.

Consider the following math:

ax + bx + cx + dx ... == x(a + b + c + d + ...)

Using that logic, the basic math for one array can be simplified.... for example, you can take the second array, sum up the values, and call that sum x.

Now you just need to take all the values in the first array, and multiply them by the sum of the second array, instead of summing the individual products.

As it happens, you can take the same logic, and apply it the other way as well. Bottom line, is that the solution is simply the product of the sums of the arrays:

#include <iostream>

int sum(int count) {
    int tmp, sum = 0;
    for (int i = 0; i < count; i++) {
        std::cin >> tmp;
        sum += tmp;
    }
    return sum;
}

int main() {
    int N, M;
    std::cin >> N >> M;
    int suma = sum(N);
    int sumb = sum(M);
    int result = suma * sumb;
    std::cout << result << "\n";
    return 0;
}

Note, that:

the above code no longer uses "using namespace std;"
The sum method no loger uses static variables. Those are a bad idea especially when it comes to re-entrant code.
Output a newline after the last line.


I'll go through the code line-by-line:

 1    getNthFromEnd :: Int -> [a] -> a
 2    getNthFromEnd _ [] = error "Empty list given"
 3    getNthFromEnd nth list
 4        | listLength < nth = error $ "List length must be greater than " ++ show nth
 5        | listLength == nth = head list
 6        | listLength >= nth = list !! (listLength - nth - 1)
 7        where listLength = length list
 8    getNthFromEnd _ _ = error "Unknown exception occurred"

Line 1

Type signature - good!

Line 2

A function which calls out to error is kinda frowned upon. Such functions are
called partial functions because they could throw an exception and that is not
indicated in the type signature. That's why some people don't like to use head
and tail - they prefer to use pattern matching instead for these functions.
This is not really a critic of your code, more just an observation. If you were
to write documentation for this function you might warn users that it is partial,
although they might be able to guess from the description that it necessarily has to be.

More on partial functions:

https://begriffs.com/posts/2013-08-18-dont-be-partial-to-partial-functions.html

Line 4

I would change the error message to List length must be at least ... to match the comparison.

Lines 4 -- 6

Clearly one of the three comparisons has to hold, so for efficiency you can change
the guard in line 6 to an otherwise clause:

| listLength < nth  = ...
| listLength == nth = ...
| otherwise         = ...

This avoids an unnecessary comparison check when listLength is greater or euqal
to nth.

Another common Haskell idiom is to match on the result of compare like this:

-- may need Data.Ord

case compare listLength nth of
  LT  -> ...
  EQ  -> ...
  GT  -> ...

This has the advantage of being provably exhaustive by the compiler. However, it may turn out to be the slowest of the three. It depends a lot on how smart the compiler is. I don't see it used a lot in the Prelude functions for integer comparisons, and I imagine there is an efficiency reason behind that.

To summarize:

The code you've written is exhaustive (handles all the cases) just because we know that one of the comparisons has to hold. But GHC can't prove this, and it may perform an extra comparison when it doesn't need to.
Using an otherwise clause is exhaustive because we're using an otherwise clause. But it avoids an extra check sometimes.
Using compare is provably exhaustive by the compiler.

In any case, this declaration will handle all the cases which leads to...

Line 8

Based on the previous discussion, your function will never get to this point so
this line isn't needed. Even if it did, GHC will throw it's own error with a message
like:

*** Exception: /tmp/err.hs:3:1-17: Non-exhaustive patterns in function foo

Moreover, having this catch-all clause is hiding a potentially useful warning. If you remove that line and compile with -Wall GHC reports:

/tmp/pats.hs:5:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘getNthFromEnd’: Patterns not matched: _ (_ : _)

This raises two points:

The way you've written the code you are not proving to GHC that you are handling all of the list patterns. GHC would like you to write the second stanza with a pattern:

getNthFromEnd nth list@(:) =

That enables GHC to know that you've covered both the empty list and non-empty list cases.

Using the catch-all clause prevents GHC from making this check.


using namespace std;

You import using namespace std;, but you actually only use it in your call to cout.  As a general rule, you don't want to import this in its entirety, but to call the components directly, like in your calls to std::cin.  See Why is using namespace std considered bad practice for more information.

Function Declaration

As a general rule, you order C++ functions from last used to first, unlike in Java.  That means your oper() method would typically be written above your main() method.  Typically, you only explicitly declare functions in header (.h) files, and when two functions call each other and you do not have a .h file to go with your .cpp file.

Comments

Please do not use comments when it is obvious what is happening.  Your only comment here does not help understand either the how or why of the program.

Style

Please use braces around your if statements.  At first, I thought you had a bug here because of the two lines, but then I realized it was just a line break in a single statement.  Braces would help clear this up, as would writing the statement either on one line, or with better indentation as:

cout << "\nx = " << x
     << ", y must be < " << x << "\n";

Error Handling

Your program has absolutely no error handling, and that is perfectly understandable at this point.  Eventually, however, you will need to use a try block to ensure your program will not crash if the user enters invalid input and a loop to ensure a valid value is eventually entered.  Bjarne Stroustrup's "Programming: Principles and Practice Using C++" dedicates the majority of several chapters to proper error handling, and I strongly recommend you read this book; it will help you with your Java programming as well as your C++ programming.

Improvements

You only output the result if the x value entered is greater than the y value entered.  Your program should output the result when y is greater than x, and when x is the same value as y as well.


Style

Variables and functions (except constructors) in JavaScript are normally written in camelCase with a leading lowercase letter. It's not mandatory, but you'll find it easier to work with others if you follow a language's conventions. There are many guides out there, but I mostly follow Google's JavaScript Style Guide.

Some of the variables do not change once set. These should use ALL_CAPS to denote that they are constants and probably assigned at the top.

Another point in the guide is to surround all operators and keywords with a space. Omitting the space between if, while, etc. and the opening parenthesis makes it harder to skim without syntax highlighting.

You can omit comments that merely restate the code in prose. At best they waste the readers time, and at worst they become misleading or incorrect when they aren't changed with the code. Good comments state programmer intent or clarify tricky algorithms. This comment adds no value.

// increment repeats
Repeats++;

Bug

As I noted in the comment, you have a typo bug:

if(BlockY <= MinY || BlockX >= MaxY) {
                     ^^^^^^

This is common when using similarly-named variables, but it's difficult to avoid doing so in rendering code.

Clarity

You can improve the performance of the random choice between -1, 0, and 1--and in my opinion make it more obvious--using a simpler equation without the array:

BlockX += floor(3 * random()) - 1;

You are using a while loop where a for loop would be more obvious. As written, you have to scan the whole body to see that Repeats only gets incremented once at the end. Use this instead:

for (var Repeats = 0; Repeats < MaxRepeats; ++Repeats) { ... }


Reduce the length of words in a sentence

Review

Magic numbers

4 is a magic number, it is best to assign these to a variable name, that way it is more clear what this number means

numbers don't have names, variables do

MAX_WORD_LENGHT = 4

Use built-ins when possible

to_keep = word_length - to_cut
if to_keep < 4:
to_keep = 4

Can be replaced with the max builtin

 to_keep = max(word_length - to_cut, 4)

Add tests

That way it becomes easy to check after a change if the function still works

Alternative

I went a slightly different route,

Instead of joining after each word, I calculate the chars we need to cut beforehand

So we can keep a variable that will hold the amount of chars we still need to cut to reach our target

And only at the return join the words

import doctest

MAX_WORD_LENGHT = 4

def cut_everything(sentence, max_length):
    """
    reduces each word in sentence to a length of 4

    :type sentence: string
    :param sentence: the sentence to cut
    :type max_length: int
    :param max_length: the length to which the sentence will be reduced

    >>> cut_everything('foo bar foooobar', 16)
    'foo bar foooobar'

    >>> cut_everything('foo bar foooobar', 8)
    'foo bar fooo'

    >>> cut_everything('foo bar foooobar baaarfoo', 20)
    'foo bar fooo baaarfo'

    >>> cut_everything('fooooooo baaaaaaar foooobar baaarfoo', 2)
    'fooo baaa fooo baaa'
    """
    words = sentence.split()
    chars_to_cut = len(sentence) - max_length
    for index, word in enumerate(words):
        if chars_to_cut < 0:
            break
        word_length = len(word)
        if word_length > MAX_WORD_LENGHT:
            to_keep = max(word_length - chars_to_cut, MAX_WORD_LENGHT)
            words[index] = word[:to_keep]
            chars_to_cut -= word_length - to_keep
    return ' '.join(words)

if __name__ == '__main__':
    doctest.testmod()


Regular expressions can be a good way of processing text input in situations like this. Your current process finds every digit in the input string, concatenates it together, and then parses the result.

I doubt that this is a good solution because it makes examples like: "There are 10 people arriving at 9pm" parse as 109. Is that what you want?

Even then, Regular expressions are probably a good solution:

str = Regex.Replace(str, @"[.\D+]", "");

In str, replace all non-digits with "" (i.e. remove any non-digits).

Your code will still fail with an exception for input like "Hello", which has no digits, because the ToDecimal call will fail. Values with multiple . characters will also be interesting...

Additionally, your code does not support negative input values. This can be a trick to accomplish, but, again, using regular expressions, it is not horrendous.

Finally, I feel you should only be parsing the first set of decimal-like digis in the input, not all of them.

Putting this all together, I would have:

use regex
parse the first set of digits
accept negative inputs

And use the code:

    public static Decimal ExtractDecimalFromString(string str)
    {

        Regex digits = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*");
        Match mx = digits.Match(str);
        //Console.WriteLine("Input {0} - Digits {1} {2}", str, mx.Success, mx.Groups);

        return mx.Success ? Convert.ToDecimal(mx.Groups[1].Value) : 0;
    }

I have put this, with some test cases, in this Ideone here;


Add currency fields to get a subtotal, then add other values but only if the relevant checkbox is checked

//Add up some values which are always part of the subtotal
decimal subtotals = val1 + val2 + val3 + val4 + val5 + val6 + val7 + val8;

decimal ditem1Cost;
if (Item1RateYN.Checked) {
    decimal.TryParse(item1Cost.Value.ToString(), out ditem1Cost);
    subtotals+=ditem1Cost;
}
decimal ditem2Cost;
if (Item2RateYN.Checked) {
    decimal.TryParse(item2Cost.Value.ToString(), out ditem2Cost);
    subtotals+=ditem2Cost;
}

Is slightly better.

If using C#7 remove decimal ditem1Cost = 0; and replace decimal.TryParse(item2Cost.Value.ToString(), out ditem1Cost) with decimal.TryParse(item2Cost.Value.ToString(), out decimal cost)


Automating the install of PostgreSQL from Shell

I recommend using psql -c command for the first invocation of psql, or better yet, just use the createuser command.

For the second invocation, you might want psql -f /etc/schema.sql.  I would also suggest using the --single-transaction flag, so that in the unlikely event of an error, the failure will be blatantly obvious since the spider database will be empty.  (I assume you will also create a database named spider sometime before trying to import data into it.)


You might consider providing typedefs for the types expected by std::iterator_traits.
Your type should meet the requirements of InputIterator.  This means that you should also provide an overload for operator ->.
The semantics of operator != are not really useful.  For example, this won't allow you to use your iterator in the idiomatic

line_iterator begin = …;
line_iterator end = …;
while (begin != end)
  {
    std::cout << *begin << std::endl;
    ++begin;
  }

because there is no value you can set end to such that it compares not non-equal to begin only after begin was advanced a certain number of times.  I suggest you implement it somehow like this:

friend bool
operator!=(const line_iterator& lhs, const line_iterator& rhs) noexcept
{
  if (lhs.m_stream == nullptr && rhs.m_stream == nullptr)
    return false;
  else if (lhs.m_stream == nullptr)
    return rhs.m_stream->good();
  else if (rhs.m_stream == nullptr)
    return lhs.m_stream->good();
  else
    return lhs.m_stream != rhs.m_stream;
}

This will allow you to use a default-constructed line_iterator as end and have it compare not non-equal to begin only after begin's stream is exhausted.

You should then implement lhs == rhs as !(lhs != rhs).
You are making many copies of the string which is not as efficient as it could be.  I also feel that it makes your code more complicated than necessary.  You should read directly into m_string by implementing the increment operator as

line_iterator&
operator++()
{
  assert(m_stream && m_stream->good());
  std::getline(*m_stream, m_string);
  return *this;
}

and the dereferencing operator as

const std::string&
operator*() const
{
  return m_string;
}

In your constructor, default-construct m_string and (if the pre-conditions are met) advance once.
Personally, I prefer to only mention those members in the constructor's initializer list that depend on the constructor arguments.  Those that get default values I prefer to initialize in the class definition.

class line_iterator
{

public:

  line_iterator()
  {
    // nothing to do
  }

  line_iterator(std::istream& istr) : m_stream {&istr}
  {
    if (m_istr->good())
      std::getline(*m_stream, m_string);
  }

  …

private:

  std::string m_string {};     // defaults to empty string
  std::istream * m_stream {};  // defaults to 'nullptr'
};

If you're going to make the friends inline anyway, I'd prefer to define them right in the class body.


It appears that you're just trying to create a list of players from the id values on a list of <li> tags and also build a comma separated list of those ids.  If that's the case, you can do the entire code block like this:

var players = $("#jailplayer > li").map(function(index, elem) {
    return this.id;
}).toArray();
var sender = players.join(",");

Note: this doesn't populate variables player1, player2, etc...  Instead, it puts the players into an array where they are likely easier to deal with later.

Also, it is unclear what you are trying to do with this:

var ize = [sender];

If you explain the purpose of that, we could offer help on whether that's the right way to to it.  Storing an array of a single value that's a comma separated string list of values seems a bit odd which is why I ask.

Key concepts here:

$("#jailplayer > li") - get all the desired <li> tags into a jQuery collection so we can iterate over them.

.map() - iterates over a jQuery collection building a new jQuery object containing the values that the callback returns.  Note, the callback will be passed this as each successive element in the original jQuery collection and the id value can be referenced simply as this.id.

.toArray() - get the array out of the jQuery object that was returned so you have just an array, not a jQuery object any more.

.join(",") - take all the elements of the array and join them into a string with the passed in separator between them.


Hashes does not need to be unique, a good hash will have a good distribution and as little as possible collisions.

Which are the implications of this? Given two dictionaries \$a\$ and \$b\$ (with \$a = b\$) and an hash function \$\operatorname{f_{hash}}(D)\$ you can assert that \$\operatorname{f_{hash}}(a) = \operatorname{f_{hash}}(b)\$; similarly for \$a \neq b\$ the same condition may also be true. With this in mind default behavior may be considered wrong but simply they can't provide an effective generic-enough function. Also note that they explicitly suggest to do not override GetHashCode() if object is mutable (a dictionary is) because its hash may be used in an outer container.)

Which hash function is better may be not a simple choice because it has to be choosen to balance complexity, performance and distribution. Some knowledge of the elements you want to hash will also help you to pick the best one (in your case...where those numbers come from? Is there any rationale behind them to reach a better distribution?)

Let's start with a very simple case: hash is the number of items in the collection \$\operatorname{f_{hash}}(D) = \#(D)\$. It's better than default implementation and it's pretty fast but it's still a terrible hash function (huge number of collisions.) More often than not I just needed this.

Any other implementation depends on context: are items immutable (or you hash only keys)? In this case you may keep a running hash when inserting/removing items (assuming hash function you use can be reverted to subtract a now removed hashed item.)

What I sometimes do for dictionary of immutable items (unless your dictionary is made by thousands items, or you need hash in a very performance critical function) is to calculate hash only when required and cache it, cache will be invalidated when you add/remove an element. Proof of concept (here I override just Add() but you have to do it also for Remove() and Clear()):

public override int GetHashCode() {
    if (_hash == null)
        _hash = CalculateHashCode();

    return _hash;
}

public override void Add(TKey key, TValue value) {
    base.Add(key, value);

    _hash = null;
}

Note that if items are mutable then you can't cache calculated hash and it must be recomputed each time it is required (unless they're also observable objects...)

Which hash function? That's an hard choice, your magic numbers must be chosen to have a good distribution (if you know anything about objects stored in the dictionary.) As starting point you may use the simplest solution (unless you have some knowledge about distribution of hashes of elements): even \$\operatorname{xor}(\{d_1,\ldots,d_n\})\$ is good enough (you will use as much bits as used by hashes of items/keys in your dictionary.) It has the advantage to be fast, if you just need a quick comparison of two dictionaries (or lists) then you probably want the fastest algorithm (not the best - what a vague concept - one.)

Next step may be to use a popular general purpose (non-cryptographic!) hash function to balance between performance and quality, you may take a look to CityHash (developed by Google). It has good performance and it's easy to implement (plus: it may have different sizes then you may even decide to devote 16 bit for keys and 16 bits for values.) Its inputs are hashes from keys/values (then don't forget that also those hashes have to be of good quality)

To summarize: too many ifs, right? That's why to-do-nothing path was a good choice...


SQL query for adding column value to compare with other column

I am not exactly familiar with Oracle syntax, but I know that Oracle supports indexes on functions.  I'm not sure if it will be used, since there is grouping involved, but you may wish to look into creating an index for this query if performance of the query becomes an issue.  A guess at the syntax used to create the index would be:

Create index net_qty on table_inventory(SUM(quantity + in_coming_qty) - SUM(locked_qty));

You can search for "Oracle function based index" for more information.


Generating permutations with repetitions of string

I'm not going to rewrite this code right now, but I can highlight a few points:

Naming.

Identifiers should have a meaningful name.
Disemvoweling is evil.
Adding a 1 after an identically-named variable is bad.
Adding a 2 after an identically-named variable is terrible.
Adding 21 instead of a 3 after an identically-named variable is careless.
If you think you need the same variable 3 times in one function, something's not right. Right? I think Tim's comment on your original post has a huge golden clue on that matter.

UI is for presentation. Logic that isn't presentation logic shouldn't need to know there's a UI involved.

Decoupling your logic from the UI helps making your code testable.
Learn to pass parameters into your functions.
Knowing exactly what's involved is very hard to tell, we need to puzzle out the whole thing just to figure out what RichTextBox1 is supposed to contain; your naming isn't helping.

Implicit string-to-numeric conversion is ugly and bug-prone, especially with user input.

Assume the user is a 3 year old that could click anywhere and enter anything in any TextBox.

You have many, many, many things to worry about before you can think of improving performance.

Using Random isn't making it any faster. I don't think Random is warranted here.
Access the UI once to get the values you need, once to write the values you've computed; pass the values as parameters (I said that before, I'll say it again - here, done).
It's not the job of a permutation function to access the UI. Ever. Take values in (as parameters), do your thing, spit out a result (as a return value).
perm (bad name) shouldn't be an instance variable. Not even a parameter. It's only meaningful within the permutate function: that's where it belongs.

That's all folks! I might edit this post later with actual code.


Go fmt

First off, always go fmt your source code. The best thing about Go is that it always looks the same.

Godoc

Follow the godoc standard for comments. When commenting a function, start with the function name, capitalized, and end with a dot. Use proper grammar (like capital letter after punctuation). This makes automatically generated documentation look great, and further normalizes how Go code looks. TokenStack represents the input stack. is a good first sentance to start with.

(Actually, maybe TokenStack should be named InputStack, if that's what it really is?)

Const

Using iota to assign a single value like you are doing looks wierd. It's not that clear what you are doing.

const T_NUM = 1

or

const T_NUM = iota+1

or actually use the first value; make the nil value useful:

const (
    T_UNKNOWN = iota
    T_NUM
)

Usually, there is more than one constant. Since you're only using one, I'm wondering if it would be better to remove it as well. Every valid token is T_NUM, after all, so why have a constant for it in the first place?

Type

If you are going to use T_NUM as an enum, give it a type. Right now, T_NUM is just a constant integer. That means we can do weird things like T_NUM + T_NUM * 5. If we define a new type, such as type TokenType int and then make T_NUM a constant TokenType instead, we get a compililation error, since multiplying a TokenType by a number doesn't make sense. In many C-like languages, like C and C++, defining a new type like this wouldn't help, but in Go, types are real types, not type aliases.

Package main

You're starting the file with package main but there's no func main() in the source code. It looks like this is a library package, and in that case, the package name should be changed. The Go Blog has a great post about naming packages and things in packages.

NoMatch

It feels like NoMatch should be an error (for example `var NoMatch = errors.New("could not match TokenStack to known rules"). Right now it looks like C-code.

Exporting everything

Everything in your package is exported. You probably want some of the functions or types to be package-local. I'd aim for only exporting a single function: Parse. That way, it's super simple for someone to get started with the package. V and T should definitely not be exported as they stand, but if they have to be exported, they should probably be renamed.

Package testing only gets away with exporting T because that's almost the only thing it's exporting, and everytime you use it, you write testing.T. The name of the package helps explain what T is.

In-bound errors

Some of your functions return NoMatch on error, which is just -1. This is a common way of doing things in C or C++, but not in Go. It's usually better to return multiple values, the last one being an error, so that the caller can know how to check for errors without having to read the documentation first. Maybe all negative return values are errors, or just -1. What happens if the library updates and adds another possible return value; do we get subtile bugs? Is 0 an error? atoi is a good example. In C, there's no way of knowing if it encountered an error (or if it just parsed the string "0"). In Go, it returns (int, error).

if else if else if else if

The Go switch statement is very powerful and can be used instead of long if/elseif/elseif/else statements. If you omit the argument to switch it looks at the cases one by one until it finds one that is true, just like a long if/elseif/elseif statement does. In this case, however, since you need semicolons in your if-statements, switch does not work. Just a pointer for future code.


Algorithm that creates in a systematic form, matrix with zero-one elements

First of all I would try to avoid all the matrix operations like trimming, joining, etc.
And instead just find a function that tells what value is on each position
bool tell(int x, int y, int K);

This would of course require more mathematical skill then programming, but you might eventually end up doing just this:
arma::mat P;
int maxY = K * (K-1) / 2
for (int y = 0; y < maxY; ++y) {
  for (int x = 0; x < K; ++x) {
    P.set(x, y, tell(x, y, K) ? 1 : 0)
  }
}

If tell(x,y) has O(1) complexity, this will probably be faster.
Another option that I can think of is similar, but more iterative.
Fill the topmost KxK part of the matrix with the pattern.
Then another (K-1)x(K-1) part of the metrix, fill with the (K-1) pattern while filling the last column with zeroes.
then another part of size (K-2)x(K-2) fill with pattern of size K-2 while filling the last two columns with zeroes.
And so on and so on until trying to fill pattern 0x0 where you terminate.
But you'll end up on something similar to the previous
int Y = 0;
for (int step = K; step > 0; --step) {
  for (int y = 0; y < step; ++y, ++Y) {
    for (int x = 0; x < step; ++x) {
      P.set(x, Y, tell(x, y) ? 1 : 0)
    }
    for (int r = step; r < K; ++r) {
      P.set(r, Y, 0)
    }
  }
}

here the tell function actually becomes quite trivial and third parameter is not even needed
bool tell(int x, int y)
{
  return x >= y;
}

Whether the tell function for the first implementation is possible in O(1) and how to do it I leave to you and the mathematician inside of you :)


If you need risk level to be an enum (which sounds like good idea anyway), it would be nice to tightly couple the meaning of, say, Risk.Level2 with the range of raw values it represents, such as 1..<5. In other words, the enum itself should define all the applicable ranges. Depending on your specific needs, one of the following two approaches may be along the lines of what you're looking for:

enum Risk {

    case Level1, Level2, Level3, Level4

    var range: Range<Int> {
        switch self {
        case Level1: return 0..<1
        case Level2: return 1..<5
        case Level3: return 5..<10
        case Level4: return 10..<Int.max
        }
    }

    init(_ risk: Int) {
        switch risk {
        case Level2.range: self = Level2
        case Level3.range: self = Level3
        case Level4.range: self = Level4
        default: self = Level1
        }
    }
}

Risk(5) //--> Risk.Level3

Or:

enum Risk: Int {

    case Level1 = 0
    case Level2 = 1
    case Level3 = 5
    case Level4 = 10

    var range: Range<Int> {
        switch self {
        case Level1: return Level1.rawValue..<Level2.rawValue
        case Level2: return Level2.rawValue..<Level3.rawValue
        case Level3: return Level3.rawValue..<Level4.rawValue
        case Level4: return Level4.rawValue..<Int.max
        }
    }

    init(_ risk: Int) {
        switch risk {
        case Level2.range: self = Level2
        case Level3.range: self = Level3
        case Level4.range: self = Level4
        default: self = Level1
        }
    }
}

Risk(5) //--> Risk.Level3

This would all be much nicer if we could have enum Risk: Range<Int>. Unfortunately, Range<Int> cannot be expressed as a literal, so cases could not be assigned rawValues...


You are looking for values in a sorted array, first thing that comes to mind is binary search (improves to \$O(n \log n)\$).

However because the values you look for are also sorted then you know that the next value will be after the value you found in the last iteration. Keep the index where you broke out of the inner loop and start there during the next iteration.

int innerIndex = 0;
for(int count = 0; count < sorted1.length; count ++) {
      for(; innerIndex < sorted2.length; innerIndex++) {
           if(sorted1[count] == sorted2[innerIndex]) {
                duplicates.add(sorted1[count]);
           } else if(sorted1[count] < sorted2[innerIndex]) {
              break;
           }
       }
 }

Otherwise you can pretend to merge the arrays. It's essentially the same algorithm but makes it clearer what is happening:

int index1 = 0, index2
while(index1 < sorted1.length && index2 < sorted2.length){
    if(sorted1[index1] < sorted2[index2]){
        index1++;
    }else if(sorted1[index1] > sorted2[index2]){
        index2++;
    }else{
        duplicates.add(sorted1[index1]);
        index1++;
        index2++;
    }
}


First of all, I would specify that your stack is using a "dynamically allocated array", as opposed to just an array, as I at first expected a C array when looking at the title.  That varies from person to person, though.

On to more important things:

I would not print anything in the stack functions.  If someone wants information on what they're pushing and popping, let them do it themselves.
You seem to be missing a peek function.
Either throw an exception or add an assert to pop for the array_ == last_ case.
length_ should actually be called capacity_.
expandArray may leak memory if the copy throws.  I would use an std::vector<T*> internally for this stuff.
You don't check that length > 0 in the constructor.
I would not allocate so anything by default.
You lack all three of a copy constructor, assignment operator, and destructor, so you'll definitely leak memory.  You should also have a move constructor and a move assignment operator, but those aren't as critical.
You provide no way to check whether the stack is empty.


This mostly looks good to me.
I don't think that logging exceptions should be the concern of your rDB class. Also, you could utilize the PSR logger interface

class rDB extends PDO implements \Psr\Log\LoggerAwareInterface
{
    //do not override the PDO constructor

    public function setLogger(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    //override the PDO methods as you have done but, call
    //$this->log() instead of $this->logger->log()
    //i.e.
    public function prepare($statement, $driver_options = array())
    {
        $this->log(\Psr\Log\LogLevel::INFO, $statement, array(
          'driver_options' => $driver_options
        ));
        return parent::prepare($statement, $driver_options);
    }

    private function log($level, $message, $context = array())
    {
        //note: only log if a logger is set
        if ($this->logger) {
            $this->logger($level, $message, $context);
        }
    }
}

A factory method added to your rDb class could be useful to construct an instance for you:

public static function createInstance($params)
{
    $dsn = array_key_exists('dsn', $params) ? $params['dsn']: null;
    $user = array_key_exists('user', $params) ? $params['user'] : null;
    $pass = array_key_exists('pass', $params) ? $params['pass']: null;
    $logger = array_key_exists('logger', $params) ? $params['logger']: null;

    $rdb = new rDB($dsn, $user, $pass);
    $rdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    if ($logger) {
        $rdb->setLogger($logger);
    }

    return $rdb;
}

EDIT
I suggest using a factory method to construct your instance instead of overriding the constructor primarily because 1) Changing the argument list in any overridden method effectively changes the interface. This makes it more difficult to replace one class with another. 2) I feel that constructors should do no more than serve as a way to inject dependencies that are always needed and initialize default values.

In your application, somewhere during initialization/bootstrap:

//Depending on your environment (production, development, etc),
//you can configure different kinds of loggers. For example,
//a development logger would probably log EVERYTHING but a
//production logger might only log error, critical, alert, emergency
$logger = new YourLoggerClassWhichImplementsLoggerInterface();

try {
    $dbConfig = //read in a configuration from somewhere
    $rdb = rDB::createInstance(array(
        'dsn' => $dbConfig->dsn,
        'user' => $dbConfig->user,
        'pass' => $dbConfig->pass,
        'logger' => $logger,
    ));

    //Now pass $rdb to whatever needs it (i.e. a controller).
} catch (Exception $e) {
    $logger->error($e->getMessage(), array('exception' => $e));
    //Display some kind of error page to the user
}


Lookup closest value in Pandas DataFrame

Not sure if this will help, but I'm using this to find nearest in a sorted column: (time series stuff)

result_index = df['col_to_search'].sub(search_value).abs().idxmin()

.sub(search_value) subtracts search_value from the df[col_to_search] to make the nearest value almost-zero,
.abs() makes the almost-zero the minimum of the column,
.idxmin() yields the df.index of the minimum value, or the closest match to search_value.

I got this approach from a similar search, but didn't note the original author or the site I found it.


Simulation of Central Limiting Theorem (CLT)

Even though you are implementing your own random number generator, I would stick to the interface defined in the standard library module random. You could have a random, a uniform, a randint (or randrange if it is inclusive on the end) and a choices method.

Your class should probably also allow setting the seed on creation.

Python has an official style-guide, PEP8, which recommends not using trailing ; and using lower_case both for variables as well as functions/methods.

Even in Python 2 (which you should no longer use), if either the numerator or the divisor is a float, the result is also a float with the division operator /, so you only need to cast one of them. In Python 3 / is always float division and // is always integer division, so no need for the casts to float.

You should always add a dosctring to your code explaining how to use it.

For range, the start is implicitly 0. Also _ is conventionally used for unused loop variables.

Wrap the code that uses your class in a if __name__ == "__main__": guard to allow importing from this script without it running.

class Random:
    """A pseudo-random number generator using a LCG."""
    m = 4294967296 # modulus
    a = 1664525    # multiplier
    c = 1013904223 # increment

    def __init__(self, seed=1):
        """Initialize the pseudo-random number generator with a seed (default: 1)."""
        self.state = seed

    def randint(self, a=None, b=None):
        """Return either a random integer between `0` and `self.m`
        or between `a` and `b` (exclusive?)."""
        if a is None and b is None:
            self.state = (self.a * self.state + self.c) % self.m
            return self.state
        elif a is not None:
            if b is not None:
                return int(self.uniform(a, b))
            else:
                return int(self.uniform(0, a))
        else:
            raise ValueError("Need to also set `a` if you set `b`.")

    def random(self):
        """Return a random float between 0 and 1 (exclusive?)."""
        return float(self.randint()) / self.m

    def uniform(self, a, b):
        """Return a random float between `a` and `b` (exclusive?)."""
        return (b - a) * self.random() + a

    def choices(self, population, k=1):
        """Return a k sized list of population elements chosen with replacement."""
        n = len(population)
        return [population[self.randint(n - 1)] for _ in range(k)]

The usage of this is similar to your code, just with renamed methods.

You can also greatly shorten your examples using list comprehensions and a utility function mean:

random = Random()

def mean(x):
    return float(sum(x)) / len(x)

if __name__ == "__main__":
    N = 999999
    population = [random.random() for _ in range(N)]
    print("Population mean = ", mean(population))

    rnd_num_count = 30
    sample_size = 12
    sample_means = [mean(random.choices(population, k=sample_size))
                    for _ in range(rnd_num_count)]
    print("Mean of sample mean = ", mean(sample_means))

This script has the advantage that you can easily test it with the standard library random module by replacing the line random = Random() with import random. This way you can see if your class produces random numbers somewhat correctly.

If implementing so many different random functions gets tedious, you can also subclass random.Random:

  Class Random can also be subclassed if you want to use a different
  basic generator of your own devising: in that case, override the
  following methods:  random(), seed(), getstate(), and setstate().
  Optionally, implement a getrandbits() method so that randrange() can
  cover arbitrarily large ranges.

This of course means that you are using the standard library and not your own implementations as much. In that case you probably also want to use statistics.mean.


Simple Java calculator with two operands

Your code

Simple is nice. But it would have been good to decompose your solution to multiple methods, for example at least:

a method to read a double
a method to perform the calculation: take the numbers and an operator as parameter and return the result

Other issues:

Don't pre-calculate the result of all possible calculations when you will only use one of them
The print statements are repetitive. If you decomposed the solution to multiple methods, naturally you would have factored out duplicated elements.
Naming, as @Caridorc already covered.

The instructor's code

Sort of nicely written, decomposed, but this is bad code:

Delaying the validation of input by carrying around the String values of supposed numeric values is a terrible idea. As @Caridorc said it too, the numeric input should have been read into the desired types (double in this example) and lift the burden of uncertainty from the rest of the code.
The getInput method is a good idea, but poorly executed. Creating a new Scanner for every piece of input is a waste. Just like there is one System.in, a single Scanner could be used and passed to the method. The method is a huge missed opportunity for actually validating the input, and returning the desired type, instead of a String.
Large try blocks are also better to avoid, and the large try block in the middle is just another consequence of delaying the input validation, that could have been done much better earlier.


Your code seems not to be correct. In case you don't have the substring /plug/pluginr/ it would still return true since indexOf returns an integer containing the position of the first ocurrence. If theres no ocurrence of the substring then it returns -1 which is evaluated to true in JavaScript.

You better use this instead;

function isExt(path){
    return path.indexOf("/plug/pluginr/") > -1;
}


Session state wrapper, extending an existing application

There are 4 places where you have code like,

if (session != null)
{
    List<KeyValuePair<string, T>> questionModelStore;

    if (session["QuestionModelStore"] == null)
    {
        questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];

It would be neater if these were a common subroutine:

List<KeyValuePair<string, T>> GetQuestionModelStore<T>()
{
    var session = HttpContext.Current.Session;
    if (!session)
        return null;
    return (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
}

That would simplify code such as:

public T GetValue<T>(string key)
{
    var cached = GetQuestionModelStore();
    if (cached == null)
        return default(T);
    return cached.FirstOrDefault(t => t.Key.Equals(key));
}

It might be slightly faster to use a Queue than a List, because a Queue is designed to let you enqueue at one end and dequeue at the other.

You're not quite implementing a LRU algorithm: if you want to do that, when you find an item in the cache you should move the item to the most-recently-used end of the list.

There's one bug I see, which is that your methods are generic: the first time you call SetValue it creates a List<KeyValuePair<string, T>>; unless all your SetValue and GetValue methods use the same type of T this will cause a run-time error (casting between different types of T). If all your SetValue and GetValue methods do use the same type of T then you might as well specify what T is instead of making it generic.


Find filenames with 4 digits which are not divisible by 20 and delete them

Requirements

The requirements are somewhat imprecise because they rely on untold assumptions about the filenames we should expect. Before implementing anything, we should try to think about the different inputs we can have and how we should handle them.

In our case, this could correspond to:

what if the regexp does not match (no underscore or less than 3 numbers) ?
what if we have more than 4 numbers ? Should we consider only the first 4 ?
what if the pattern appears more than once ?

In order to tests tests, I've defined the following list of file names from my invention.

files = [
    '.h5',
    '_.h5',
    'foo_.h5',
    'foo_123.h5',
    'foo_1234.h5',
    'foo_1240.h5',
    'foo_12345.h5',
    'foo_12340.h5',
    'foo_12340.h5',
    'foo_12400.h5',
    'foo_12403.h5',
    'foo_123_bar.h5',
    'foo_1234_bar.h5',
    'foo_1240_bar.h5',
    'foo_12345_bar.h5',
    'foo_12340_bar.h5',
    'foo_12400_bar.h5',
    'foo_12403_bar.h5',
    'foo_1234_bar_1240.h5',
    'foo_1240_bar_1234.h5',
]

From here, changes in the code may be considered wrong as they could change the way the code behaves (on some of the inputs above) but I do not know what the expected behavior is.

Improving the code

The first thing we could do is try to be more robust when the pattern does not match.

Usually after a call to re.search, the next step is "if match" (or "if match is None").

Taking this chance to define variables with better names ("digits" instead of re-using "match" for the string of 4 digits, "n" instead of "digits" from the corresponding integer), we'd have something like:

for f in files:
    match = re.search(r'_\d{4}', f)
    if match is not None:
        digits = match.group(0)[1:]
        n = int(digits)
        if n % 20 != 0:
            print("remove file " + f + " (" + digits + ")")
            continue
    print("skip file " + f)

Removing the need for modulo

Division by 20 is simple enough so that the corresponding logic can be moved into the regexp.

Disclaimer: This may not correspond to something we usually want to do but it is fun and interesting so let's do it anyway :)

A number is divisible by 20 if and only if:

last digits is a 0
the digit before that is divisible by 2

We could write:

for f in files:
    match = re.search(r'_\d\d[02468]0', f)
    if match is None:
        print("remove file " + f)
    else:
        print("skip file " + f)

Organisation

It would indeed be worth defining small functions to make your code easier to understand. We could imagine having a function "def file_must_be_deleted(filename)" return a boolean.


Overall, it seems really really good to me and I like the way you use IndexError to count surrounding cells in a concise way without bothering about edge cases.

Here are a few comments anyway :

Removing a useless check

This is not much but you can remove a check of universe[a][b] in

        if universe[a][b] == 0 and countSurrounding(universe, a, b) == 3:
            nextUniverse[a][b] = 1
        elif universe[a][b] == 1 and countSurrounding(universe, a, b) not in (2, 3):
            nextUniverse[a][b] = 0

and it becomes

        surr = countSurrounding(universe, a, b)
        if universe[a][b]:
            if surr not in (2, 3):
                nextUniverse[a][b] = 0
        else:
            if surr == 3:
                nextUniverse[a][b] = 1

(It looks slightly longer though) (I also took this chance to use an additional variable)

Use tuple instead of list if it's not something you plan to iterate over

Here, the surroundings are just pairs and that should be enough. Also, it makes the access of the different elements much more convenient through tuple unpacking.

Iterate in a pythonic way

You shouldn't use range to iterate over a structure when python provide such a convenient way to iterate over it.

For instance, you could do :

surrounding = [(a - 1, b - 1),
               (a - 1, b    ),
               (a - 1, b + 1),
               (a    , b - 1),
               (a    , b + 1),
               (a + 1, b - 1),
               (a + 1, b    ),
               (a + 1, b + 1),]
for a,b in surrounding:
    try:
        if universe[a][b]:
            count += 1
    except IndexError: a

Same kind of argument applies to for a in range(0, 9): for b in range(0, 9): even though you might want to introduce enumerate.


There are a few problems with your validation, and the code itself could be a bit neater.

First up, your code will try to validate impossible puzzles. Sudoku puzzles need to be square-sided You check that the puzzle is square, but your slot-size is not valid. It assumes a side that is a perfect square (4, 9, 16, etc.).

Additionally, you only check the first row is the right length, I suspect your code will validate as true if one of the rows has an extra element (with a carefully-chosen value).

In multiple places you set valid = false, and in those places you should just return false. You know the puzzle is not valid, so why continue checking?

Finally, it would be nice if you could make the checking generic. There are 3 things to check:

all expected elements in each row are present
all expected elements in each column are present
all expected elements in each mini-square are present.

I would try to put that together as a collection of functions for each check:

var extractions = [
    {   name: "rows",
        get:  function(data,span,block,member){
                  return data[block][member];
              }
    },
    {   name: "cols",
        get:  function(data,span,block,member) {
                  return data[member][block];
              }
    },
    {   name: "minis",
        get:  function(data,span,block,member) {
                  var coloff = (block % span) * span;
                  var rowoff = (block / span) * span;
                  return data[rowoff + (member / span)][coloff + (member % span)];
              }
    },
]

function isvalid(data) {
    var size = data.length;
    var slot = Math.sqrt(size);
    for (var block = 0; block < size; block++) {
        if (data[block].length != size) {
            return false;
        }
        for (var ext = 0; ext < extractions.length; ext++) {
            var tmp = [];
            for (var member = 0; member < size; member++) {
                tmp.push(extractions[ext].get(data, slot, block, member));
            }
            for (var i = 1; i <= size; i++) {
                if (tmp.indexOf(i) < 0) {
                    return false;
                }
            }
        }
    }
    return true;
}


Check digital input signals that is sent as an integer using bitwise checking

Firstly, you can simplify the outer else statements:

...
    else
    {
      if ((currentBits & INPUT_0) == INPUT_0)
      {
        ...
      }
    }
...

to

...
else if ((currentBits & INPUT_0) == INPUT_0)
{
} ...

Secondly, if the check of all masks follows the same pattern as showed, you can create a mask checker method like this one (in C# 7.0):

private void HandleMask(int bitPattern, (int mask, Action<bool> action) maskItem)
{
  if ((bitPattern & maskItem.mask) == maskItem.mask)
  {
    if ((currentBits & maskItem.mask) != maskItem.mask)
    {
      currentBits |= maskItem.mask;
      maskItem.action(true);
    }
  }
  else if ((currentBits & maskItem.mask) == maskItem.mask)
  {
    currentBits &= ~maskItem.mask;
    maskItem.action(false);
  }
}

public void IoPort_sigInputChange(int p_nBits)
{
  lock (lockObj)
  {
    var maskItems = new(int mask, Action<bool> action)[]
    {
      (mask: INPUT_0, action: RaiseRunModeEvent),
      (mask: INPUT_1, action: RaiseAllPositionsSetEvent),
      (mask: INPUT_2, action: RaiseOrderEndedEvent),
    };

    foreach (var maskItem in maskItems)
    {
      HandleMask(p_nBits, maskItem);
    }
  }
}

Update

In .net 3.5 you should/could do it in a way like this:

private void HandleMask(int bitPattern, int mask, Action<bool> action)
{
  if ((bitPattern & mask) == mask)
  {
    if ((currentBits & mask) != mask)
    {
      currentBits |= mask;
      action(true);
    }
  }
  else if ((currentBits & mask) == mask)
  {
    currentBits &= ~mask;
    action(false);
  }
}

public void IoPort_sigInputChange(int p_nBits)
{
  lock (lockObj)
  {
    var maskItems = new[]
    {
      new { mask = INPUT_0, action = (Action<bool>)RaiseRunModeEvent },
      new { mask = INPUT_1, action = (Action<bool>)RaiseAllPositionsSetEvent },
      new { mask = INPUT_2, action = (Action<bool>)RaiseOrderEndedEvent },
    };

    foreach (var maskItem in maskItems)
    {
      HandleMask(p_nBits, maskItem.mask, maskItem.action);
    }
  }
}


Optimize this Scheme-written chess engine module

Your question and code are both confusing to me, but I'll give it a shot.

(define whites) doesn't compile with my standard definition of define.  define usually needs to bind the identifier to something, even if it is just '() or #f.  Since it seems like they (blacks and whites) are meant to hold a-lists, I've initialized them to '().

I don't know what dialect of scheme you're running, but you may be able to drop the outer begin form, and your concatenate function is usually called append in most schemes.  Finally, you may have a list* function so to replace (cons i (cons x y)) with (list* i x y)

Next, in order to call setup, it wasn't immediately clear that setup was a function that took two arguments, the first being an integer intended to be the row to place the pieces onto, and the second being the row to set the pawns.  I would make setup into a thunk since the initial placement of the pieces is pretty intrinsic to chess unless you're planning to support rectangular boards or something.  Also, being a thunk emphasizes that it's being called for its side effect, and not it's value.  You could really bring home that point by calling the function setup! instead.

I would give more descriptive names to your identifiers.  I would create a function that put a list of pieces together with their coordinates, called make-row, and a function that setup both the pieces and pawns given the rows to place them on, called setup-color

With regard to your concern about optimizing: readability and extensibility are usually more important than a few instructions.  There are exceptions, and those exceptions will kill performance if you don't optimize when they occur.  There are no rules about where performance bottlenecks lie, except for they are usually not where you think they are ;-).  That's why it is important to MEASURE your performance as you go.  The bottlenecks of most chess engines are usually NOT in the method used to setup the board.  They are usually in the search methods, so when you get there, time spent optimizing will yield a much better ROI.

Also, when you go to optimize, before starting down the path of flipping your program inside -out to CPS it, consider easier wins first, like using a vector instead of a list as your primary data structure.

As for shadowing symbols, it seems you may have a misunderstanding.  Shadowing doesn't buy you anything in performance.  It's not the identifier that takes up space, it's whatever that identifier is bound to.  When you shadow a variable, the old value still has to be stored for when it is unshadowed later.

In fact, shadowing variables can actually be harmful to performance in some cases.  Since you can shadow primitive operations like +, the compiler is unable to safely inline those operations.  If you can tell the compiler that you promise not to shadow +, it can inline addition operations.  If your implementation has a decent module system, wrapping you code in modules may help the compiler make these deductions, otherwise there may be flags to encourage inlining.

Here is my suggested refactoring.

;; Alist: (cons 'piece xy-coordinates)
(define whites '())
(define blacks '())

;;Set!s whites and blacks to the initial chessboard setup
(define (setup!)
  (define (make-row pieces row)
    (map (lambda (piece x) (list* piece x row))
     pieces
     (iota 8)))

  (define (setup-color pawn-row piece-row)
    (let ((pawns '(p0 p1 p2 p3 p4 p5 p6 p7))
          (pieces '(r0 n0 b0 q k b1 n1 r1)))
      (append
       (make-row pawns pawn-row)
       (make-row pieces piece-row))))

  (set! whites (setup-color 1 0))
  (set! blacks (setup-color 6 7)))


Determine whether a checkbox is checked or unchecked

This is tighter I think:

function addParameter( url , name , value )
{
  var justHostname = ( location.href == ( location.protocol + "//" + location.host + "/" ),
      separator = justHostname?"?":"&"
  return url + separator + encodeURIComponent(name) + "=" + encodeURIComponent(value);
}

$('#mapControl').on('click', function(){
    var url = window.location.href,
        urlParamObj = $('#urlParam');
    if(this.checked)
    {
      url = addParameter( url , 'mapControl' , 'true' )
    } else {
      url = url.replace('?mapControl=true&','?')
               .replace('?mapControl=true','')
               .replace('&mapControl=true','');
    }
    urlParamObj.val(thisUrl);
});

I did not test this, but you should catch the drift.

If it were me though, I would not re-invent the wheel and use the code from the answer here :
https://stackoverflow.com/questions/6953944/how-to-add-parameters-to-a-url-that-already-contains-other-parameters-and-maybe