Calculating e^x by math.h and by own means

What's the point of the syntax: and Syntax: labels?
You don't use them, so remove them.
And if you must use two labels, make them less similar to each other.

When the condition in the while loop is true from the start,
consider rewriting it as a do { ... } while loop.

You don't need the a variable.
You can easily rewrite the program without it.

The coding style is very odd:

Excessive vertical spacing (many empty lines) at many places
Too compact: it's recommended to put spaces around operators

Other tips:

Instead of h=h+1 you can do ++h, as you did in the for loop
Instead of x = x * y you can use x *= y
Instead of x = x + y you can use x += y

With the above suggestions (and some more) applied, the code becomes slightly simpler:

#include <math.h>
#include <stdio.h>

main()
{
    int exponent, h;
    float math, iteraties, c, stdio, z, verschil;

    char stop = 'n';
    do
    {
        printf("vul exponent in:\t\t");
        scanf("%d", &exponent);
        math = exp(exponent);
        c = 1.0;
        h = 0;
        stdio = 1.0;
        for (iteraties = 1.0; ; iteraties++)
        {
            ++h;
            z = pow(exponent, h);

            c *= iteraties;
            stdio += z / c;
            verschil = math - stdio;
            if (verschil < 0.01)
            {
                iteraties++;
                break;
            }
        }
        printf("\nexp (%d) uit math.h is:\t\t%f",exponent, math);
        printf("\nexp (%d) m.b.v. de reeks is:\t%f",exponent,stdio);
        printf("\nhet verschil is: \t\t%f", verschil);
        printf("\naantal iteraties is:\t\t%.f", iteraties);

        printf("\n\nstoppen n/j\t\t\t");
        getchar();
        scanf("%c", &stop);
    } while (stop != 'j');
}


"The Genuine Sieve of Eratosthenes" in C++14

At least to me, this seems a little like another instance of the same basic problem pointed out in linked paper: although there are a few parts that I guess are sort of neat, overall it strikes me as a huge amount of code to solve a trivial problem, and (at least based on the numbers you're posting) apparently runs really slowly.

It doesn't attempt to make much in the way of style points, but lets consider sort of a reference implementation--roughly the simplest thing that works to some degree:

#include <vector>
#include <iostream>
#include <locale>

unsigned long primes = 0;

int main() {
    int number = 20'000'000;
    std::vector<bool> sieve(number,false);
    sieve[0] = sieve[1] = true;

    for(int i = 2; i<number; i++) {
        if(!sieve[i]) {
            ++primes;
            for (int temp = 2*i; temp<number; temp += i)
                sieve[temp] = true;
        }
    }
    std::cout.imbue(std::locale(""));
    std::cout << "found: " << primes << " Primes\n";
    return 0;
}

On my notebook (4 or 5 years old, and wasn't tremendously fast when it was new) this finds 1,270,607 primes in 147 milliseconds (so in round numbers, it's running something like 75 or 80 times as fast as the code in the question). Even compared to @Toby's optimized version, it's still something like 20 times faster.

Don't get me wrong: I'm all for using nice algorithms and making code generic where it's reasonable--and I'm pretty sure there are ways to do that in this case without paying much of a penalty. But, at least to me, it seems to me as if the code you presented is paying a pretty high penalty--and given its much greater length and overall complexity, I'm not convinced we're getting any real improvement in return for that speed penalty either.

I'd re-emphasize that this is not really optimized code, or anything like that either--we can do quite a bit better by taking the square root into account, using a segmented sieve, and switching to something like a sieve of Atkins, and using a more specialized bit vector instead of std::vector<bool>. If we did those, we could probably expect to improve speed by around another order of magnitude (and depending on the number of primes we decided to find, maybe even more than that).


I'm assuming the indenting is cut and paste problems, but going through this:

#include <iostream>

You don't use iostream, so don't include it

#include <string>
#include <algorithm>
#include <vector>
#include <functional>

I'd recommend you sorted the #includes. It makes it a lot easier to find things if you have a lot of them and avoids a certain class of problem with merging file changes

//at least two digits must be distinct
bool isUnique(int num)

Given the comment, isUnique is not a good name. It's looking for 2 distinct digits, not - well, it's not looking for anything unique. contains_2_distinct_digits perhaps?

{
    constexpr int numlength = 4;
    std::vector<int> digits;

    for(int i = 0; i < numlength ; ++i)

for is not a function call. It's a keyword. Put a space after it.

    {
        int digit = num%10;
        digits.push_back(digit);
        num /= 10;
    }

The 4 doesn't really belong here (see below).

    //If digits are all equal return false.
    if ( std::adjacent_find( digits.begin(), digits.end(), std::not_equal_to<int>() ) == digits.end() )

I wouldn't have the space after the ( there.

This code is somewhat inconsistent with the use of spaces. You have a space after commas and brackets here, but not further down. Pick a style and stick to it.

    {
        return false;
    }else

I'd recommend against dangling the else off the }. Either put it on its own line or use '} else {'

    {
        return true;
    }

You don't really need that if. Just

    return std::adjacent_find(digits.begin(), digits.end(), std::not_equal_to<int>()) != digits.end();

}

int KaprekarsConstant(int num)

TBH I'd expect a name like that to return the constant (actually I wouldn't expect with that name it'd even be a function). This isn't returning that. It's returning how many iterations it takes to stabilise.

{
    constexpr int kaprekarsConst = 6174;
    constexpr int lengthRequirement = 4;

You have this 4 here and you use 4 for the passing in isUnique. This is fragile, should you ever want to deal with a similar property for numbers with digits other than 4.

    static int iteration = 0;

There's no need for this to be static

    if(std::to_string(num).length() == lengthRequirement && isUnique(num))

if is not a function call

    {
        int difference = num;
        std::string sNum;

sNum only needs to exist in the while loop, so put it there. You should attempt to declare variables at the point of use where possible.

            while(difference != kaprekarsConst)

while is not a function call. Put a space after it.

If you wanted to generalise this to n digits, I wouldn't define kaprekarsConst. You'd just check if the newly evaluated difference matched the previous difference.

            {
                sNum = std::to_string(difference);

                std::sort(sNum.begin(),sNum.end(),std::greater<int>());
                int ascendNum = stoi(sNum);

                std::sort(sNum.begin(),sNum.end(),std::less<int>());
                int descendNum = stoi(sNum);

As has been suggested, this is already sorted, so you could just reverse it.

                difference = ascendNum - descendNum;

                ++iteration;
            }
    }
    return iteration;
}


This should suffice

fun_2 <- function(x) sapply(x, function(y) sum(x < y))
fun_2(Value)
# [1]  0 11  8  5  0  0 12  0  0 10  7  6  8

P.S. sapply/lapply are the same loops, just masked and a little bit faster.

Or if your data is very large we can do it a lot faster using data.table, aggregating the data and counting:

require(data.table)
fun_3 <- function(Value) {
  d <- data.table(x = Value) # creates 1 column data.table
  # setkey(d, x) # not needed here keyby sets the key
  d <- d[, .N, keyby = x] # calculate count of each unique x value
  # and sorts the results
  d[, a := c(0, cumsum(N)[-.N])] # calculate lagged cumsum from N (counts)
  # a represents element count that is smaller than x
  d[.(Value), a] # using datatable-keys-fast-subset get a(result) for each Value
}

set.seed(42)
Value2 <- sample.int(1e5)

system.time(r2 <- fun_2(Value2)) # 36.64
system.time(r3 <- fun_3(Value2)) # 0.03
all.equal(r2, r3)
# [1] TRUE

OR with base R:

fun_4 <- function(x) {
  xorder <- order(x)
  xsorted <- x[xorder]
  xsdifs <- c(0, diff(xsorted))
  m <- seq_along(xsdifs) - 1L
  m[xsdifs == 0L] <- 0L
  m <- cummax(m)
  m[order(xorder)]
}

For reverse (Value > x):

fun_2r <- function(x) sapply(x, function(y) sum(x > y))
fun_3r <- function(Value) {
  d <- data.table(x = Value)
  d <- d[, .N, keyby = x]
  setorder(d, -x)
  d[, a := c(0, cumsum(N)[-.N])]
  setkey(d, x) # need to reset key for sub setting,
  # because reordering d removes it
  d[.(Value), a]
}


Is this the proper way to find the subclass of a polymorphic superclass?

You have to learn a lot about OOP... There is no polymorphism in your code, as this principle is designed to tackle exactly the kind of code you've written.

The code that uses Asset should never branch its logic based on actual derived type (otherwise it would brake Open-Closed Principle), instead classes should use polymorphism to specify differences in logic. Here is simple example based on your code:

public abstract class Asset
{
    public string Name {get; set;}
    public abstract decimal CalculateValue();
    //... other common properties and methods of Asset
}

public class Property : Asset
{
    public decimal Value {get;set;}

    public override decimal CalculateValue()
    {
        return Value;
    }
}

//usage
public static void PrintAsset(Asset theAsset)
{
    Console.WriteLine(theAsset.Name);
    Console.WriteLine(theAsset.GetType().ToString());

    string assetValue = theAsset.CalculateValue().ToString();
    Console.WriteLine(assetValue + "\n");
}


is the use of ref correct here?

Taken from MSDN: ref (C# Reference)

  The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refer to the new object.

The point of ref is to pass a value type (struct) to a method as if it was reference type (class). List<T> is a class, so there's no need to add refin this scenario as it's just acting as another level of redirection. Think of it as being a pointer to a pointer.

The problem with using List<List<T> is that the size of the nested lists could differ from the top-level list and this wouldn't be a matrix. I'd recommend that you use something with a guaranteed rectangular structure, such as T[,]. i.e:

public static void MatrixTranspose<T>(ref T[,] matrix)
{
    int columns = matrix.GetLength(0);
    int rows = matrix.GetLength(1);
    T[,] transposed = new T[rows, columns];
    for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns; column++)
        {
            transposed[row, column] = matrix[column, row];
        }
    }

    // Reassign matrix so that it gets picked up by ref.
    matrix = transposed;
}


Providing one-time calculations to frequently used methods

Ok, so after some (more!) search on the net, I will propose one thing that I was already pondering about (having a little experience mostly with OOP languages Java and C#).
creating a class/datastructure to hold the values
I was inspired by these sources:

answer to this question
answer nr 2 to this question
and this webmonkey explanation

still not sure if this is a "better" approach in JavaScript, but at least for my rather inexperienced eyes it looks more structured
the refactored version of my pulsating object is here
the slightly changed javascript (find the class ElementWrapper at the end):

$(document).ready(function () {
    var element = $('#circle');
    var growInPercent = 100;
    var elementWrapper = new ElementWrapper(element, growInPercent);

    var durationGetBigger = 500;
    var durationGetSmaller = 100;
    var frequency = 3;
    var pause = 3000;
    pulsate(elementWrapper, durationGetBigger, durationGetSmaller,
    frequency, pause);
});

function pulsate(elementWrapper, durationBigger, durationSmaller, frequency, pause) {
    for (var i = 0; i < frequency; i++) {
        getBigger(elementWrapper, durationBigger);
        getSmaller(elementWrapper, durationSmaller);
    }
    setTimeout(function () {
        pulsate(elementWrapper, durationBigger, durationSmaller, frequency, pause)
    }, pause);
}

function getBigger(elementWrapper, duration) {
    elementWrapper.element.animate({
        width: elementWrapper.increasedWidth,
        height: elementWrapper.increasedHeight,
        top: elementWrapper.newTop,
        left: elementWrapper.newLeft,
        opacity: 1
    }, duration, 'linear');
}

function getSmaller(elementWrapper, duration) {
    elementWrapper.element.animate({
        width: elementWrapper.originalWidth,
        height: elementWrapper.originalHeight,
        top: 0,
        left: 0,
        opacity: 0.5
    }, duration, 'linear');
}

function ElementWrapper(element, percent) {
    this.element = element;
    this.originalHeight = element.height();
    this.originalWidth = element.width();
    this.increasedHeight = getIncreasedValue(this.originalHeight, percent);
    this.increasedWidth = getIncreasedValue(this.originalWidth, percent);
    this.newLeft = -Math.round((this.increasedWidth - this.originalWidth) / 2);
    this.newTop = -Math.round((this.increasedHeight - this.originalHeight) / 2);

    function getIncreasedValue(originalValue, percent) {
        var increase = Math.round(originalValue * (1 + percent / 100));
        if (originalValue % 2 > 0) { // odd
            // make sure increased size is odd too
            return Math.floor(increase / 2) * 2 + 1;
        }
        else {
            return Math.floor(increase / 2) * 2;
        }
    }
}


Return error messages for sending emails

By switching the if condition to check if $cardStatus is false and the same for $sendUserEmail you will reduce some of the nesting.

if (!$cardStatus) {
    return $this->cardApiError;
}

$cardEmailContent = $this->setCardEmailContent();
$sendUserEmail    = $this->sendCardToUser($cardEmailContent);

if (!$sendUserEmail) {
    return $sendUserEmail;
}

$this->sendAdminEmail();
$this->updateCardDetails();

by using these guard clauses it avoids the upcoming arrow antipattern.


I don't know what _getline is; perhaps it's something like the file-input function described here.

This looks strange ...

int nlines;

nlines = 0;

I think that C now (like C++) allows you to delay defining a local variable until you initialize it. So there's no need to declare your variables at the top of the function.

Passing MAXLEN is probably wrong: because if (MAX_LEN > storage_size) then you give _getline the opportunity to write past the end of the buffer.

Allowing a buffer overrun is a bug.

Instead you could do something like:

int n_lines = 0;

for (;;)
{
    // define local buffer inside function
    char buffer[MAX_LEN];
    int line_length = _getline(buffer, MAXLEN);
    if (line_length == 0)
        break;
    if (n_lines >= maxlines)
        return -1;
    if (line_length > storage_size)
        return -1;
    buffer[line_length - 1] = '\0';
    // copy local buffer to passed-in buffer
    strcpy(storage, buffer);
    lineptr[n_lines] = storage;
    storage += line_length;
    storage_size -= line_length;
    ++n_lines;
}

return n_lines;

Or you can read directly into the passed-in buffer, to avoid strcpy and avoid defining MAXLEN:

int line_length = _getline(buffer, storage_size);
if (line_length == storage_size)
{
    // fail unless there's nothing more to read
    char temp[1];
    if (0 != _getline(temp, 1))
        return -1;
}

I'm not sure what this statement does ...

storage[len - 1] = '\0';

... if the end-of-line marker is a two-character "\r\n" sequence (which it is on Windows).

You could possibly edit your variable names; if you're going to use_underscores as you did for storage_size, then perhaps:

maxlines -> max_lines
len -> line_length
lineptr -> lines or lines_array
nlines -> num_lines or line_number or line_counter

The least obvious variable name was len.


Is this a proper way of "loading" views in PHP?

I agree that its a better pattern to wrap your view logic in a class.

Here is some code I whipped together tonight - It represents the simplest class I could devise that contains the minimum logic that I require in a view:

Includes - Ability to include other views
Captures - Ability to easily capture content within your view
Layouts - Ability to inject data into a re-usable layout template
Fetching - Ability to fetch view output instead of sending it to output buffer
data - Ability to access the resulting data once the view is finished

[edit] Refactored per conversation in comments regarding passing $data by reference.

View.php

<?php
/**
 * Simple view class that supports includes, capturing, and layouts, as well
 * as retrieving rendered view content and resulting data.
 *
 * *NOTE* When a view uses a layout, the output of the view is ignored, as
 *        as the view is expected to use capture() to send data to the layout.
 *
 * @author David Farrell <DavidPFarrell@gmail.com>
 */
class View implements ArrayAccess
{
    /**
     * View file to include
     * @var string
     */
    private $file;

    /**
     * View data
     * @var array
     */
    private $data;

    /**
     * Layout to include (optional)
     * @var string
     */
    private $layout;

    /**
     * Constructor
     *
     * @param string $file file to include
     */
    public function __construct($file)
    {
        $this->file = $file;
    }

    /**
     * render Renders the view using the given data
     *
     * @param array $data
     * @return void
     */
    public function render($data)
    {
        $this->data = $data;
        $this->layout = null;

        ob_start();

        include ($this->file);

        // If we did not set a layout
        if (null === $this->layout)
        {
            // flush view output
            ob_end_flush();
        }
        // We set a layout
        else
        {
            // Ignore view output
            ob_end_clean();

            // Include the layout
            $this->include_file($this->layout);
        }
    }

    /**
     * fetch Fetches the view result intead of sending it to the output buffer
     *
     * @param array $data
     * @return string The rendered view content
     */
    public function fetch($data)
    {
        ob_start();
        $this->render($data);
        return ob_get_clean();
    }

    /**
     * get_data Returns the view data
     *
     * @return array
     */
    public function get_data()
    {
        return $this->data;
    }

    /**
     * include_file Used by view to include sub-views
     *
     * @param string $file
     * @return void
     */
    protected function include_file($file)
    {
        $v = new View($file);
        $v->render($this->data);
        $this->data = $v->get_data();
    }

    /**
     * set_layout Used by view to indicate the use of a layout.
     *
     * If a layout is selected, the normal output of the view wil be
     * discarded.  The only way to send data to the layout is via
     * capture()
     *
     * @param string $file
     * @return void
     */
    protected function set_layout($file)
    {
        $this->layout = $file;
    }

    /**
     * capture Used by view to capture output.
     *
     * When a view is using a layout (via set_layout()), the only way to pass
     * data to the layout is via capture(), but the view can use capture()
     * to capture text any time, for any reason, even if the view is not using
     * a layout
     *
     * @return void
     */
    protected function capture()
    {
        ob_start();
    }

    /**
     * end_capture Used by view to signal end of a capture().
     *
     * The content of the capture is stored under $name
     *
     * @param string $name
     * @return void
     */
    protected function end_capture($name)
    {
        $this->data[$name] = ob_get_clean();
    }

    /* ArrayAccess methods */
    public function offsetExists($offset)      { return isset($this->data[$offset]); }
    public function offsetGet($offset)         { return $this->data[$offset]; }
    public function offsetSet($offset, $value) { $this->data[$offset] = $value; }
    public function offsetUnset($offset)       { unset($this->data[$offset]); }

}

run.php

<?php
require "View.php";

$v = new View('view_main_simple.php');
$fetch = $v->fetch(array('message' => 'Hello, world'));
print("Fetch result: {$fetch}\n");

$v = new View('view_main_complex.php');
$v->render(array('one' => 1, 'two' => 2, 'rows' => array('a','b','c')));

$data = $v->get_data();

print("\n");
var_export($data);

view_main_simple.php

The message is: <?php echo $this['message'] ?>

view_main_complex.php

<?php $this->set_layout('view_layout.php') ?>
<?php $this->capture() ?>
    one=<?php echo $this['one'] ?>

    <?php $this->include_file('view_include.php') ?>
    three=<?php echo $this['three'] ?>

<?php $this->end_capture('body') ?>

view_include.php

two=<?php echo $this['two'] ?>

<?php $this['three'] = 3 ?>

    <?php foreach($this['rows'] as $row) { ?>

<?php echo $row ?>

    <?php } ?>

view_layout.php

<?php echo $this['body'] ?>

Program Output

Fetch result: The message is: Hello, world

    one=1

    two=2

a

b

c

    three=3

array (
  'one' => 1,
  'two' => 2,
  'rows' =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
  'three' => 3,
  'body' => '   one=1

    two=2

a

b

c

    three=3

',
)


Simple administrator authentication page in PHP

You should not store your password in plaintext, as this means that read access (eg via LFI) automatically leads to more (probably some sort of write access via the admin backend). Use bcrypt for this (this also solves the next point automatically).

Ideally, you should also use some sort of timing safe string comparison.

Ideally, I would move the user credentials into an extra config file, which can be placed outside the web root (in case the connection breaks up while a user edits the file, which may lead to a backup file like login.php~ or similar being created, which may be severed by a webserver).

  I plan on adding things like halting the script for a few seconds depending on how many attempts were made from the current session.

I guess that is one solution, but I would just deny attempts completely for x seconds if y attempts where made from that IP in the last z seconds.

Misc

You are overdoing it a bit with comments, which leads people to ignore your comments. Comments should not rephrase what the code already told us, but add additional information in case the code is unclear (Username => Password and possibly Expiration time in seconds/Array of authenticated users are the only comments I would actually keep).


Skip invalid record and avoid execution break for invalid record

Simplify logic to eliminate next

To improve readability by eliminating next, rearrange your record validity test, so lines 4 to 9 become

if participant_account.present? || utility_program.present?
  sub = Subscription.where(account_id: account.id, program_id: program.id)
else
  # this is just a logger method defined in the second file.
  failure_msg('participant account is #{account.inspect} & utility program is #{program.inspect}')
end

I am not sure this is what you mean. Ask yourself if you really need only one of participant_account or utility_program for the subscription query to succeed.

Don't do things many times that could be done once

To save some time, put line two before the iteration, because value of account does not depend on data. This also helps readability and debugging, as when programmers read the body of an iteration, they  expect only to see lines that need to be evaluated many times.

Only make queries if you need the result

To save a little more time and memory, only calculate the value of program if you know you are going to use it. So put it inside the conditional:

if participant_account.present? && utility_program.present?
  program = Program.where(program_identifier: data[:id]).first
  sub = Subscription.where(account_id: account.id, program_id: program.id)
else # ...

Extract methods

After these changes the conditional is starting to get a bit complicated, so extract some methods, for example:

if participant_account.present? && utility_program.present?
  sub = subscription(account, first_program(data))
else # ...

def subscription(account, program)
  Subscription.where(account_id: account.id, program_id: program.id)
end

def first_program(data)
  Program.where(program_identifier: data[:id]).first
end

Put query logic in models

I don't know if Program is an ActiveRecord model. If it is, then #first_program could be a class method in that model

Don't use #first unless you guarantee the order

For example, if you have ActiveRecord timestamps, you could use

Program.where(program_identifier: data[:id]).order(:created_at).first

Are validation and failure handling cross-cutting concerns?

You might also want to consider patterns that factor out your validation and failure handling code, but whether and how to use them depends on the larger structure of your program. For example, you could yield to your validations and sub = ... line as lambdas from a validate_with_logging method.


A get_extents helper function for Boost.MultiArray in C++

Avoid unnecessary temporary variables
There still is no need for the temporary vector shape_list, just use std::copy_n:
boost::detail::multi_array::extent_gen<NumDims> output;
std::copy_n(input.shape(), NumDims, output.ranges_.begin());

Please take some time to look at the list of all the STL algorithms. There are lots of useful functions there that will save you a lot of time. You don't have to remember them all, but get a feel for the type of functionality it provides, and next time you have a problem you might remember that some existing algorithm might solve it for you. The World Map of C++ STL Algorithms is also a great resource to build intuition for it.


n.is_a? Prime

Doesn't work. I don't know enough Ruby to tell you why, but it doesn't. Use Prime.prime? instead.

Further, (d + n) / d is not the right calculation. You want d + n/d.

You can simplify

return (1..self).collect { |n| n if ((self/n) * n) == self }.compact

to

(1..self).select { |n| self / n * n == self }

which is even simpler as

(1..self).select { |n| (self % n).zero? }

One can do even better by making this lazy:

(1..self).lazy.select { |n| (self % n).zero? }

Then one can precompute the primes for later:

primes = Array.new(max+1) { |i| false }
Prime.each do |n|
    break if n > max
    primes[n] = true
end

1.upto(max) do |n|
    factors = n.factors
    counter += n if factors.all? { |d| primes[d + n/d] }
end

One can also note that only numbers one below primes actually need to be checked, since 1 is a factor of every number. This simplifies things:

primes = Array.new(max+1) { |i| false }
Prime.each do |prime|
    break if prime > max
    primes[prime] = true

    n = prime - 1
    factors = n.factors
    counter += n if factors.all? { |d| primes[d + n/d] }
end

One also only need the first square root of factors, since larger numbers are paired with the smaller numbers anyway:

(1..Math.sqrt(self) + 1).lazy.select { |n| (self % n).zero? }

This now takes about 100 seconds for n = 100_000_000.


Bug

Your second functional solution does not run. You forgot to add the second argument to A.reduce. I will assume you wanted an array as the last argument.

Why functional sucks

This example clearly illustrates the problem with some functional solutions that involve data manipulation. The requirement of no side effects forces the solution to copy the whole dataset even when you manipulate only a single item. This is particularly noticeable in your second functional solution. See performance results below.

Code and Style

Some minor points...

function () {};  the trailing semicolon is not needed.
Swap the conditions.

You have if(a % 2 === 0) { /*even*/ } else { /*odd*/ } ...

can be if(a % 2) { /*odd*/ } else { /*even*/ }
Compact code. Try to avoid sprawling code. It may not matter for small segments of code, but source code can very long and reading code there spans pages is not as easy as having it all in one view.
Before a newline it is either } or ;. There are two exceptions. The } that closes an object literal should have a closing ; eg const a = {};. And multi line statements and expressions.

Know the language.

You do a lot of code examples, many of them are rather trivial. Of late many of your posts contain bugs or incomplete code (may be a sign of boredom? or a lack of challenge (engagement)) . I do not believe in the classical closed book assessment examination, it does not reflect the real world. However a good memory of the field makes you a more productive coder.

There are many subtle tricks in JavaScript that can catch you out if unaware. Testing your knowledge improves your understanding of the language making you a better coder.

This is a example JavaScript Web Development Quiz picked at random from a web search "javascript quiz"

It is good practice to do one of these every now and then.

I did not get 100%

Example A

Compacting the function.

function sortByParity(arr) {
    const odd = [], even = [];
    for (const val of arr) {
        if (val % 2) { odd.push(val) }
        else { even.push(val) }
    }
    return [...even, ...odd];
}

Performance

The second functional example was so slow I had to push the other best time down to the timer resolution cutoff 0.2ms or it would have taken forever to complete the test.

The functions as tested

function sortByParity_I1(A) {
    const odd = [], even = [];
    for (const a of A) {
        if (a % 2 === 0) { even.push(a) }
        else { odd.push(a) }
    }
    return [...even, ...odd];
}
const sortByParity_F2 = A => A.reduce((acc, x) => x % 2 === 0 ? [x, ...acc] : [...acc, x], []);
const sortByParity_F1 = A => A.reduce((acc, x) => {
        if (x % 2 === 0) { acc.unshift(x) }
        else { acc.push(x) }
        return acc;
    }, []);

Benchmarks

Mean time per call to the function in 1/1,000,000 second. OPS is operations per second. % is relative performance of best.

For array of 1000 random integers

sortByParity_I1:    20.709µs OPS  48,287 100%
sortByParity_F1:   133.933µs OPS   7,466  15%
sortByParity_F2: 3,514.830µs OPS     284   1%

For array of 100 random integers

sortByParity_I1:     2.049µs OPS 488,148 100%
sortByParity_F1:    10.005µs OPS  99,947  20%
sortByParity_F2:    46.679µs OPS  21,422   4%

Note that the results for the functional solution do not have a linear relationship with the size of the array.

Improving performance

I will drop the  slow functional and add an improved imperative function that pre allocates the result array. This avoids the overhead of allocation when you grow the arrays. As there is one array the overhead of joining the two arrays is avoided as well. This almost doubles the performance.

function sortByParity_I2(A) {
    const res = new Array(A.length);
    var top = res.length - 1, bot = 0;
    for (const a of A) { res[a % 2 ? top-- : bot ++] = a }
    return res;
}

10000 items
sortByParity_I2:   119.851µs OPS     8,343 100%
sortByParity_I1:   223.468µs OPS     4,474  54%
sortByParity_F1: 5,092.816µs OPS       196   2%

1000 items
sortByParity_I2:    13.094µs OPS    76,372 100%
sortByParity_I1:    23.731µs OPS    42,138  55%
sortByParity_F1:   123.381µs OPS     8,104  11%

100 items
sortByParity_I2:     0.900µs OPS 1,110,691 100%
sortByParity_I1:     2.245µs OPS   445,398  40%
sortByParity_F1:     9.520µs OPS   105,039   9%

Test on Win10 Chrome 73 CPU i7 1.5Ghz


Project Euler 92: count sum-squared-digits chains that reach 89

I guess the idea behind using permutations is that any permutation of the same digits will result in the same squared sum. However... in that case, shouldn't we simply calculate the squared sum and cache that?
It appears that we're only caching the permutations of the digits at the end of the chain. i.e. we'll only ever end up with 1, 89 and 98 in the map! We should probably be caching all the values in the chain up to the final result.
#include <string> for std::to_string.
Converting to and from std::string is probably quite slow. We can use simple integer arithmetic to extract the individual digits.
The implementation of sumOfDigitsSquared is clearly incorrect with basic testing.


The code mutates an array. It is not good.
The code does too much. You may return false as soon as max_changes reaches 2 (no need to examine the rest).
More functions please. It is very hard to follow the complicated decision making. Consider
int find_first_violation(int * nums, int size)
{
    int i = 0;
    for (; i < size; i++) {
        if (nums[i] < nums[i-1]) {
            break;
        }
    }
    return i;
}

Then the business logic would be:
    int violation = find_first_violation(nums, size);

    if (violation == size) {
        // array is already non-decreasing
        return true;
    }
    if (violation == size - 1) {
        // easily fixable: increase nums[size - 1]
        return true;
    }

    // Now fix the violation
    // violation == 1 is fixable by decreasing nums[0]. No action needed.
    // Otherwise, we only care about the case where nums[violation] is too
    // small - less than two preceding numbers. It is only fixable by
    // increasing it, effectively setting it equal to nums[violation - 1].

    if ((violation > 1) && (nums[violation] < nums[violation - 2])) {
        nums[violation] = nums[violation - 1];
    }

    // Finally, the core argument to have more functions: there
    // must be no more violations.

    return find_first_violation(nums + violation, size - violation) == size - violation;

Of course the first two conditions can be combined into violation >= size - 1. Of course increasing of nums[violation] can be virtual, without mutating the array (if nums[violation - 1] > nums[violation + 1] we may immediately return false;).


The only thing that pops out to me (though admittedly, it is very minor) is that you're recompiling the regex every time you call ToDeclarations.

You could use a static Regex instance which compiles the expression only once. Regex instances are also threadsafe - so no worries there.

Thus, your code could look like:

private static Regex _cssRegex = new Regex("(?<property>[a-z-]+):\s*(?<value>.+?)(;|$)", RegexOptions.IgnoreCase);
public static IEnumerable<(string property, string value)> ToDeclarations(this string style)
{
    return
        _cssRegex
            .Matches(style)
            .Cast<Match>()
            .Select(m => (
                property: m.Value("property").Trim(),
                value: m.Value("value").Trim())
            );
}


Refactor selective item by highest create date or update date

You could try and make LINQ do more, to me it is more readable but it may not be to your style.

var allCostsInThisPo = CostRepository
                       .GetAll()
                       .WhereInPo(po.po_surr_key);

if (allCostsInThisPo.Any())
{
    var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item => item.create_date)
                                                        .Select(c => new { Name = c.CreatedByUser.user_fullname, Date = c.create_date})
                                                        .First();

    // if there is a max edited date greated than the cost created date then this will
    // be populated, otherwise will be null.
    var costWithMaxEditedDate = allCostsInThisPo.Where(item => item.update_date.HasValue && item.update_date.Value > costWithMaxCreatedDate.Date)
                                                          .OrderByDescending(c => item.update_date.Value)
                                                          .Select(c => new { Name = c.EditedByUser.user_fullname, Date = c.update_date.Value})
                                                          .FirstOrDefault();

    var maxCost = costWithMaxEditedDate ?? costWithMaxCreatedDate;

    history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(maxCost.Name, maxCost.Date);
}


A caveat & context: I'm writing this answer because I think it's an interesting question, however I'm drawing from CS lectures from 15 years ago and some hasty Googling, so rather than aiming for a correct answer, I'm hoping this will prompt some responses from smarter people.

flatten1:

First of all, an iteration of your original function. The only thing that stood out was that the ternary operation was a bit hard to read on a single line.

I don't like using white-space for formatting, but in this case I'd probably put each expression on it's own line:

(data is [Any])
  ? outputArray += flatten(input: data as! [Any])
  : outputArray.append(data)

But in this case I prefer to use avoid the short hand format, and use the longer conditional assignment, which I prefer because then you can avoid the forced cast to [Any]:

func flatten1(input: [Any]) -> [Any] {

    var flattened = [Any] ()

    for index in 0..<input.count {
        let element = input[index]

        if let array = element as? [Any] {
            flattened.append(contentsOf: flatten1(input: array))
        }
        else {
            flattened.append(element)
        }
    }

    return flattened
}

flatten2:

The second iteration was that I moved the loop into the recursion. As far as I know (and it is likely that I misunderstand this), compliers can't perform a tail call optimization unless you pass through an accumulator that collects up the value as the recursive calls are made (otherwise the runtime needs to increase memory to keep track of the incremental values, then perform some operation - in this case concatinating arrays, as it works itself back to the first recursive call).

func flatten2(input: [Any]) -> [Any] {

    guard let head = input.first else { return [] }

    if let headArray = head as? [Any] {
        return flatten2(input: headArray) + flatten2(input: Array(input.dropFirst()))
    }
    else {
        return [head] + flatten2(input: Array(input.dropFirst()))
    }
}

flatten3:

With that in mind, here's a third iteration using an accumulator:

func flatten3(input: [Any], accumulated: [Any] = []) -> [Any] {

    guard let head = input.first else { return accumulated }

    if let headArray = head as? [Any] {
        return
            flatten3(input: Array(input.dropFirst()),
                     accumulated: flatten3(input: headArray, accumulated: accumulated))
    }
    else {
        var _accumulated = accumulated
        _accumulated.append(head)

        return flatten3(input: Array(input.dropFirst()),
                        accumulated: _accumulated)
    }
}

Comparisons

I made an attempt at profiling these to compare performance with each other. I can into a bit of a stumbling block here when I tried to manually write in a deeply nested array where Xcode gave an Expression was too complex to be solved in reasonable time error. I ended up creating the nested array for testing like this:

var input: [Any] = []

override func setUp() {

    let test: [Any] = [1, [2], [3, [4]], [5, [6]], 7, [8], [[[[9, [10]]], [11, [12], 13]], 14, [15, [16]], [17, [18]], 19], 20, [21, 22], [23, 24, 25]]

    let level1 = [test, test, test, test, test]
    let level2 = [level1, level1, level1, level1]
    let level3 = [level2, level2, level2, level2]
    let level4 = [level3, level3, level3, level3]
    input = [level4, level4, level4, level4]
}

So now for testing (MBP late 2016, using -O3 flag for optimization):

flatten1    0.089s  6% STDEV
flatten2    0.599s  4% STDEV
flatten3    3.297s  3% STDEV
flatMap     0.000s  175% STDEV (actual time ranged 0.000016s to 0.000251s)

So flatten3 is actually a lot slower than the original loop approach, but with the benefit (if tail-call optimization is performed) of using a constant amount of memory.

But the standout is how fast flatMap performs. The post asks for ways to write the function more swifty, but unless you're planning the fucntion to have some sort of additional side effects as the intermediary steps are performed, then the simple input.flatmap{ $0 } is the best case on all fronts!

Edit: As @MartinR points out, flatMap only flattens the first level. I feel a bit silly for not actually checking the output. I've also realized that I don't understand flatMap as shown by this snippet...

print([[1, 2], [3, 4]].flatMap{ $0 })
// -> [1, 2, 3, 4] (expected output)

print([1, [2, 3, 4]].flatMap{ $0 })
// -> [1, [2, 3, 4]] (I didn't expect this!)

Here's a gist if anyone wants to use this as a starting point of their own -- like I started the post, it would be great to see someone more experienced chime in with thoughts or corrections :)


Hash table using open addressing with double hashing probing

Here are a few things I noticed reading your code:

You should probably use more descriptive identifiers for M and N here.
Instead of dynamic allocation you could also use std::vector<...> for table and mark. That would allow to simplify your code considerably. For example you could drop the custom copy/move constructors/assignment operators and the destructor and use the implicitly defined ones instead.
You could also use the provided .size() method of std::vector to get M instead of saving it explicitly.

If you didn't use std::vector for performance considerations, then I doubt that is a problem. Element access is through one indirection anyway and you do not have resize operations. Simply use reserve in your constructor to allocate the proper size immediately. Only the required memory for std::vector might be a bit larger (additional integer for current size/reserved size and doubling of length M).

Even if you still don't want to use std::vector, then you should consider writting an additional class (heap_array?) to handle the memory management or you could use std::unique_ptr, which would at least make your custom move constructor/assignment operator and the destructor redundant.
In hash_table(std::size_t m): The body is simply zero-initialization of the mark array. The same can be achieved with:

hash_table(std::size_t m)
    : M(power_of_2_ceiling(m)),
    table(new std::pair<K, V>[M]),
    mark(new bool[M]{}), N(0)
{ }

In hash_table(hash_table<K, V>&& map): Is there a reason to set M and N to zero? A moved object only needs to be properly destructable, but the destructor does not use M or N.
You can refer to the current instantiation of a template class without specifying the arguments, i.e. hash_table(hash_table&& map) would be fine for the move constructor, too.
To use std::unordered_map you need to include <unordered_map>.
hash_table(std::unordered_map<K, V>&& map): You have a rvalue reference constructor here, but none for const references. That seems inconsistent.
hash_table(std::unordered_map<K, V>&& map) initially does the same as hash_table(std::size_t), you could simply call it:

hash_table(std::unordered_map<K, V>&& map)
    : hash_table(map.size())
{
    for (auto &p : map) {
        insert(std::move(p));
    }
}

(dropped)
(dropped)
You could use just one array of type std::tuple<K,V,bool> (or a custom struct) instead of two arrays table and mark. Then you would not have to repeat the memory management code twice, and with the access pattern related data is closer in memory. Together with my point 2. this would reduce overhead even more.
Your only method to return elements find returns a const std::pair<K,V>*, implying that it is impossible to modify the value of an entry in-place. I think that is a rather strong limitation. Of course one may not change the key in-place, but the value should be modifiable. Therefore the type should be std::pair<const K,V>* and table also should be of type std::pair<const K,V>.
The maximal size of your hash_table is kind of arbitarily chosen and once it is full there will be an exception thrown. This might not have been the scope of your intentions but really the size should grow when a certain load is reached and rehashing should happen.
Your insert takes a rvalue reference. This means that only temporaries or moved elements can be inserted. There should also be an overload for const references (and without move).
size() should be const.


The first remark I'd like to make about your function is that the names of things are not very clear as to what it is supposed to do. Imagine presenting only the code to someone, who doesn't know what problem you are trying to solve. Do you think it would be very clear?

We can make it more general, so that it can be applied to other problems. Instead of candies and plastic bags, let's use units and containers. That way, we can also calculate practically any "number of \$x\$ in \$y\$..." problems that involve integers:

Number of boxes in delivery trucks
Number of passengers in train carts
Etc.

Since we are looking to get as many full containers as we can, and then the remainder in another container, let's name the function that way as well. Here is what it looks like so far, with just the names changed:

def get_full_containers_and_remainder(units, container_capacity)
  container_number = 1
  containers = []

  begin
    units_in_this_container = units / container_capacity > 0 ? container_capacity : units
    units -= units_in_this_container
    containers << [container_number, units_in_this_container]
    container_number += 1
  end while units > 0
  containers.to_h
end

get_full_containers_and_remainder(120, 50)
# {1=>50, 2=>50, 3=>20}

So far, so good. The logic is identical, but the function is easier to understand with more general names.

The logic can be simplified to not having to rely on manually adding units one container at a time in a loop. For such small numbers this is trivial, but if you had to divide up really big numbers this would take very long.

We can instead use a bit of simple math to calculate the remainder as well as the number of containers without a loop.

Using the modulo operator we can get the remainder:

remainder = units % container_capacity # remainder of 120 ÷ 50 = 20

Then we can calculate the number of full containers by subtracting the remainder from the total units, and then dividing by the container size.

count_full_containers = (units - remainder) / container_capacity # (120 - 20) ÷ 50 = 2

From there it's simply a matter of adding that many full containers, and then one more container with the remainder. Note that I added a check at the beginning to return an empty hash early if either of the values is zero, to avoid division-by-zero errors.

Working demo on repl.it

def get_full_containers_and_remainder(units, container_capacity)
  if units == 0 || container_capacity == 0
    return [].to_h
  end

  remainder = units % container_capacity
  count_full_containers = (units - remainder) / container_capacity
  container_number = 1
  containers = []

  begin
    containers << [container_number, container_capacity]
    container_number += 1
  end while container_number <= count_full_containers
  containers << [container_number, remainder]
  return containers.to_h
end

puts get_full_containers_and_remainder(120, 50) # {1=>50, 2=>50, 3=>20}
puts get_full_containers_and_remainder(0, 50)   # {}
puts get_full_containers_and_remainder(120, 0)  # {}


This problem statement is simply asking if the array is a symmetrical matrix, so lets explore making a function which checks that!

We want a function which checks an object for all the qualities of a symmetrical matrix. Because we like to reuse functions in future programs, we're gonna make this function robust.

It checks that the parameter is a 2d array of either tuples or lists, that the matrix is a square, and checks that element i,j is the same as element j,i.

def check_symmetrical(array2d):
    # Check that the array is a valid square matrix
    if not type(array2d) is list and not type(array2d) is tuple:
        return False
    for row in array2d:
        if (not type(row) is list) and (not type(row) is tuple):
            return False
        if not len(row) == len(array2d):
            return False
    # Check that the array is a valid symmetrical matrix
    for i in range(len(array2d)):
        for j in range(len(array2d)):
            if not array2d[i][j] == array2d[j][i]:
                return False
    # if no failures then it must be good!
    return True

Lets revisit your input code

numWords = int(raw_input('Enter Number of Words: '))

This line has the opportunity to crash our code. Never trust the user! Lets use the isdigit function to fix that up

num_words = raw_input('Enter Number of Words: ')
if not num_words.isdigit():
    print('Not a Valid Number')
    sys.exit()
num_words = int(num_words)

When a user input garbage, the program will close gracefully.

Now we need to turn that list of words into a 2d array. Lets use list comprehension

words = []
for i in range(num_words):
    word = raw_input('Enter Word: ')
    if len(word) != num_words:
        print('Not Valid Grid')
        sys.exit()
    words.append(word)
# comprehension used to create a list of lists
word_array2d = [list(word) for word in words]

Finally, run that array through our check_symmetrical function!

if check_symmetrical(word_array2d):
    print('Valid Grid')
else:
    print('Not a Valid Grid')


MySQL query to select number of fields occurring more times than x

Initially I was thinking of suggesting the HAVING clause, but I don't think that would help in this case, since the query selects the aggregated count and uses that for a comparison.

One option is to use a Common Table Expression (CTE) but apparently those aren't introduced until MySQL version 8. One other option is to make a View:

CREATE VIEW countEnglishWord as select word.body, count(*) as count
    from word
    join document on word.document_id = document.id
    where document.language = 'english'
    group by word.body;

and use it like this:

select count(*) + 1, body
from countEnglishWord c
where count > (select count
  from countEnglishWord t
  where body = 'the'
)

I haven't tested it on a million rows... but 3 in this sqlfiddle.


Simple object oriented design for an Temperature class

Make the base class meaningful

Right now you've declared Temperature as a base class, but all it really does is set up your two variables.  One way to utilize it more would be to assign a unit of some sort to the class (I've chosen Kelvin, but it could have been anything).

In my version, Temperature stores everything as Kelvin.  Any class that inherits from it only has to know how to convert back and forth to Kelvin (So Celsius<->Kelvin and Fahrenheit<->Kelvin).  Later, if I wanted to add operators to add/subtract/compare temperatures, since the base units are all kelvin, everything is easy.

You'll also notice that I've moved has_temp? to the base class and the threshold temperature is in Kelvin.  This gives all sub-classes the functionality without having to know anything about where the theshold is, and likewise the base class will always work without needing to know the details of a particular unit of measure.

Finally, while I've used Kelvin as the unit for Temperature, the base class could have just as easily been called Kelvin.

class Temperature
  attr_accessor :temp, :method

  FEVER_THRESHOLD = 310.15  # 98.6F to K

  def initialize(temp, method)
    @temp = temp
    @method =method
  end

  def to_s
    "#{@temp} K"
  end

  def has_fever?
    @temp > FEVER_THRESHOLD
  end
end

class Celsius < Temperature
  def self.to_k(value)
    value + 273.15
  end

  def self.from_k(value)
    value - 273.15
  end

  def initialize(temp, method)
    super(Celsius.to_k(temp), method)
  end

  def to_s
    "%0.2f C" % [Celsius.from_k(@temp)]
  end
end

class Fahrenheit < Temperature
  def self.to_k(value)
    (value + 459.67) * (5.0/9.0)
  end

  def self.from_k(value)
    (value * 9.0/5.0) - 459.67
  end

  def initialize(temp, method)
    super(Fahrenheit.to_k(temp), method)
  end

  def to_s
    "%0.2f F" % [Fahrenheit.from_k(@temp)]
  end
end

#test Celsius
temp = Celsius.new(39, nil)
puts temp.to_s         # 39.0 C
puts temp.has_fever?   # true

#test Fahrenheit
temp = Fahrenheit.new(97.9, nil)
puts temp.to_s         # 97.90 F
puts temp.has_fever?   # false

On a personal note, I wouldn't necessarily use inheritance as my go-to solution for this problem without a lot more knowledge and thought about the use-cases; I only followed your initial design.  Temperatures themselves are fairly trivial, but perhaps for a more complicated scenario this implementation would have advantages.


Finding subsets from specified array, avoiding duplicates

To avoid the duplicates, you need to make the decision whether that element is already part of the subset. To do so, you need to do search in the already considered elements for the subset.

The challenge is performing this search optimally. Available options are to use a BST to store the subset elements which can be summed to the target sum. The searching operation will be efficient (log2H H -height of tree). This operation needs to be performed for every element, so it's better to use a BST.

Another alternative is to sort the given input, which is at the cost of \$\mathcal{O}(n \log n)\$. Then we can easily check the duplicates in the subset as they are appearing consecutively.

Let's compare the above approach:

BST has two costs:

Construction of BST for each subset and balancing it
Cearching (log2H)

Sorting approach needs: \$\mathcal{O}(n \log n)\$

The winning answer is to maintain the HashSet of the subset and contains can be performed in \$\mathcal{O}(1)\$ constant time.


Rounding a time to its lowest quarter-hour

Java has integer division, so you can divide the minutes by 15 and multiply them again:

int mins = calendar.get(Calendar.MINUTE);
calendar.set(Calendar.MINUTE, mins / 15 * 15);

The division will round the number of 15-minute intervals down to the nearest integer, and multiplying it back gets you the interval you want.

To do this down to the milliseconds, do the same trick but with setTime() directly:

calendar.setTimeInMillis(calendar.getTimeInMillis() / 900000 * 900000);


Switching font and background color on button click

The repetition of getting a random font, color, background class cries to be extracted to a utility function:

function pickRandom(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

$("#try-me").click(function() {
    $("#content")
        .hide()
        .removeClass()
        .addClass(pickRandom(font))
        .addClass(pickRandom(color))
        .fadeIn(600);

    $("html")
        .removeClass()
        .addClass(pickRandom(background));
});

I also agree with @MainMa about defining background in terms of color.

Other than that, I think it's nice code!

Ensuring change

If you want to make sure that each font/color/background are different every time the user clicks on the button, then perhaps you can create another helper:

function pickRandomExcept(arr, previous) {
    while (true) {
        var pick = arr[Math.floor(Math.random() * arr.length)];
        if (pick != previous) {
            return pick;
        }
    }
}

However, in the caller you will need to keep track of the previous picks of each. For example:

var picked_color;

$("#try-me").click(function() {
    picked_color = pickRandomExcept(color, picked_color);
    $("#content")
        .hide()
        .removeClass()
        .addClass(pickRandom(font))
        .addClass(picked_color)
        .fadeIn(600);


Utilisation of multi-threading while reading a file and want to find the top 20 most frequently used words

Code Review

A lot of people like to put some logical order on the includes.

#include <iostream>
#include <iterator>
#include <set>
#include <vector>
#include <algorithm>
#include <map>
#include <mutex>
#include <fstream>

I like to put containers together, streams stuff together, C stuff together; others like to order them alphabetically. But with this many includes some sort of logic is probably a good idea.

You don't need to use this old library.

#include <pthread.h>

Threading is now part of the C++ standard. All the threading and mutex classes are included.

Not sure what these are:

#include "mingw-std-threads-master/mingw-std-threads-master/mingw.thread.h"
#include "mingw-std-threads-master/mingw-std-threads-master/mingw.mutex.h"

But that seems awfully deeply nested. Which usually means that there are are top level includes that include these files indirectly. A comment with a link to the documentation would be nice especially since a maintainer is not likely to know about these.

Hmmm

//bad practise but convenient for this code example
using namespace std;

C Macro

No need to use macros. There are better C++ alternatives.

//File to read so that we can find the most frequent used words.
#define FILENAME "mobydick.txt"

//The amount of words to find which are most used.
#define WORDS_TO_FIND 20

Notice we can type these correctly now.

// http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s
static std::string constexpr fileName    = "mobydick.txt"s;
static int constexpr         wordsToFind = 20;

Globals

Globals is a bad idea. These should be wrapped in a class object.

map<string,int> word_count;
queue<string> word_queue;
std::mutex m;                // inconsistent use of std::

//Not great approach but condition_variable is not available in my environment.
bool keep_running = true;

Locals

Love it.
Not enough people work out how to use the streams and locals correctly.

//Ignore punctuations coming from the stream, and to read only valid "english" letters from the input stream.
//This is an improvement but it still doesn't cover all cases.
struct letter_only: ctype<char>
{
    letter_only(): ctype<char>(get_table()) {}

    static ctype_base::mask const* get_table()
    {
        static vector<ctype_base::mask> rc(ctype<char>::table_size,ctype_base::space);

        fill(&rc['a'], &rc['z'+1], ctype_base::alpha);
        return &rc[0];
    }
};

Insert

Your lock is over too large a surface area. You lock the queue even while you are working on word_count and this is not used by the reader thread. The reader thread could be actively using the queue while you play with the word count object.

You should also look into using RAII to correctly lock and unlock your lock.

You read loop is a busy loop. You are going to melt the processor doing this. It would be better to use a condition variable and force the thread to sleep if the queue is empty (which it will be most of the time).

Lastly you overcomplicated the addition.

std::string getWord()
{
    std::lock_guard<std::mutex>  lock(m);   // Only lock as long as you need.
    std::word result = word_queue.front();
    word_queue.pop();
    return result;
}
void insert()
{
    string word;

    while(keep_running || (!keep_running && !word_queue.empty()))
    {
        // Add condition variable here.
        if(!word_queue.empty())
        {
            // Call getWord() that locks as part of the access
            // It is in a separate function so that the RAII lock
            // can simply unlock on exit.
            word = getWord();

            // If word does not exist. The [] operator inserts a value
            // using `word` as the key and zero-initializes the value
            // so for an int the value inserted is a zero.
            //
            // It returns a reference to the value, so you can simply
            // increment the result of the operation.
            ++word_count[word];
       }
    }
}

Optimization

This is very expensive.

    for(int i = 0; i < WORDS_TO_FIND; i++)
    {
        for(auto it = word_count.begin(); it != word_count.end(); ++it )
        {

You are basically looping over all the words 20 times. This list could be huge. There are 171,476 words in the english language (assume no spelling mistakes many more if you include these). You can replace this and loop over the words once and just keep track of the top 20.


The most obvious problem is when there are large number of strings, string concatenation is inherently slow. Try using a StringBuilder instead, like this:

 DataTable sqlData = GetConfiguration();

       // var q = sqlData.AsEnumerable().Where(data=> data.Field<String>("slideNo")=="5");

        var w = sqlData.AsEnumerable().Where(data => data.Field<String>("slideNo") == "5")
            .Select(data => data.Field<String>("QuestionStartText")).Distinct();

        List<String> queryResult = new List<String>();
        StringBuilder sb = new StringBuilder();
        foreach (var item in w.ToArray<string>())
        {
            if (item != null)
            {
                String queryString = item;
                //queryResult.Clear();
                for (int i = 0; i < excelDataTable.Columns.Count; i++)
                {
                    for (int k = 2; k < excelDataTable.Rows.Count; k++)
                    {
                       sb.Clear();
                       bool check = excelDataTable.Rows[k][0].ToString().StartsWith(queryString);
                       if (check)
                       {
                           for (int j = 0; j < excelDataTable.Columns.Count; j++)
                           {
                               sb.Append(excelDataTable.Rows[k][j].ToString());
                               sb.Append(':');
                           }
                           string row = sb.ToString();
                           if (!queryResult.Contains(row))
                           {
                               queryResult.Add(row);
                           }
                       }
                    }
                }
            }
        }


Gradient function that returns a list of all colors in order

I rarely do python nowadays, but cleanup of the conditions would be:
def add(c, gap):
    return min(255, c + gap)

def sub(c, gap):
    return max(0, c - gap)

def gradient(gap=1):
    r, g, b = 255, 0, 0

    if gap<=0:
        return (r, g, b)

    rbg_list = []
    while True:
        if  r == 255 and g < 255 and b == 0:         # 1
            g = add(g, gap)

        elif r > 0 and g == 255 and b == 0:          # 2
            r = sub(r, gap)

        elif r == 0 and g == 255 and b < 255:        # 3
            b = add(b, gap)

        elif r == 0 and g > 0 and b == 255:          # 4
            g = sub(g, gap)

        elif r < 255 and g == 0 and b == 255:        # 5
            r = add(r, gap)

        elif r == 255 and g == 0 and b > 0:          # 6
            b = sub(b, gap)

            if b == 0: break

        # print(r, g, b)
        rbg_list.append((r, g, b))
    return rbg_list

Now let me understand what happens. Let us on paper name the 3 states for a color component x (r, g or b):
    a = x == 0
    b = 0 < x < 255
    c = x == 255

    a :   == 0
    bc :  > 0
    c :   == 255
    ab :  < 255

    start: c a a

    c   ab  a    .+.  -->>  c c a
    bc  c   a    -..  -->>  a c a
    a   c   ab   ..+  -->>  a c c
    a   bc  c    .-.  -->>  a a c
    ab  a   c    +..  -->>  c a c
    c   a   bc   ..-  -->>  c a a

A very limited kind of gradient, restricted to one color component.
This  could be written as 6 loops:
        while g < 255:         # 1
            g += gap
            rbg_list.append((r, g, b))

        g = 255
        rbg_list.append((r, g, b))

        while r > 0:           # 2
            r -= gap

        r = 0
        rbg_list.append((r, g, b))

        ...

However you have just increasing from 0 by gap, and decreasing from 255 by gap.
These would give two component value arrays which can then be used with the two other components 0 or 255. That should be exploitable in Python.
You might also calculate how many gap steps are needed for 255, times 6, and have a function that gives for the ith step the (r, g, b). That would be the simplest.
I admit I might be mistaken in what gradient calculation you want to achieve.


You can DRY your JS code, assuming you modify the HTML this way:

On each of the four selector s, add a selector class and a data-id="N" attribute, where "N" refers to the #ElementN.
On each of the four selectable s, add a selectable class.

So your HTML part becomes:

Inserer un produit

Inserer un nv crédit

    Afficher les produits
    Afficher les crédits courants

<table id="Element1" class="selectable formInsertTab" ...

BTW, note that I affected data-value in the order showed by your demo (1, 4, 2, 3), while the code posted in your question is 1, 2, 3, 4.

Then in the JS part you can:

Take advantage of the above HTML changes to bind click event only once for all selectors.
Hide selectable elements without previously checking if they show.
Warning, anyway your test was falsy: $('#ElementN').show always returns true, since it checks if the show() method exists, not if the element is showing!
Add the improvement proposed by @Roamer-1888: chain fadeToggle() before hiding other elements.
BTW here is an interesting demo from him, which illustrates how you can have fine control on the fadeToggle() execution.

The resulting code is so much reduced:

$('.selector').click(function() {
  $element = $('#Element' + $(this).data('id')).fadeToggle('slow');
  $('.selectable').not($element).hide();
}


Abstract factory or inversion of control pattern?

IOC vs Abstract factory is kind of an apples to oranges question.  Abstract factory assumes you have a collection of related classes for which you don't want to know any of details involved in creating instances of those classes.  IOC doesn't necessarily abstract you away from the creation, it just sort of moves it to another area of your code base. In your particular scenario, one way to simplify that code might be like this

public class DocumentMappingSelector
{
    private Dictionary<Type, Type> mappingRoutes = new Dictionary<Type,Type>();

    public void AddRoute(DocumentMappingRoute route)
    {
         if (this.mappingRoutes.ContainsKey(route.SourceType))
         {
                // you could throw an exception or replace the route here, for this
                // example i'll just replace it
                if (this.mappingRoutes[route.SourceType] != route.MapperType)
                {
                    this.mappingRoutes[route.SourceType] = route;
                }
                else
                {
                     this.mappingRoutes.Add(route.SourceType, route);
                }
         }
    }

    public DocumentMappingRoute SelectMappingRoute(Type sourceType)
    {
        DocumentMappingRoute result = null;
        if (this.mappingRoutes.ContainsKey(sourceType))
        {
            result = this.mappingRoutes[sourceType];
        }
        return result;
    }
}

public class DocumentMappingRoute
{
    public DocumentMappingRoute(Type sourceTypeToBeMapped, Type mappingStrategyType, Action<object,UpdateStudentDocumentRequest> mappingProcessAction)
    {
         this.SourceType = sourceTypeToBeMapped;
         this.MapperType = mappingStrategyType;
         this.MappingProcess = mappingProcessAction;

    }
    Type SourceType { get; private set; }
    Type MapperType  { get; private set; }
    Action<object,UpdateStudentDocumentRequest> PerformMapping { get; private set; }
}
internal UpdateStudentDocumentRequest MapDocToUpdateDocumentRequest<T>(T doc)
{
    Type sourceType = typeof(T);
     UpdateStudentDocumentRequest updateStudentDocumentRequestInstance = new UpdateStudentDocumentRequest ();
    return selectorInstance.SelectMappingRoute(sourceType).MappingProcess(doc, updateStudentDocumentRequestInstance);  // you might not need the updateStudentDocumentRequestIsntance paramter here
}

For give any errors, I didn't type this in visual studio I just typed it in this editor.

Create and Add Document mapping routes to the selector
Get the mapping from the selector

Sorry this doesn't show the full code.  I ran short on time, but this should give you a general direction that will keep your code tight.  Let me know if you have any questions.


ES6 arrow function

Nice work utilizing functional programming (i.e. .map()) and the arrow function. One improvement here is that there isn't much of a need for a code block (i.e. { ....}) and return statement. So the callback to .map() in the render method can be reduced to a single line like below:

render() {
    return
 {
        this.state.comments.map((comment) =>
{comment.body}—{comment.author}
)
    }
;
}

jQuery - just for AJAX requests?

It appears that the only jQuery functionality used is its AJAX wrapper (i.e. $.ajax()). If that is all jQuery is used for, consider using a different technique like the fetch API (read this article for more info).

componentDidMount() {
    fetch(JSON_URL)
    .then(response => response.json())
    .then(data => this.setState({comments: data.comments}));

See this plunker for a demonstration.

Update

It has been mentioned that the fetch API has no support for aborting the request. If that is desired, there are other alternatives like Superagent (recommended by you might not need jQuery). See this updated plunker for an example of using superagent with its abort method in the componentWillUnmount method.


You made a typo. The line

responses ~ bernoulli_logit(theta);

should be outside the for loop in the model block.


Check the hardrive performance of the particular process using a Perl script

in general this script seems to be straight forward.

But here are some suggestions for improvements:

First check for needed command line arguments and die early with a usage message if they are missing/incomplete. Alternatively you could supply defaults for time interval and iterations like this

#stores the time interval
my $time_interval=$ARGV[0] || 10;
#stores the no of iteration
my $test_count=$ARGV[1] || 50;

You also might want to remove the hard coded process name (chrome) and use a third command line parameter

#stores the process name
my $processname=$ARGV[2] || 'chrome';

and

@processes=`iotop -b -n 1 |grep $processname`;

The result of calls to the write method of Spreadsheet::WriteExcel should be checked for success (=0) and failures should be shown somewhere (either on the console and/or in some log file).

The processing of iotop output could be enhanced.

Variables $read and $write are not needed.
Each line needs to be matched only once (while -> if and no need
for matching modifier g)

The regexs could be made more robust and written more readable.

I defined the regex for the throughput part once in a variable ($throughputpattern) and used it twice afterwards in the match. This is a general principle (don't repeat yourself) for better maintainablility.
the regex now uses the x modifier which allows whitespace in the pattern for better spacing and readability (but then you need to express whitespace to be matched explicitly with \s).
I changed the accepted units of B and K to any capital letter. Who knows what throughput might be possible?

   my $throughputpattern = qr{\b (\d+\.\d+) \s+ [A-Z]/s \s+}x;
   foreach(@processes)
   {
      if ($_ =~ /$throughputpattern $throughputpattern/x)
      {
         $read_per_second+=$1;
         $write_per_second+=$2;
      }
   }


IComparable implementation for a class representing a version

You could change it to reduce the "arrow style" like so

public int CompareTo(object obj)
{
   if(obj == null) { return 1; }

   var updateId = obj as UpdateId;
   if (updateId == null)
   {
       throw new ArgumentException("Object is not an UpdateId");
   }

   int compareResult = this.Year.CompareTo(updateId.Year);
   if (compareResult != 0) { return compareResult; }

   compareResult = this.ReleaseNumber.CompareTo(updateId.ReleaseNumber);
   if (compareResult != 0) { return compareResult; }

   return this.Revision.CompareTo(updateId.Revision);

}

which will save you some horizontal spacing and some not needed variables, because they all meant the same so I changed them to compareResult.


To extract specific information in the stack trace using regular expression

If you wish to include the hat ^ and dollar $ signs, then the regex can be rewritten as:

^.*\s+at widget\.List\.(\w+)\((\w+\.java)\:(\d+)\)$

Ofcourse, you can still use \d{3,4} instead of \d+ but that'll result in you missing the errors in line numbers less than 100(like 1 to 99).

Similarly, you can use \w+ in place of [a-zA-Z]+ or simply, [A-z]+ will work too.


You can get rid of the <type_traits> header by replacing your std::enable_if by a bool template specialization:

template <::std::size_t, ::std::size_t, bool>
struct expand_indices_impl;

template <::std::size_t A, ::std::size_t B>
struct expand_indices:
    expand_indices_impl<A, B, A==B>
{};

template <::std::size_t A, ::std::size_t B>
struct expand_indices_impl<A, B, true>
{
    using indices_type = indices<A>;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices_impl<A, B, false>
{
    static_assert(A < B, "A > B");
    using indices_type = typename catenate_indices<
        typename expand_indices<A, (A + B) / 2>::indices_type,
        typename expand_indices<(A + B) / 2 + 1, B>::indices_type
    >::indices_type;
};

Moreover, in C++ (and many other programming languages, see Python range for example), ranges tend to have the end-exclusive form [begin, end); therefore, make_indices_range<3, 9> should contain the indices from 3 to 8, and not from 3 to 9. It is easy to alter the behaviour:

template <::std::size_t A>
struct make_indices:
    detail::expand_indices<0, A-1>::indices_type
{};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range:
    detail::expand_indices<A, B-1>::indices_type
{};

As proposed in the comments, make_indices_range also needs to provide an empty range when A == B:

template <::std::size_t A>
struct make_indices_range<A, A>:
    indices<>
{};


float32_t   float64_t

Since the goal is:

  float32_t and float64_t is that those types are always their fixed size

the macros nearly achieve that.

  is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?

Big caveat: OP's expressed goal is same size, not same encoding.  Two systems may have a 32-bit float, yet different mantissa, exponent range and other properties.  The biggest "safety" concern is assuming same floating point properties with same size.

C allows for a great diversity of implementations though.  The macros accommodate most current compilers well, yet they are not specified to be always typedef 32/64 bit types.

To be clear, checking xxx_MANT_DIG, FLT_RADIX, xxx_MIN_EXP, ... is not sufficient, in general, even though it may be practically sufficient.

It fundamental comes down to:

  what should code do if it encounters a novel implementation?

I'd go with testing for the usual suspects and expand code when I encounter a true counter case.

#ifndef __float64_t_defined
  #if FLT_RADIX==2 && DBL_MANT_DIG==53 && DBL_MIN_EXP == -1021
    #define __float64_t_defined
    typedef double float64_t;
  #elif FLT_RADIX==2 && FLT_MANT_DIG==53 && FLT_MIN_EXP == -1021
    #define __float64_t_defined
    typedef float float64_t;
  // Expand list for variants that I have found
  #elif FLT_RADIX==2 && DBL_MANT_DIG==TBD && DBL_MIN_EXP == TBD
  #else
    #error TBD code for float64_t
  #endif
#endif

Note: Code like DBL_MANT_DIG==24 is not even C compliant with FLT_RADIX==2.  DBL_MANT_DIG >= 34 to meet precision requirements.   This looks like a test for a non-real machine.

I recommend 2 additions:

Report fail to typedef right away with #error

#   elif LDBL_MANT_DIG==53
#       define __float64_t_defined
        typedef long double float64_t;

// Add
#   else
#     error TBD code for float64_t

#   endif

With C11 or later, use _Static_assert

_Static_assert(sizeof (float64_t)*CHAR_BIT == 64, "Unexpected `float64_t` size");

With early compilers, see Static assert in C and others.

floatmax_t

After taking advantage or known COMPILER_CLANG, COMPILER_GCC compilers, I'd recommend more conventional code - Simply test for C99 or later.

#ifndef __floatmax_t_defined
#   if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
#       define __floatmax_t_defined
        typedef double floatmax_t TYPE_MODE(__XF__);
#   elif (__STDC_VERSION__ >= 199901L)
#       define __floatmax_t_defined
        typedef long double floatmax_t;
#   else
#       define __floatmax_t_defined
        typedef double floatmax_t;
#   endif
#endif

Similar question I posed

Detecting unicorn and dinosaur compilers


Preferably I'd like to just be able to update that node in the XML file without having to rewrite the whole file every time a change is made.

In general, that's simply not possible, because XML is a text-based format.

Imagine you have the following file:

<UserSettings>
    <Name>Aron</Name>
    <!-- other settings here -->
</UserSettings>

Now you want to fix the name from “Aron” to “Aaron”:

<UserSettings>
    <Name>Aaron</Name>
    <!-- other settings here -->
</UserSettings>

But doing this means that everything that's after the Name line has to be moved by one byte in the file, so almost the whole file has to be rewritten.

With config files, this usually doesn't matter, because they tend to be relatively small. If it does matter to you, you will have to use another way of saving the config; a good choice might be an embedded database, like SQL Server Compact or SQLite.

Yet another option would be to use .settings files (built-in in VS). It doesn't save you from rewriting the file, but it saves you from having to write all that code.


Loading .txt file content and filename into pandas dataframe

As mention in the comments, pandas work really really well with csv so if you are generating the data your self you might consider to save the data in csv format.
allFiles is just used once, dont define it; use glob in loop instead.
Replace stories and filenames with just one DataFrame, and use pandas.concat()
If you are just updating the script evertime you run it, you can just have a age variable.
Never use file_[0:-4] to remove filextensions, use os.path.splitext.
I guess you will run this code for a lot of diffrent ages, so make a function out of it.

from os.path import basename, splitext
import pandas as pd

def getDataByAge(age)
    res = pd.DataFrame()
    for file_ in glob.glob(".../test_age%d/*.txt" % (age)):
        with open(file_) as f:
            textf = " ".join(line.strip() for line in f)
        res = pd.concat([res,pd.DataFrame(data = {"filename" : [splitext(basename(file_))[0]], "stories" : [textf], "age" : [age]})])
    return res


Confirm code is correct - crossover methods in Java

It's difficult to just look at, but a few things jump out. More improvements than bugs:

For single point crossover using System.arraycopy() would be much more reliable. For example:

System.arraycopy(parent1Genes, 0, childGenes, 0, xoverPoint);
System.arraycopy(parent2Genes, xoverPoint, childGenes, xoverPoint, geneSize-xoverPoint);

You could use the same method for two point, but it would be slightly more complex.
In Uniform crossover you can use rand.nextBoolean(), which returns true or false, instead of  comparing the float.


Create a list of all possible combinations of elements into n-groups from a set of size k

First, determine the one or two group sizes that will apply, and how many of each you will have.  Define m, the maximum capacity of any one group, as ceil( k / n ).  Let i represent the number of groups of size m.  Solving for i, we have

m == ceil( k / n )
( m * i ) + ( ( m - 1 ) * ( n - i ) ) == k
( m * i ) + ( m * ( n - i ) ) - ( n - i ) == k
( m * n ) - ( n - i ) == k
( m * n ) - k - n == -i
k + ( n * ( 1 - m ) ) == i

Thus, there will be i groups of size m and n - i groups of size m - 1.

Then, choose an ordering of the groups.  This is like generating an integer with a given number of 1 bits.  If k happens to be divisible by 'n', there's only one possible ordering.  See Gosper's hack for a nifty way to get the next choice given the current choice, which is essential if you want to implement this as an iterator that yields the next grouping on each call to next().

class GosperIterator implements Iterator< Long > {
    private final int iParticipants, iGroups, iMaxCap, iHowManyMax;
    private long lCurrentOrder;
    public GosperIterator( int iParticipants, int iGroups ) {
        this.iParticipants = iParticipants;
        this.iGroups = iGroups;
        this.iMaxCap = Math.ceil( iParticipants / iGroups );
        this.iHowManyMax = iParticipants + ( iGroups * ( 1 - iMaxCap ) );
        // implemented only for maximum of 64 groups
        this.lCurrentOrder = ( 1L << iHowManyMax ) - 1L;
    }
    @Override public boolean hasNext() {
        return lCurrentOrder < ( 1L << iGroups );
    }
    @Override public Long next() {
        long lOut = lCurrentOrder;
        // Gosper's Hack
        long c = lCurrentOrder & -lCurrentOrder;
        long r = lCurrentOrder + c;
        lCurrentOrder = ( ( ( r ^ lCurrentOrder ) >>> 2 ) / c ) | r;
        return lOut;
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}

Then, allocate each participant x to one of the not full groups which is between the first and the maximum empty group.  That means, in particular, that participant 1 always ends up in the first group, participant 2 always ends up in the first or second group (if there are two groups), etc.

To do this one grouping per next() call, you will need to produce the first grouping (all the participants in order,  say), then start removing participants in reverse order of participant number, looking for an alternative place to assign them which has a higher group number but no smaller empty group.  If no such place exists, back out to a smaller participant number.  If you get all the way to participant 1, it is time to call on Gosper again, and if there are no numbers left for Gosper, you're done.

class GroupingWithFixedLayoutIterator implements Iterator< Set< Set< Integer > > > {
    @Override public boolean hasNext() {
        // left as exercise
    }
    @Override public Set< Set< Integer > > next() {
        // left as exercise
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}
class GroupingIterator implements Iterator< Set< Set< Integer > > > {
    private final int iParticipants;
    private final Iterator< Long > ilLayout;
    private Iterator< Set< Set< Integer > > issiGrouping = null;

    public GroupingIterator( int iParticipants, int iGroups ) {
        this.iParticipants = iParticipants;
        this.ilLayout = new GosperIterator( iParticipants, iGroups );
        initFixedLayoutIterator();
    }
    private final boolean initFixedLayoutIterator() {
        this.issiGrouping = ilLayout.hasNext()
            ? new GroupingWithFixedLayoutIterator( iParticipants, ilLayout.next() )
            : new EmptyIterator< Set< Set< Integer > > >(); // left as exercise
    }
    @Override public boolean hasNext() {
        return issiGrouping.hasNext() || ilLayout.hasNext();
    }
    @Override public Set< Set< Integer > > next() {
        if ( !issiGrouping.hasNext() )
            initFixedLayoutIterator();
        return issiGrouping.next();
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}


I started with your code, added sys.argv so I could pass file paths on the
command line, downloaded a big text file (War and Peace, of course), ran your
program, and checked files sizes:
$ curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt -k

$ time python huffman.py war-peace.txt encoded

real    0m11.052s
user    0m10.462s
sys 0m0.389s

$ ls -lh
-rw-r--r-- 1 fmc staff  40M Aug 24 13:51 encoded
-rw-r--r-- 1 fmc staff 3.3M Aug 24 13:50 war-peace.txt

Looks like you have inadvertently invented an expansion algorithm: it creates a
file roughly 12x bigger! Also, 11 seconds seems slow to process a meager 40M of
text. Normally Python can crunch data of that size much more quickly.
I temporarily assigned a short string (huffman) to the text variable,
bypassing file reading, and printed out some of your intermediate variables.
Although letter_freq looked fine, alphabet was the opposite of what we
want:
f 00000     # The most frequent letter has the longest code.
h 00001
u 0001
m 001
a 01
n 1

The Huffman algorithm combines the 2 elements with the least common
frequency, but you are doing the opposite. So I tweaked your code like this:
(letter1, count1), (letter2, count2) = letter_freq.most_common()[:-3:-1]

With that change, alphabet at least looks more plausible, the output file
ends up being smaller than the input file (although not by as much as I expect,
so there are probably other problems in your code), and it finishes in about 1
second rather than 11 (most likely because it's writing a much smaller output
file).
Some suggestions:

Focus on correctness first. Worry about speed later -- and only if it
truly matters (and it might, if for no other reason that educational).

Algorithms and side effects don't mix. Reorganize your code to facilitate
testing and debugging. The huffman_compress() function itself should not
concern itself with file reading and writing. It should take a blob of text and
return a blob of bytes, period. Highly algorithmic code (as Huffman is) should
never have side effects; it should live in the realm of pure functions.

Roundtrip the data. Also write a huffman_expand() function: take bytes,
return text. Without that, you cannot have any confidence in the process. In
particular, you want to be able to do the following: assert original_text == huffman_expand(huffman_compress(original_text)). That doesn't prove that
you've correctly implemented Huffman (perhaps you will invent your own special
encoding scheme, which could be cool), but at least it will prove that you can make a lossless roundtrip.


Handling Java instant Ajax request/respond with Angular

I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.

The request is being made before the previous post completes.

In your Angular, you need to chain your $http actions

function HomeCtrl($scope, $http) {
    $scope.term = "";
    $scope.location = "";
    $scope.submitSearch = function () {
        var data = {
            term: $scope.term,
            location: $scope.location
        }; //end data
        var res = $http.post('/searchRestaurant', data);

        //chain from the post
        res.then ( function() {
            return $http.get('/restaurantResult').
        }).then ( function(result) {
            $scope.response = result.data;
            return data;
        }).catch ( function(error) {
            //log error
            throw error;
        });

        //return for further chaining
        return res;
    }
 }

By chaining your actions, you guarantee that the previous action completes before starting the next.

Notice that the .then method returns data differently than the .success method.

Also I avoid the .success and .error methods for two reasons: They ignore return values and they are deprecated. For more information on tbe deprecation of .success and .error, see the AngularJS $http Service API Reference -- deprecation notice.

For more information on chaining see AngularJS $q Service API Reference - chaining promises.

UPDATE

To answer you questions about the differences between .then and .catch methods and the deprecated .success and .error methods.

The $http service .then method returns a response object to its resolve callback.

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function resolveCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function catchCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The response object has these properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

--- AngularJS $http Service API Reference -- general usage

  Deprecated: The $http service .success method spreads out the response object.

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

As I said before, avoid these method for two reasons: they ignore return values and they are deprecated.

The rule of thumb for functional programming is always return something. By ignoring return values, .success and .error break that rule. What makes promises powerful is returning and chaining.


Most efficient way to find spatial order from a list of tuples (Python)

No need for recursion. You may want to first convert the tuples to a dict to make it more readable. Then iterate over the dict to construct an ordered list.

In terms of efficiency (or time / space complexity), your code is \$O(n^3)\$ in time and \$O(1)\$ in auxiliary space. Note that idx = tuples.index(e) is not necessary at all, since tuples.index(e) == i. Making use of this would allow your code to be \$O(n^2)\$ in time. The most time-efficient solution is \$O(n)\$, which is also the time complexity of the proposed solution involving a dict. However, the auxiliary space complexity of that solution is \$O(n)\$ -- inferior to your original approach.

If you want to update the order after obtaining a new tuples list, you can keep the dict and iterate over the new tuples, comparing with values in the dict to see if there is any change. However, the efficiency of this approach would probably be in most cases worse than constructing a new dict from scratch.

from collections import defaultdict

def tuples_to_neighbors_dict(tuples):
  """
  Covert `tuples` to a dict mapping each point to a list of its neighbors.
  """
  neighbors = defaultdict(list)

  for (a,b) in tuples:
    neighbors[a].append(b)
    neighbors[b].append(a)

  return neighbors

def tuples_to_order(tuples, start=0):
  """
  Covert `tuples` to a list of points.
  """
  neighbors = tuples_to_neighbors_dict(tuples)
  order = []

  prev = None
  current = start

  while current != start or prev is None:
    # add the current value to the list
    order.append(current)

    # move to the next -- pick the neighbor which we haven't visited yet
    neigh = neighbors[current]
    new = neigh[1] if neigh[0] == prev else neigh[0]
    prev = current
    current = new

  return order

EDIT   I just now looked at the SO question and noticed that one answer is almost identical to mine


Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.

Anyway, pure existence is generally uninteresting, supported operations count.
funcs() and funcs_t are nearly a generally useful abstraction.

Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.

A good name would be overloaded.
HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.
If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.
Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.
return 0; is implicit for main(). Make of that what you will.


Performance of Median routine using min performs abysmally

The structure of your function is

for (i = 0; i < halflength; ++i)    // N/2 iterations
{
    ...

    for (j = 0; j < length; ++j)    // N iterations
    {
        ...
    }

    for (k = 0; k < length; ++k)    // N iterations
    {
        ...
    }
}

this makes \$ N/2 (N+N) = N^2\$ iterations, where \$ N \$ is the length
of the array.

There are small improvements possible: In the k-loop, if a
matching element has been found, you can break-out early:

    // now that we know which is the smallest number, eliminate only 1st occurance of it
    for (k = 0; k < length; ++k)
    {
        float comparitor = array[k];
        if (comparitor == lowestInArray)
        {
            array[k] = highNumber;
            break;
        }
    }

But actually this loop is not needed at all: In the j-loop,
remember the index where the lowest element has been found,
and then set to a "large" number directly:

    float lowestInArray = array[0];
    unsigned int indexOfLowest = 0;

    for (unsigned int j = 1; j < length; ++j) {
        float comparitor = array[j];
        if (comparitor < lowestInArray) {
            lowestInArray = comparitor;
            indexOfLowest = j;
        }
    }
    array[indexOfLowest] = FLT_MAX;

Also FLT_MAX is a better choice than 999.0 for a "large number".
This reduces the number of iterations by a factor of 2.

  If it finds the same number a second time, it ignores the number until
  the next iteration.

Yes, but the j-loop still traverses over the entire array. Instead of
replacing the found minimal element by FLT_MAX, you could replace it
by the last array element, and then reduce the upper bound
for the j-loop accordingly:

for (unsigned int i = 0; i < halflength; ++i)
{
    float lowestInArray = array[0];
    unsigned int indexOfLowest = 0;

    for (unsigned int j = 0; j < length - i; ++j) {
        float comparitor = array[j];
        if (comparitor < lowestInArray) {
            indexOfLowest = comparitor;
            indexOfLowest = j;
        }
    }
    array[indexOfLowest] = array[length - i - 1];
    median = lowestInArray;
}

This reduces the number of iterations again. But it is still
\$  O(N^2) \$, and I doubt that much more is possible with this
algorithm.

As you already noticed, sorting the array first and then taking
the middle element is faster. This is no surprise since sorting can
typically be done in \$  O(N \log N) \$ operations.


there is a lot of thing you can do to further add depth:

move the printing out of the switch
display an help with current operators
implements others operator (pow(), sin(), square(), root()...), you'll then have to check the number of arguments
use a std::map<string, *functionPointer> to avoid the switch
implement a parsing function so you can just enter something like "3+2*8", this would require care as you have to check operator precedence, using prefix or postfix representation could help and allow ignoring ")(".


Thread Safety

Yes, there is a possible race condition here if two threads call Set with the same key. But just using a ConcurrentDictionary won't necessarily be enough, since you're effectively managing a transaction across two dictionaries - the main cache and the expiration task dictionary.

There are several ways to avoid this. One is to use lock around the entire Set statement so that concurrent Set requests on the same key will wait until the first call finishes, and the immediately expires the previous item and replaces it.

A second is to avoid having two dictionaries, and not expose IDictionary in the first place, which I think is the best way to go, for one big reason:

You're currently exposing two very different interfaces in your CacheDictionary. Both the standard IDictionary's Add/[] methods for directly setting/fetching a value, and the ICacheDictionary's Get/Set interface, which is similar to ConcurrentDictionary, and deals with value factories, default values, and a whole set of concepts that IDictionary doesn't deal with, regardless of the actual expiration logic. This can be very confusing to your user, who now has two different ways to do the same thing. If I was using this ICacheDictionary, I wouldn't know if calling myDict[key] = value directly was a good idea or not.

What I would do is just implement ICacheDictionary's Get/Set methods, and keep an internal ConcurrentDictionary<string, Tuple<object, TaskCancellationToken>>. This means you only have one data store, which is thread-safe, and it stores both the value and the expiration task for each entry.

Disposability

Generally speaking, there are two good indicators that you should implement IDisposable to clean up your state. The first is that you're using COM objects/Win32 calls/PInvoke statements to create unmanaged resources. The second is that you're holding instances of IDisposable objects that you might want to dispose explicitly when the container is disposed.

In your case, you don't have any unmanaged code. And as of managed objects, you have two types here - the Dictionary, which doesn't require disposal, and the Task objects, which you don't even bother storing, instead relying on the TaskCancellationSource to handle their cancellation with no way to catch or handle them. Since the official .NET recommendation is to not bother with Disposing Task objects, I think you're in the clear here too.

So no, don't bother implementing IDisposable. You can add a Clear method to clear all items, but that's not the same.


Which way of writing a conditional test is the most readable?

I would suggest to add two more intermediate variables:

var allTriggersAvailable = meterFlag && workFlag && timeFlag;
var anyTriggerAvailable = meterFlag || workFlag || timeFlag;

if (allTriggersAvailable || (!IsAllTriggersRequired && anyTriggerAvailable))
{
    result.Add(new TodayTaskTest { Code = item1.Code, Id = item1.Id, Title = item1.Title });
}


Calculating calendar year for a student based on DOB

I think this is equivalent to your function.

year1 <- function(dob) as.numeric(format(dob, "%Y")) + 6 +
    (as.Date("1997-07-01") <= dob & 7 <= as.numeric(format(dob, "%m")))

You would run it like this.

> test <- c(as.Date("1985-09-15"),as.Date("1999-02-15"),as.Date("2004-08-15"))
> year1(test)