Credit card validator using Luhn's algorithm

Comments

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */

You're stating the obvious and forgetting the important things. Yes, args is the command line arguments, but that's standard for the Java main method. I'd suggest documenting which command line arguments you actually accept - namely only one, and it should be a file path!

Additionally, some of the code in the methods below looks like it could use some commenting as well. It looks complicated. Maybe I'll understand it if I look at it in greater detail...

Throw exceptions when it matters

    for (int i = 0; i < array.length; i++) {
        array[i] = Integer.parseInt("" + reverse.charAt(i));
    }

From your validate function. This will throw NumberFormatException if it fails to convert the character to an Integer. But if you throw NumberFormatException, the whole program grinds to a halt! If you encounter an unparseable character in a creditcard number, then obviously it's not a valid credit card number. Wrap it with try-catch and return false.

Readability

if (str.length() >= 16 && str.length() <= 19) {
    return "MasterCard";
}

When dealing with ranges, I prefer to write an if statement as a range, rather than two separate conditions. Consider if (16 <= str.length() && str.length() <= 19) instead. This goes for all cases where you have ranges like this.

Magic Numbers

Your third method is filled with magic numbers! What do 622126, 622925, 6011, 644, 649 and so on even mean?! In this case, I think they're all connected in some sort of way. You should add a comment in the code stating where you got the numbers from.

Simplifying the algorithm

    int[] array = new int[str.length()];
    for (int i = 0; i < array.length; i++) {
        array[i] = Integer.parseInt("" + reverse.charAt(i));
    }
    int sum = 0;
    for (int i = 0; i < array.length; i++) {
        if (i % 2 == 1) {
            array[i] *= 2;
            if (array[i] > 9) {
                array[i] -= 9;
            }
        }
        sum += array[i];
    }
    return sum % 10 == 0;

You're using two for loops, but don't use the result in the meantime. You end up only needing the sum of the contents, with some minor permutations. Let's simplify!

First, merge the two for loops.

    int[] array = new int[str.length()];
    int sum = 0;
    for (int i = 0; i < array.length; i++) {
        array[i] = Integer.parseInt("" + reverse.charAt(i));
        if (i % 2 == 1) {
            array[i] *= 2;
            if (array[i] > 9) {
                array[i] -= 9;
            }
        }
        sum += array[i];
    }
    return sum % 10 == 0;

Now that we've merged the two for loops we see that we store data in the array... but never use it afterwards! So all we really need is a single int value.

    int sum = 0;
    for (int i = 0; i < str.length(); i++) {
        int digit = Integer.parseInt("" + reverse.charAt(i));
        if (i % 2 == 1) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }
        sum += digit;
    }
    return sum % 10 == 0;

And there we go - it's a bit simpler now. You'll still have to add the try-catch that I suggested above yourself, though.

Other comments

String reverse = new StringBuilder().append(str).reverse().toString();

java.lang.StringBuilder can take a String as argument. Doing so would allow you to remove your append call, shortening the code, making it more readable (and potentially speeding things up slightly as you need 1 function call less, but that's negligible).


Greatest prime number smaller than N where N can be as large as 10^18

These macros are not needed in C++:

#define c2 341550071728321
#define c1 4759123141

They should be constants, using the const keyword (or constexpr in C++11):

const int c2 = 341550071728321;
const int c1 = 4759123141;

I've only kept the names the same here because I have no idea what they mean.  Try to avoid using single-char variable names, unless their meaning is already obvious.
You use unsigned long long in many places, which could look verbose.  You could use a typedef so that you can use another (shorter) name in place of them:

typedef unsigned long long ull;

Better yet, you can use std::uint64_t from <cstdint>.  It is shorter, and it should be guaranteed to hold 64 bits on any system.
This is quite a bit of whitespace:

if (n < c1) {

            l = 3;
    }
    else if (n < c2) {
            l = 7;
    }
    else {

            l = 9;
    }

You already use four spaces for indentation, so it should be consistent:

if (n < c1) {
    l = 3;
}
else if (n < c2) {
    l = 7;
}
else {
    l = 9;
}

You're also lacking indentation within main() and check_prime(), but it's okay in your other functions.  I don't see the reason for all this inconsistency if you're not in a hurry to write the code itself.  Make it clean now so that fine-tuning will be easier, both for you and for others.


Python script to find employees who are in one PostgreSQL table but not in another

LEFT JOIN from test_test to test_table selecting only rows where test_table.test_emp_id is null.

select emp_id
from test_test
left join test_table on (
    test_table.test_emp_id = test_test.emp_id and
    test_table.state = 'test_state'
)
where (
    test_test.flag = true and
    test_test.emp_id is not null and
    test_test.ver_id in (
        select id
        from test_phases
        where state = 'test'
    ) and
    test_table.test_emp_id is null
)

You may also want to consider:

Using an inner join instead of a subquery to select only rows with test_phases.state = 'test'.
Selecting distinct emp_ids if test_test.emp_id does not have a unique constraint.

select distinct emp_id
from test_test
inner join test_phases on test_phases.id = test_test.ver_id
left join test_table on (
    test_table.test_emp_id = test_test.emp_id and
    test_table.state = 'test_state'
)
where (
    test_test.flag = true and
    test_test.emp_id is not null and
    test_phases.state = 'test' and
    test_table.test_emp_id is null
)


Simple Random Password Generator in Python

I found a bug. If the initial response to "Do you want to..." is neither yes-like or no-like, it prompts for the username again. Also, you have large sections of dead code that will never execute.

Avoid duplicating code.

Several prompts are exactly the same as each other, even with the same logic after them. Refactor the code so that each possibility only occurs once.
Avoid duplicating variables

The GeneratePassword and GeneratePasswordAgain variables serve the same purpose: to get user input and determine if it should continue. and should be unified.
Keep the code reusable.

Avoid calls like sys.exit() that prevent this snippet of code from being used elsewhere.
Use the language features properly.

You know how to use while loops -- so why are you making multiple unnecessary recursive calls, each of which performs the same task as a while loop?
Separate logic and user-interface. Separate the code into modules.

Write the function that generates the password and does nothing else. Something like

 def RandomPassword(passwordCharacters, minLetters, maxLetters):
    return "".join(random.choice(PasswordCharacters) for i in range(random.randint(minLetters, maxLetters)))

 def DefaultRandomPassword():
     passwordCharacters = string.ascii_letters + string.digits + string.punctuation
     return RandomPassword(passwordCharacters, 8, 16)

Write another function that takes a prompt, displays it, waits for the user to type something, and then does it again if it was not a valid yes-no answer. Then return either yes or no. Call this function multiple times.


Transforming data from an API using Typescript and Lodash

First and most importantly, change your policy about using any for unstable APIs.

Typescript is an incredibly powerful tool for making it possible to work with constantly changing APIs. When you use any you are throwing away (nearly) all the benefits which Typescript gives you. If you declare an interface for the data being returned by the API, you can simply modify the interface when the format changes and you will be alerted to any code which needs to be updated. If you instead use any your code will compile without any warnings - and then break in production.

Besides this, there really isn't that much to mention. Good work!

On to the code:

The first thing I did was add types, here are the interfaces I will be using for the rest of the answer:

interface APITabCategory {
    Color: string;
    GroupName: string;
    QuoteCount: number;
    SortOrder: number;
    TabCategoryID: string;
    TabCategoryName: string;
    TabCategoryOrder: number;
    TabID: number;
    TabName: string;
}

interface Tab {
    Color: string;
    SortOrder: number;
    TabID: number;
    TabName: string;
    QuoteCount: number;
}

interface TabCategory {
    TabCategoryID: string;
    TabCategoryName: string;
    TabCategoryOrder: number;
    Tabs: Tab[]
}

interface TabCategoryCollection {
    GroupName: string;
    TabCategories: TabCategory[]
}

It doesn't do what you think it does. As soon as I added interfaces for your types Typescript yelled at me that TabCategoryOrder was missing - this may be intentional as you are now using an array, but it is included in your sample output.
The current code includes a bunch of extra data in each Tab, this is fine so far as Typescript is concerned, but since this code normalizes the data you may want to consider removing the extra properties.
JavaScript has built in map and filter functions on arrays, I prefer using these to their lodash alternatives where appropriate. In this case, it removes most of your code's dependence on lodash.
Avoid double checking conditions. If you save the quotes with the current group name in an array, you can avoid checking the group name when extracting the tabs.
Get a linting program and use it - the current code is inconsistent with whether or not to use semicolons.

Here is how I would implement this function:

function FormatQuoteSummaries(Quotes: APITabCategory[]): TabCategoryCollection[] {
    const UniqueGroupNames = _.uniq(Quotes.map(Quote => Quote.GroupName));

    return UniqueGroupNames.map(GroupName => {
        const GroupQuotes = Quotes.filter(Quote => Quote.GroupName == GroupName)

        const TabCategories: TabCategory[] = GroupQuotes
            .filter(Quote => Quote.GroupName === GroupName)
            .map(({ TabCategoryID, TabCategoryName, TabCategoryOrder }) => {
                return {
                    TabCategoryID,
                    TabCategoryName,
                    TabCategoryOrder,
                    Tabs: GroupQuotes.filter(Quote => Quote.TabCategoryName === TabCategoryName)
                };
            });

        return {
            GroupName,
            TabCategories: _.uniqBy(TabCategories, 'TabCategoryID')
        };
    });
}

One last small nitpick, it is fairly standard is JavaScript / TypeScript to use camelCase as opposed to PascalCase for local variables and properties. Most JS / TS devs, when seeing Quotes expect a class / interface / enum / namespace, not an object or array. Feel free to disregard if your team has an established naming convention already.


A faster way to compute the largest prime factor

There are many questions about Project Euler 3 on this site already.  The trick is to pick an algorithm that…

Reduces n whenever you find a factor, so that you don't need to consider factors anywhere near as large as 600851475143
Only finds prime factors, and never composite factors, so that you never need to explicitly test for primality.

Your algorithm suffers on both criteria: the outer for loop goes all the way up to 600851475143 (which is ridiculous, because even if you optimistically assume that it takes one nanosecond per loop, that would be 5 minutes), and you're testing each of those numbers for primality (which is incredibly computationally expensive).


I'm not sure what you're looking for specifically in trying to revise your program past this point. So, here's a handful of general things I would change:

Remove static modifier from your code. This can be done by creating an NQueens class, that maybe takes the N as a parameter to it's constructor, then can be run by calling a "run" method.
Use curly braces on all your conditional statements. You're less likely to break code down the road that way.
See all those comments you have? Instead of commenting on little sections of that, you could increase your code's readability by making those their own methods.

Example: In the following code, maybe make a method that explains what you're doing here, such as resetPosition or something.

    //If current column is not valid
    column++;
    if (column >= board.length) {
        board[row] = -1;
        row--;
        if (row >= 0)
            column = board[row] + 1;
    }

I would suggest trying to better name your iterators as well. i and j are just fine, but if you're actually iterating through something that has a name, such as row, column, etc. go ahead and use that. Again, easier to read and follow the algorithm.
Similarly, row, column aren't totally obvious in how they're used. Would they be better represented as currentRow or currentColumn? Since you're using these as nodes to find new solutions from, it might makes sense to have a more descriptive name.
isValid; what exactly is valid? Is that a valid representation of the board, a valid solution, or only part of the solution?
Lastly, why isn't the board represented as a 2D array? You received this as feedback last time as well, but I second it. A game board is represented in 2-dimensional space, x and y. The same way a cube would be in 3-dimensional space and therefor hopefully be represented as a 3-dimensional array. Trying to represent objects outside their native dimension takes some time to understand. I would avoid this at all costs unless there are serious performance gains to be made.

I think the point I'm getting at here is that: Ideally, I shouldn't have to know anything about what the NQueens problem is in order to follow your code without much issue.


One-by-one file deletion for a derived list of files

I may suggest the following : why checking for file deletion ?

if (File.Exists(fileEntry))

After all, in file.delete documentation we have :

  If the file to be deleted does not exist, no exception is thrown.


Error handling

What if there is no <title> in a web page,
or if it's written as <TITLE>?
The script will crash.

It we would be good to check the result of Split to make sure you don't access an invalid index.

Extracting substrings

Instead of Split,
it would be better to use Instr to find the start and end positions of the title, and then Mid to extract the substring.
This is better because Split creates an array of strings, and scan until the end of the input string. Instr can stop immediately when it finds a match and doesn't need to create new objects.


Business logic inside MVC Cart Controller method

I think there is more to discuss here then business logic inside your controller.  I'm going to generally keep it to a high level of discussion, but feel free to comment and ask for specifics.  I'm going to break it down like this:

Security issues
Architecture issues
Business logic issues
Formatting issues

Here we go!

Security

These two lines right here are actually quite dangerous:

$productId  = $_POST['productId'];
$quantity   = $_POST['quantity'];

It doesn't look like you are doing any validation/filtering/cleaning of user input.  Both of these variables are copied straight out of the user input and then sent off to various methods (getProductDetailsByProductId, computeProductPrice) that have no expectation that they are now dealing with untrusted user input.  As a result, the possibility of security vulnerabilities is high.  At the very least, you should:

$productId  = (int) $_POST['productId'];
$quantity   = (int) $_POST['quantity'];

Understanding that user input is untrustworthy, and treating it as such, is a key part of application security.  I would very carefully check the rest of your code and make sure that you are vetting all user input everywhere.  Are you familiar with the dangers of XSS vulnerabilities and SQL injection?  If you're not, now is the time to start learning.

I similarly don't see anything related to CSRF protection, which is a necessity for endpoints such as this.  Some frameworks would automatically handle CSRF protection in middleware, but given the overall details of what I see here, I'm suspicious that CSRF protection is simply not happening.

Architecture

The "fatness" of your controller has to do with more than just business logic.  You are also instantiating your dependencies directly inside your controller.  This makes automated testing impossible, but also opens you up to any number of subtle bugs.  Dependency injection is the best way to fix these issues, but if that is too much of an architectural change for you, you could always go with the old school fallback: singletons.  It's far from ideal, but it is easier to implement than dependency injection, and will at least make it so that you can't accidentally open up multiple connections to the database in response to a single HTTP request.

To be clear, these are the lines I'm talking about:

$connection = new Connection();
$session    = new SessionModel();

Although to be fair, all of your object instantiation is a symptom of the problem.  What it really comes down to is a lack of proper separation of concerns.  Your controller is in charge of everything: not just business logic, but also application logic.  This makes it substantially harder to manage your application in the long-run.

Business Logic

Getting to your question, I definitely think that you have too much business logic in your controller.  The issue is that you are looking at this from the perspective of "I've got this one place where I add items to the cart".  It never works that way.  An e-commerce system naturally starts that way, but you will find your needs will quickly grow over time.  How do you handle the situation when someone says: "Hey, can I look at my order history and click a button to add an old order back into my cart?".  That is a super common feature for an e-commerce platform.  Unfortunately, adding an item to a user's cart currently involves multiple dependencies and 50ish lines of code.  If you ever need to add to a cart, in any other way, and at any other endpoint, you will very quickly realize the pain caused by fat controllers like this.

So what should it look like?  This is what your controller method should look like:

public function processAddingAndUpdatingOfCartItems(cart $cart)
{
    // Get values from request
    $productId  = (int) $_POST['productId'];
    $quantity   = (int) $_POST['quantity'];

    if ($quantity <= 0)
        return 'Invalid quantity';

    if (!$cart->is_valid_product($productId))
        return 'Invalid product';

    if (!$cart->add_product($productId, $quantity))
        return 'There was an error processing your request';

    return redirect('/view_cart');
}

All of this business logic should be handled by the cart.  You should not instantiate the database connection: in fact, your controller shouldn't even need it.  You preferably shouldn't even create the cart: it should be injected in.  Worst-case scenario though, the cart is the only thing you should have to create.

The cart should handle validation (which it can defer to a cartValidator, if desired).  The cart should defer storage of itself to the session object, and the cart shouldn't care about whether the session exists or not.  That is the session objects job.  The session object should simply be told "store this", and the session object should automatically create the actual session, if need be.  Ideally this would all happen via dependency injection.

These are just a couple points, but it all boils down to the same thing: to get anything done, your controller has to know about everything.  It would help to read up on the single responsibility principle.  The more things your code has to "know" about to get its job done, the more room there is for things to break in the future, and the harder it is to update your application.

Keep in mind that the goal here isn't just to shuffle everything into a cart class.  Rather, the cart class itself defers most of its responsibility to its own child classes: cartValidator, cartProduct, session, etc...  A lot of the stuff you have right now needs to be better divided into some of these classes, so that each class does only the things that are directly related to its own functionality, and defers the rest to someone else.  However, you should have one cart object that acts as a single entry point for all cart-related functionality: adding products, verifying product information, etc...

Formatting

This one isn't too bad, but the way you line up your variables is a little wonky.  Many code bases avoid lining things up all together, but if you would rather do that in your code base, obviously that's perfectly reasonable.  I think though that if you are going to do this you should find some consistent stop-points for lining stuff up at.  If you put some of your lines of code right next to eachother, I think you'll see the problem:

$productTable   = new ProductTable($connection);
$productDetails = $productTable->getProductDetailsByProductId($productId);
$productModel = new Product();
$productPrice = $productModel->computeProductPrice($productId, $quantity);
$cartItem   = new CartItemModel();
$cartValidator                  = new CartValidator();
$doesCartExistForCurrentUser    = $cartValidator->doesCartExistForCurrentUser();
$cartTable      = new CartTable($connection);
$cartItemTable  = new CartItemTable();

The inconsistency can be distracting, and the last thing you want while looking at code is to be distracted.  Code gets read much more than it is written, so it is best to write it consistently.

Again, I'm happy to delve into more details on any particular item, if you are interested.

Dependency Injection

Dependency injection is not a small thing, and won't be a small change for your system architecture.  That being said, dependency injection will be an important change for your architecture, and, if done right, will substantially improve your organization and long-term maintainability.  As Sam mentioned, learning about SOLID is a good place to start.  The idea though is that you don't directly instantiate your dependencies.  Rather, they are given to you.  This is typically done via type-hinting in your constructor.  In many ways, your other classes are already doing this.  The trick therefore is to implement a dependency injection container.  Again, this isn't necessarily a small thing, so do some reading first, find an open-source one instead of building your own, and start small.  It is absolutely worth the effort.

In practice it works because your dependency injection container builds all of your objects for you, and uses reflection to determine the dependency each object needs to do its job.  So your controller would look like this:

class cart_controller{
    public function __construct(cart $cart, request $request){
        $this->cart = $cart;
        $this->request = $request; // stores details of the HTTP request
    }
}

Your cart then might look like this:

class cart{
    public function __construct(session $session, cartItemFactory $cartItemFactory, cartValidator $cartValidator){
        // store dependencies
    }
}

Your application bootstrapping process builds the controller with the dependency injection container, the dependency injection container sees that the controller needs the cart, it sees the cart needs the session, itemFactory, and validator, and then it will find any necessary dependencies of those things as well.  It starts at the bottom of the dependency tree, building the things that have no dependencies, passing those into the next objects and building them, and all the way up until you have a controller that gets a cart object when it is instantiated.

It can be complicated, which is why it is best to just use a pre-built DI container.  It is also a completely different way of building your application, which is why it is best to spend some time learning and start small.  This isn't the sort of thing you just "do" over a weekend.  The biggest advantage though is that it allows you to actually test your code.  Having maintained large applications both with and without automated testing, I can tell you that in the long run having some automated tests (unit tests, integration tests, etc...) in place is a huge boon to your ability to maintain your code-base, and introduce new features quickly.  That alone is absolutely worth the time it will take you to implement these large changes.

Then again, some of your classes are already receiving some of their dependencies through their constructor arguments, so you're also kind of halfway there.

Responding to your questions

Regarding whether or not to have the DB connection passed in to the controller constructor: As a general rule of thumb, if you have a controller with methods that have completely different dependencies, then they should probably be in different controllers.  It all comes down to the Single Responsibility Principle and proper separation-of-concerns, which you will read plenty about if you start learning about SOLID.  As another option though, it is common in some PHP MVC frameworks to do method-level dependency injection, where each controller-method can have additional dependencies injected in.  I'm not really a fan of it myself (partly for the above reasons), but it is a common pattern, so you wouldn't be crazy to do it.

Regarding my comment about how all your object instantiation is a symptom of the problem, what I mean is that directly creating objects violates the D in SOLID, which Sam mentioned in his answer.  When you directly create your dependencies, rather than allowing them to be given to you, you tightly couple a class to its sub-classes, which makes your application more rigid, harder to maintain, and impossible to test.  Again, this are large architectural changes, so it is probably best to start by reading up on these topics, and practicing them with smaller applications before doing anything crazy with your code base.


To update or to delete? That is the Query

Depending on your use case, I recommend two options. Both of them are based on a separate function for checking things....

At its simplest, have a function:

private static final boolean needToDoSomething(String currentValue, String newValue) {
    return currentValue == null && newValue != null || currentValue != null && newValue == null;
}

Then you can just have:

if (needToDoSomething(currentValue, newValue)) {
    ....
}

If you need to do something more special than just the 'needs modification' test, for example, you need to distinguish inside the if block between these conditions, then I would recommend an Enum with a static method, for example:

public enum EditState {
    ADDED, DELETED, MODIFIED, UNCHANGED;

    public static getState(String currentValue, String newValue) {
        if (currentValue == newValue) {
            // this covers null == null too
            return UNCHANGED;
        }
        if (currentValue != null && newValue == null) {
            return DELETED;
        }
        if (newValue != null && currentValue == null) {
            return ADDED;
        }
        return currentValue.equals(newValue) ? UNCHANGED : MODIFIED;
    }

    public boolean isStateChanging() {
        return this != UNCHANGED;
    }
}

Then, with this Enum class, you can be more specific:

EditState state = EditState.getState(currentValue, newValue);

switch (state) {
    case UNCHANGED :
        .....
    case DELETED :
        .....
    ....
}


Finding the date from "2nd Friday of X month"-style input

Your code is pretty clear but can be improved using builtin capabilities of calendar: the monthcalendar method return a list of list representing each week of the selected month (zeroes are days that are not in the month). By filtering these weeks using the index of the day you are looking for, you get all the possible day of the month that are the requested day. You can then just pick the right one into this list.

Python related remarks:

Put your import at the beginning of the file, not into functions. It will slow you down if you are heavily calling functions that contain import statements;
wkday is a constant and must be declared as such: outside of the function and with proper case;
there is no really need to make wkday a dictionary given that you can get the same information it holds using .index on a list;
[optional] depending on your needs, you may want to perform proper input validations.

import calendar
from datetime import date

DAY_NAMES = [day for day in calendar.day_name]

def meetup_day(year, month, weekday, spec_weekday):
    day_index = DAY_NAMES.index(weekday)
    possible_dates = [
        week[day_index]
        for week in calendar.monthcalendar(year, month)
        if week[day_index]] # remove zeroes

    if spec_weekday == 'teenth':
        for day_num in possible_dates:
            if 13 <= day_num <= 19:
                return date(year, month, day_num)
    elif spec_weekday == 'last':
        day_index = -1
    elif spec_weekday == 'first':
        day_index = 0
    else:
        day_index = int(spec_weekday[0]) - 1
    return date(year, month, possible_dates[day_index])

meetup_day(2014, 3, "Friday", "2nd")
meetup_day(2013, 6, "Wednesday", "4th")
meetup_day(2013, 12, "Monday", "1st")
meetup_day(2015, 5, "Tuesday", "teenth")
meetup_day(2015, 4, "Thursday", "last")


You can use unwords in place of intercalate " ".

Given the type signature of getInteger :: String -> Integer the return type of read xs must be Integer in order for the type system to unify what you've written, making your type annotation on the function implementation there redundant. You can perform eta-reduction on getInteger then (that is, write it in pointfree style) and drop the xs for an implementation of—

getInteger :: String -> Integer
getInteger = read

This is now obviously a specialization of read, which isn't all that interesting. Look now to the implementation of nthLineStr where you can see that the result of getInteger xs is passed to nthLine. Because the type of nthLine is given as Integer -> String, the compiler can again determine that read must return an Integer if you change the definition of nthLineStr to—

nthLineStr :: String -> String
nthLineStr xs = nthLine (read xs)

You can perform eta-reduction again to write nthLineStr as nthLineStr = nthLine . read. nthLineStr is a bit of a kludge though, in that it muddies the waters between your pure code and the outside world. Keep your (de-)serialization functions apart from the rest of your program, it shouldn't matter to the core logic of your application whether you were passed a String or a Text value or length encoded sequence of unit values ([()]).

main :: IO ()
main = do n <- fmap read getLine
       putStrLn $ nthLine n

Or you could use another Prelude function, interact :: (String -> String) -> IO () (a useful concept, but note this changes the semantics a bit).

main :: IO ()
main = interact (nthLine . read)


I don't have many improvements to offer-- just one major one. Like you suspected, your implementation is not efficient. This is because using a double for loop to set a Torch/NumPy array is not the preferred way to do sum reductions. What is preferred, is the use of torch.einsum. It takes an indices equation and reduces the Tensors into a final representation.

First to note is that your equation for reg_g_ij is not the most simplified form.

In your code, we start with:

q_i * q_j * (1 - C_ij) + (1 - q_i * q_j) * C_ij

But it can be reduced to:

q_i * q_j * (1 - 2 * C_ij) + C_ij

You can prove it yourself with a few lines of algebra.

The last small thing is call .unsqueeze(0) when you're expanding the dimensions of an array. In this case we used this method to expand an array's size from (9, 9) to (1, 9, 9).

    A_0 = torch.eye(n_node).unsqueeze(0)
    A_i = A

    B = A_0.repeat(reg_sig.size(0), 1, 1)

    for i in range(1, n_node):
        A_i = Sig(100 * (torch.bmm(A_i, A) - 0.5))

        B += A_i

    C = Sig(100 * (B - 0.5))

    reg_g_ij = torch.einsum('ij,ik,ijk->ijk', q, q, 1 - 2 * C) + C

When profiling this approach, we see a pretty big reduction in time:

In [257]: %timeit new(reg_sig, reg_adj)
1000 loops, best of 5: 745 µs per loop

In [258]: %timeit orig(reg_sig, reg_adj)
The slowest run took 4.85 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 5: 5.44 ms per loop


Request for help to tidy up code involving arrays and loops

After stressing about it for about two hours, I got the methods sorted, so I'll answer my own question. Please note - I'm just a beginner and I'm sure there are plenty of things that could be done even more efficiently!

import java.util.Random;
// Imports Java random number generator.

public class Practical4_Assessed_with_Methods
{
static int[] randomNumbers = new int[100];
static int[] countNumbers = new int[10];
// Two arrays declared, one to hold 100 elements, the other 10.

public static void main(String[] args)
{
    programExplanation();
    generateNumbers(randomNumbers, countNumbers);
    printNumbers(randomNumbers);
    generateNumberOfOccurences(countNumbers);
    generateAsteriskPattern(countNumbers);
    findMaxValues(countNumbers);
    // Code is broken down into five method calls (to make each section more manageable and testable).
}

static void programExplanation()
{
    System.out.println("This program will generate 100 random integers between 1 and 10. " +
            "It will then output them in rows of 10.");
    System.out.println("Following this, it will output how often each integer occured in " +
            "the array.");
    System.out.println("It will also output this information in a horizontal bar chart of " +
            "asterisks.");
    System.out.println("Finally, it will output which number, or numbers appeared most often");
    System.out.println("");
}

static void generateNumbers(int[] arrayOfGenerator, int[] countArray)
{
    Random numberGenerator = new Random ();
    for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++) // For loop continues 100 times.
    {
        int count = numberGenerator.nextInt(10);
        countArray[count]++;
        arrayOfGenerator[countOfGenerator] = count + 1;
    }
    /*  A random number (from 0 and 9) is generated and stored in count.
     *  Whatever number is generated, that element number of countArray is incremented by 1.
     *  E.g. If random number generated = 4, fourth element of countArray (i.e. element 3) is increased by 1.
     *  The element of arrayOfGenerator (determined by the loop) is given the value of count + 1.
     *  This is because the numberGenerator creates integers from 0 and 9 - we want from 1 and 10.

     *  This coding is beneficial as both arrays are filled at the same time, which saves processing time.
     */
}

static void printNumbers(int[] arrayOfGenerator)
{
    int countOfNumbersOnLine = 0;
    for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
    {
        if (countOfNumbersOnLine % 10 == 0)
            System.out.println("");
        //  Takes a new line when 10 integers have been printed on a line.

            if (arrayOfGenerator[countOfOutput] == 10)
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "  ");
                countOfNumbersOnLine++;
            }
            else
            {
                System.out.print(arrayOfGenerator[countOfOutput] + "   ");
                countOfNumbersOnLine++;
            }

    }
    /*  Used to calculate the amount of integers on a line and the spacing between them.
     *  If the arrayOfGenerator is 10, it takes two spaces, else it takes 3 spaces (to ensure proper spacing).
     *  This is needed because the numeral 10 has two characters, as opposed to 1-9.
     */

    System.out.println("");
    System.out.println("");
}

static void generateNumberOfOccurences(int[] countOfArray)
{
    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
        System.out.println("The number " + (countOfNumbers + 1) + " occurs " + countOfArray[countOfNumbers] + " times.");
    System.out.println("");
    /*  For loop continues for entire length of countOfArray (i.e. 10 times)
     *  Prints out how often each random number occured.
     */
}

static void generateAsteriskPattern(int[] countOfArray)
{
    for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
    {
        if (countOfNumbers != 9)
            System.out.print((countOfNumbers + 1) + "   ");
        else
            System.out.print((countOfNumbers + 1) + "  ");

        for (int asteriskCount = 0; asteriskCount < countOfArray[countOfNumbers]; asteriskCount++)
            System.out.print("*");
        System.out.println("");
    }
    System.out.println("");
    /*  For loop continues for entire length of countOfArray (i.e. 10 times)
     *  First if/else statement determines how many spaces are taken after numeral and before asterisks.
     *  This is used to ensure all asterisks are vertically aligned when output.
     *  Second for statement runs on each element of countOfArray, outputting asterisks for as long as array lasts.
     *  For example, if element 0 has the value 3, 3 asterisks are output.
     */
}

static void findMaxValues(int[] countOfArray)
{
    int max = 0;
    for (int counter = 0; counter < countOfArray.length; counter++)
    {
        if (countOfArray[counter] > max)
        {
            max = countOfArray[counter];
        }
    }

    System.out.print("Number(s) that appears the most:");
    /*  For loop continues for entire length of countOfArray (i.e. 10 times) and compares each value to max.
     *  If value compared is larger than the max value, it becomes new max value.
     *  By the end of this loop, largest value in the array is stored in max.
     */

    for(int checkValue = 0; checkValue < countOfArray.length; checkValue++)
        if(countOfArray[checkValue] == max)
            System.out.print(" " + (checkValue + 1));
    System.out.print(".");
    /*  For loop continues for entire length of countOfArray (i.e. 10 times)
     *  If value of element scanned is equal to the value in max, it is output.
     */
}
}

Andrew


Phone number to words based on the dictionary

I would first start by doing some basic profiling of your application to see where the issues are. This could be as simple as inserting console.log( (new Date()).valueOf() ) in a few places.

Some things I noticed.

Is your dictionary file sorted? If not then sort it first. Either way use bsearch to locate entries rather han using & which is very naive.
It looks like you are trying every combination of letters but you probably want to use an algorithm that stops if there is no match. For example given 668, if your dictionary contains no entries starting with mn (66) then there is no point in checking mnt, mnu, mnv` or any of the longer combinations.
Try to reduce the number of times you copy and modify arrays ([a..b] or shift)
This check: next if first_array.length < 3 || second_array.length < 3 could go before you copy the array (in a slightly modified form). You could just change for i in (2..total_number) to for i in (4..total_number-2)


Python solution for the N-Queens challenge

Separate generation and presentation

valid_boards both generates the solutions, prints and counts them. Better would be to have 1 method to generate the solutions, another to present the result. The simplest way to do this is to make a generator that yields the solutions, and another method that prints and counts them

reversed

reversed(range(row)) is a lot more clear than range(row - 1, -1, -1)

magical values

you use 0 for blocked, 1 for free and 2 for an occupied tile. defining these as global constants would be a lot clearer

BLOCKED = 0
FREE = 1
OCCUPIED = 2

and then use if for example

chess_board[row, col] = BLOCKED

board size

You use num and limit for the same value, the size of the board. Lat's just call this boardsize

DRY

In block_positions you do a lot of repetition for the different directions to block. More clear would be to use a generator that yields all the neighbour of a tile, and use the coordinates yielded to block those

To do this you need a method to check whether a coordinate is valid:

def valid_coord(coordinate, boardsize=5):
    row, column = coordinate
    return 0 <= row < boardsize and 0 <= column < boardsize

then using itertools.takewhile, functools.partial and itertools.count

def neighbours(row, column, boardsize):
    validator = partial(valid_coord, boardsize=boardsize)
    yield from ((row, i) for i in range(0, column))
    yield from ((row, i) for i in range(column + 1, boardsize))
    yield from ((i, column) for i in range(0, row))
    yield from ((i, column) for i in range(row + 1, boardsize))
    yield from takewhile(validator, ((row - i, column - i) for i in count(1)))
    yield from takewhile(validator, ((row + i, column + i) for i in count(1)))
    yield from takewhile(validator, ((row - i, column + i) for i in count(1)))
    yield from takewhile(validator, ((row + i, column - i) for i in count(1)))

list(neighbours(2, 3, boardsize=5))

[(2, 0), (2, 1), (2, 2), (2, 4), (0, 3), (1, 3), (3, 3), (4, 3), (1, 2), (0, 1), (3, 4), (1, 4), (3, 2), (4, 1)]

Then the block_positions suddenly becomes very simple

def block_positions(chess_board, row, column, boardsize):
    """Fills all squares that can no longer contain a queen with the value -1
    There are a maximum of 8 directions that must be blocked from a given square"""
    for x, y in neighbours(row, column, boardsize):
        chess_board[x, y] = BLOCKED

This method doesn't need to return the board. The standard library's convention is that if a method changes the object, it doesn't return something. If it returns a new object, that is returned.

By just changing the neighbours, you can easily change this to find the solutions for [related puzzles(https://en.wikipedia.org/wiki/Eight_queens_puzzle#Related_problems)

numpy

You hardly use any of the numpy strengts, but even then this can be simpler
You can pass a tuple to np.one, so initialise_board  can be as simple as

def initialise_board(num):
    """Build the empty board"""
    return  np.ones((num, num)) * FREE

Counting the number of places queens can be simpler too: (board == OCCUPIED).sum() == num instead of np.flatten and Counter

generator

Now the valid_boards method both generates the solutions, prints them and augments the counter. Simpler would be to have them just generate the solutions, and have something else take care of the printing and counting.

Slightly adapting your algorithm to a generator approach:

def add_queen(board, row, boardsize):
    if row == boardsize:
        yield board
        return
    free_columns = (index for index in range(boardsize) if board[row, index] == FREE)
    for column in free_columns:
        new_board = board.copy()
        new_board[row, column] = OCCUPIED
        block_positions(new_board, row, column, boardsize)
        yield from add_queen(new_board, row + 1, boardsize)

and call it like this:

if __name__ == "__main__":
    boardsize = 5
    board = initialise_board(boardsize)
    for solution_count, solution in enumerate(
        add_queen(board, row=0, boardsize=boardsize), 1
    ):
        print(solution)
        print()
    print(f"{solution_count} solutions")


Accelerate computing a Gram-like matrix with large files

Try to cache as much as possible.

I suppose buying more RAM and read all .npy files in advance is out of the question.

But, for instance, if it is possible to keep the data of 20 files in memory, you could read 10 files for vi-data and 10 files for vj-data, now you can fill a block of 10x10 in matrix G at the cost of 20 file reads instead of 10 + 10x10 = 110 file reads. Looping and indexing will get a bit more complicated of course.


Simple download manager based on Youtube-dl

Issues
The first one is the use of the or operator. If you wish to compare a variable with two values, you will have to write the comparison operator twice.
For instance,
if Login_ == 'y' or 'Y':
  ...

should be write as:
if Login_ == 'y' or Login_ == 'Y':

Also, it seems you are returning from the Downloader function before iterating though all links (whenever the first process finishes correcly):
...
if result == 0:
  download_count += 1
  # This will return after one commad executes successfully
  return('\nReturned Value', result)

Code style
Now, regarding code smells and style, in python there is PEP-8, a general guide for code style.
For example, functions/methods and variable names should start with lowecase (Login should be called login).
Also, in the Login function, you are assigning the values of the url and login_route parameters to URL and LOGIN_ROUTE but they do not seem to serve for anything special. You could just use the function's parameters directly:
...
headers = {
 'User-Agent': '',
  'origin': url,
  'referer': url + login_route,
}
...
csrf_token = request_session.get(url).cookies['csrftoken']

Same goes for Page_URL in Scraper.
Moreover, return should be used as a statement, rather than with function notation:
def myFunction():
  return 0

Is better than:
def myFunction():
  return(0)

Readability
Lastly, I would say this assignment in Login is not quite readable:
msg = (
        f'You have logged in successfully {login_request.status_code}' if login_request.status_code == 200 else
        f'Error {login_request.status_code}'
    )

Language features are there for when they are useful, but readability is key and should be kept in mind. I would write that assignment as a simple if-else:
if login_request.status_code == 200:
  msg = f'You have logged in successfully {login_request.status_code}'
else:
  msg = f'Error {login_request.status_code}'


You are computing your prime sieve multiple times, when you only need to compute it once.  You are told you will have at most 10 test cases.  You could easily store those in an array, compute the maximum upper limit, and run the sieve once.  Then loop through the stored test cases, and generate the output for each.  Could be up to a 10x speed up.
The only even prime is 2.  Treat it as a special case.  Then, when you are running the sieve, you can start with 3 and increment with p += 2 to skip the even numbers.
Since the sieve has already eliminated all multiples of smaller prime numbers, when eliminating the multiples of p, you don’t have to start at p*2; rather you can start at p*p and skip the even multiples using i += p*2.  (Consider storing p2 = p*2 to avoid the multiplication every loop iteration!)
In segmentedsieve(), if the upper limit is less than largest prime your sieve produced, you don’t need to generate the second sieve; just emit the primes in the correct range.
You can apply points #2 & #3 to the secondary sieve, but it will be slightly more complicated as you need to ensure you’ve calculated an odd starting multiple.
To get a 8x reduction in memory usage, use a bit array.  (You could get a 16x reduction, by storing flags for only odd values in the bit array, but your indexing will become more complex.)


Convert a string in time format to minutes

The code is easy to understand, and it seems to produce the correct result.

A couple of things:

1)
The code for "AM" and "PM" are almost identical with the difference of 12 (the PM-addend). You should not repeat yourself.

2) You "split" the string three times: one for AM/PM, one for hours, and one for minutes. Instead you could use string[] parts = input.Split(':', ' '); to split to the useful parts in one operation.

3) You should maybe check the input for correct format and throw some meaningful exceptions in case of wrong format.

All in all my reviewed code would be something like:

int CalculateTimeInMinutes(string input)
{
  if (string.IsNullOrWhiteSpace(input))
    throw new ArgumentNullException(nameof(input));

  string[] parts = input.Split(':', ' ');

  if (parts.Length != 3)
    throw new ArgumentOutOfRangeException(nameof(input));

  if (parts[2].ToUpper() != "AM" && parts[2].ToUpper() != "PM")
    throw new ArgumentOutOfRangeException(nameof(input), "Missing AM/PM qualifier");

  if (!int.TryParse(parts[0], out int hours))
  {
    throw new ArgumentOutOfRangeException(nameof(input), "Invalid hours part.");
  }

  if (hours < 0 || hours > 12)
    throw new ArgumentOutOfRangeException(nameof(input), "Hours must be between 00 and 12 (inclusive)");

  // TODO: The same checks for minutes.
  int.TryParse(parts[1], out int minutes);

  int toPM = parts[2].ToUpper() == "PM" ? 12 : 0;
  int hoursInminutes = (toPM + (hours % 60)) * 60;
  int totalMinutes = hoursInminutes + minutes;
  return totalMinutes;
}

That said, there are well known objects and apis that can do the same operation in a few lines of codes:

int CalculateTimeInMinutes(string input)
{
  DateTime time = DateTime.Parse(input, new CultureInfo("en-US"));
  return (int)(time - time.Date).TotalMinutes;
}


Hexadecimal converter using a switch statement

A hash map is often a good idea for avoiding switch statements. It can be used in combination with the Strategy and Abstract Factory patterns, such as in these examples.

However, the Strategy Pattern is overkill for your problem. A simple hashmap would look like this

Map<Character, String> hexMap = new HashMap<Character, String>();
hexMap.put('\"', "\\22");
hexMap.put('\n', "\\20");
// puts more stuff in map...

 for (int i=0, n=node.length(); i<n; i++) {
     char c = node.charAt(i);
     buf.append(hexMap.get(c));
 }

But a quick googling of "java character to hexadecimal" produces these results. My favorite is

StringBuilder buf = new StringBuilder(node.length() + 8);

    for (int i = 0; i < node.length(); ++i) {
        char ch = node.charAt(i);
        buf.append(String.format("\\%1$x", (ch & 0xFFFF)));
    }

return buf.toString();

EDIT: Forgot to say, don't use magic numbers. I have no clue what the frack that 8 is doing in your program nor do I have to patience to try to deduce.


I'd do this instead:

function validateForm() {
    if (!isset($_POST['submitform']))
        return false; // Maybe $controller->error = "Something"; as well?
    $inputs = array (
        'username', 'email', 'password',
        'repassword', 'password_f', 'repassword_f',
        'display'
    );
    foreach ($inputs as $key)
        if (empty($_POST[$key]))
        {
            global $controller;
            $controller->error = "";
            return false;
        }
    return true;
}
...
if (valudateForm()) {
    echo 2;
} else {
    // Form data not ok
}

Seems cleaner, no flags, no counting array elements, validation has its own function,...


You're probably sick of having me answer your questions, but I couldn't help myself on this one!

Basically, yes this is safe. However, you never specified what you wanted to protect against, so I'm assuming you mean from just a normal person who might try a couple tricks on you!

But nothing is perfect, and I'll see what I can do to point that out...

First off, I don't understand your first line.

filter_input(INPUT_POST, "login", FILTER_UNSAFE_RAW)

Are you checking to see if a "login" was sent? Your filter (FILTER_UNSAFE_RAW) doesn't do anything to the string if you don't specify other filters:

  Do nothing, optionally strip or encode special characters.

So I'm assuming it's just a check to see if the correct POST is there? If that's the case, what's wrong with using $_POST['login']?
I think your $usercookie is considered to be a security aspect, no? Well according to the docs:

  This function does not create random nor unpredictable strings. This function must not be used for security purposes.

And from the mt_rand() page...

  This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.

And then a little bit further...

  If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

I think we all know what needs to be done here. (Get rid of of two functions you're using!)
Why are you not handling timestamps in $lastlogin instead of the database? The database has functionality meant for this. I believe you're using MySQL.
$session has the same security issue $usercookie had.
I would put all of these variables inside the first if.
For $username, I hope when someone registers, you alert them of the invalid characters that might be in their name. If you automatically strip them, they'll be very confused when the go to log in!
FILTER_UNSAFE_RAW does nothing to the $password. What's it point again?
I'm going to make an adjustment here:

    $login = $backend->execute();
}

if($login) {
    $_SESSION['loggedin'] = $session;
    $_SESSION['auth'] = $session;
    setcookie( 'wcxadmin', $usercookie, time()+3600);
    header('Location: index.php');
}
else {
    $_SESSION['errors'] = 'Incorrect Username or Password';
    header('Location: index.php');
}

And change all this to...

    if($backend->execute()) {
        // Sessions, cookie, and headers
    }
}
$_SESSION['errors'] = 'Incorrect Username or Password';
header('Location: index.php');

I think that makes the code more concise.
Will $_SESSION['loggedin'] ever be different than $_SESSION['auth']? You set them equal to each other, which I think could be avoided.
Your bind function looks fine, clean too.
Error checking seems fine too!

Good improvement though :)


Doing Copy+Paste in your IDE should raise a big red flag and then there should be a neural inhibitor that prevents your left hand from doing it, causing your right hand to move your mouse further down the module and then start typing Private Function...

Now the first thing you need to do before you write any code, is "What is it exactly that I need to be doing?" - don't think in terms of "well I need to loop all cells in that range and check if its value matches a certain specific string, then I need to do [xyz]"; rather, think at one or two levels of abstraction above that, like "well I need to copy all the rows with the same currency code to a new worksheet that's named after the currency code in question".

If I understand what you're doing, you could consider starting with something like this:

Private Function GetRowsForCurrency(ByVal SourceRange As Range, ByVal CurrencyName As String) As Range
    Dim Cell As Range
    Dim Result As New Range

    For Each Cell In SourceRange
        If Cell.Value = CurrencyName Then Set Result = Union(Result, Rows(Cell.Row))
    Next

    Set GetRowsForCurrency = Result
End Function

Then you want to select all these rows and copy them to a new worksheet that you name after the "currency name":

Private Sub CopyToNewWorksheet(ByVal SourceRange As Range, ByVal CurrencyName As String)
    Dim Result As Worksheet
    Set Result = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))
    Result.Name = CurrencyName
    SourceRange.EntireRow.Copy Result.Cells(5, 1) 'comment why (5,1) here
End Sub

Notice I'm using the Add function's return value, which represents the sheet that was added.

With a function to get the cells and a procedure to copy them to a new sheet, all that's left to do is to call them:

Set Bereich = Sheets("Tabelle1").Range("B2:B" & Cells(Rows.Count, 1).End(xlUp).Row)
CopyToNewWorksheet GetRowsForCurrency(Bereich, "EURUSD"), "EURUSD"
CopyToNewWorksheet GetRowsForCurrency(Bereich, "GBPUSD"), "GBPUSD"
CopyToNewWorksheet GetRowsForCurrency(Bereich, "AUDUSD"), "AUDUSD"
CopyToNewWorksheet GetRowsForCurrency(Bereich, "NZDUSD"), "NZDUSD"

Now this might be made cleaner if you defined and used constants instead of magic strings:

Const EURUSD As String = "EURUSD"
Const GBPUSD As String = "GBPUSD"
...

Couple points

NEVER call a procedure a() - give it a meaningful name that starts with a verb and that says what the code does. If you can't easily give it a name, it's probably doing too many things.
Indent your code properly: anything between XXXXX and End XXXXX should be 1 Tab further to the right. If your code starts to look like arrow code, you've got a code smell (follow that link!).
Those With blocks are absolutely useless - you're never using your with block variable, which means you've set an object reference for no reason.
If you feel the need to add a number at the end of a variable name, stop right there, take your hands off the keyboard and study what your code is doing that's redundant - refactor as needed.


C++ Wrapper and Correctly Disposing Unmanaged Resources using ArrayHandle

What don't you like about it? There's a very small space where a C++ exception could occur leaking the vector memory. If the ExrDepthMapExtractor or extractDepthMap throws, there's no way to clean the vector memory. You could just put something in the catch block.

You could memcpy the pixel memory from C++ to C# instead of looping. Or share memory the other direction, by pinning it and having the C++ side write into the provided memory. That's nice because it allows the garbage collector safely deal with the memory, but requires safeguards to prevent .NET from doing anything to the memory while C++ is using it.


Ranking lines of a file according to number of occurrences

"Cool" enough? It seems fine, if procedural. Depends what you mean by cool.

I might combine a few steps. I'd also refactor and not put everything into one method, since each separate "chunk" does very distinct, and different, things. Separation makes testing easier.

The below isn't necessarily any better (and the chunk that creates the report may actually be worse--I'm not sure; it'd be less efficient), but it provides some alternate avenues to explore further.

def get_log_lines name
  logfile = IO.readlines(name)
  logfile.collect { |l| l.gsub(/\n+/, "")}.reject { |l| l == "" }
end

def ranksystem
  loglines = get_log_lines "some_logfile.log"
  logcount = Hash[loglines.group_by {|l| l}.collect {|k, v| [v.size, k]}]
  i = 0
  logcount.keys.sort.reverse.collect { |n| i += 1; "Rank #{i}: #{n} (#{logcount[n]})" }.join("\n")
end


useToken

I don't really get your expected behavior from this method. You only retry when expired, what if an exception occured while not yet expired? Nothing happens, not even a log. The same with exceptions that occur when retryWhenTokenExpired is not set, the exception gets swallowed without any trace.

  catch (Exception e) {
    if (retryWhenTokenExpired && tokenExpired(e.getMessage())) {
        System.out.println("token expired, retry");
        resetToken();
        useToken(tokenConsumer, false);
    }
  }

I would make sure the following constraint is true: either a retry is performed or an exception is propagated up the stack. In addition, on expiration, reset the token when requested so. log is an abstraction of your System.out.println.

  catch (Exception e) {
    log("error using token: " + e.getMessage());
    if (!retryWhenTokenExpired) {
        throw e;
    }
    final boolean expired = tokenExpired(e.getMessage());
    if (expired) {
        log("token expired, retry");
        resetToken();
    }
    useToken(tokenConsumer, !expired);
  }


There’s actually quite a bit you can do to simplify the listener class, while at the same time making it easier and more flexible to use!
Let’s start with deleting the default constructor: you actually don’t need to do this. Classes get an automatically-generated default constructor only if there are no other constructors defined. But in your class, there is another constructor defined! So the default constructor is already deleted.
See for yourself! Try this:
// No constructors are defined, so the class gets a default constructor.
class foo {};

// A constructor is defined, so the default constructor is suppressed.
class bar
{
public:
    explicit bar(int) {}
};

// This will compile:
auto f = foo{};

// This will not:
//auto b1 = bar{};

// But of course, this will compile:
auto b2 = bar{42};

So right away, you can drop the line deleting the default constructor.
Now, this is not wrong:
void (*number_changed)(int old_number, int new_number);

void (*number_increased)(int increased_value);

That is indeed the correct way to have two data members that are function pointers.
However…
There is actually a better way:
std::function<void (int, int)> number_changed;
std::function<void (int)> number_increased;

The reason this is better is because std::function is a LOT more powerful than a function pointer. A function pointer only works for regular, free functions, class static functions, and lambdas with no captures.
But std::function works with literally anything that even remotely looks like a function. It works for all the same things a function pointer works for. But it also works for member functions, lambdas with captures (closures), general function objects, bound-argument functions, … and so on and so forth. Like, literally everything works.
For example:
class my_int_listener
{
public:
    void number_changed(int, int) { /* whatever you want */ }
    void number_increased(int) { /* whatever you want */ }

    // This class could have data members, a constructor... whatever
    // you want, and you can use all that stuff in your callbacks.
};

// Constructed however you want, wherever you want - global var, on the
// heap, whatever - just so long as it outlives integer.
auto mil = my_int_listener{};

auto integer = Integer{1};

using namespace std::placeholders;
integer.add_number_changed_listener(
    {
        std::bind(&my_int_listener::number_changed, &mil, _1),
        std::bind(&my_int_listener::number_increased, &mil, _1)
    }
);

The other benefit of std::function is the syntax is soooo much nicer. Function pointers are ghastly. Even when I’m forced to use them, I always use typedefs to hide the ugliness:
class IntegerListener {
public :
    using number_changed_function = void (*)(int, int);
    using number_increased_function = void (*)(int);

    number_changed_function number_changed = nullptr;
    number_increased_function number_increased = nullptr;

    IntegerListener(number_changed_function&& number_changed, number_increased_function&& number_increased) {
        this->number_changed = number_changed;
        this->number_increased = number_increased;
    }
};

That just looks a lot more like natural C++. And of course, with std::function:
class IntegerListener {
public :
    std::function<void (int, int)> number_changed = nullptr;
    std::function<void (int)> number_increased = nullptr;

    IntegerListener(std::function<void (int, int)>&& number_changed, std::function<void (int, int)>&& number_increased) {
        this->number_changed = number_changed;
        this->number_increased = number_increased;
    }
};

Although you could use typedefs there too, which is probably a good idea for avoiding needless repetition.
The one downside of using std::function over raw function pointers is that std::function objects are larger—sometimes quite a bit larger, in order to do the type erasure necessary to do all its tricks. But unless you want to accept the rather severe restrictions that raw function pointers come with, there’s no other option. (Well, there are other options, but they would require a redesign: you could, for example, you could use a polymorphic base class for your listeners, and use dynamic dispatch.)
Now let’s focus on that constructor:
IntegerListener(void (*&&number_changed)(int, int), void (*&&number_increased)(int)) {
    this->number_changed = number_changed;
    this->number_increased = number_increased;
}

I’m not sure why you’d want to use rvalue-references for your constructor parameters here. Did you try something and it would’t compile without them? I can’t see what purpose rvalue-referenes here serve, even theoretically.
The other thing is: when you’re initializing data members, you almost always want to use data member initializers, rather than initializing them in the constructor’s body.
This is probably more what you want:
IntegerListener(void (*number_changed)(int, int), void (*number_increased)(int)) :
    number_changed{number_changed},
    number_increased{number_increased}
{}

Or even more correctly:
IntegerListener(void (*number_changed)(int, int), void (*number_increased)(int)) :
    number_changed{std::move(number_changed)},
    number_increased{std::move(number_increased)}
{}

The moves are because there’s no need to copy the arguments from the function parameters to the data members (assuming you don’t want to use the function parameters again). Moving is more logically correct, and can be much faster (though it doesn’t matter here).
Finally, I can’t imagine any reason why this constructor couldn’t be noexcept. If all it’s doing is just taking the parameters and moving them into the data members, then so long as the moves are noexcept (which, moves should always be noexcept wherever possible, and they are both for raw function pointers and std::function), there’s no chance of failure.
So putting it altogether, if I were writing your listener class, I might do:
class IntegerListener
{
public:
    using number_changed_type = std::function<void (int, int)>;
    using number_increased_type = std::function<void (int)>;

    number_changed_type number_changed = nullptr;
    number_increased_type number_increased = nullptr;

    IntegerListener(
        number_changed_type number_changed,
        number_increased_type number_increased) noexcept :
            number_changed{std::move(number_changed)},
            number_increased{std::move(number_increased)}
    {}
};

Now on to the dispatcher….
std::vector<IntegerListener *> integer_listeners;

I don’t see any reason why you’d want to store pointers to the listeners, rather than just storing the listeners directly. You’re not doing dynamic dispatch (IntegerListener doesn’t have a virtual destructor), and there is no functional difference between storing the objects directly in the vector or storing them remotely. Using pointers for this just means poor performance due to the extra indirection and cache busting, and the need to manage memory, with no benefits.
In fact, as I pointed out in my other comment, what you’re doing is actually just storing the address of temporary objects, which immediately die, leaving you with dangling pointers. If you actually wanted to store pointers, you would have to either manually allocate those pointers (or use global or static objects, I guess)—which means you also have to manually manage that memory with custom copy constructors and a destructor—or (and, really, this is the only option in modern C++… do NOT try manually allocating and managing memory), use smart pointers.
But, as I said, there’s no benefit to using pointers at all, so there’s nothing to be gained from using smart pointers. Just store the objects in the vector directly. It’ll be faster, easier to code, and you won’t end up with critical bugs involving dangling pointers like the one you have (or leaks or double-frees or any of the other crap that comes with manual memory management… seriously do not do manual memory management in C++).
void set_number(int new_number) {
    for (IntegerListener *&integer_listener:integer_listeners) {
        (*integer_listener).number_changed(number, new_number);
    }
    if (new_number > number) {
        for (IntegerListener *&integer_listener:integer_listeners) {
            (*integer_listener).number_increased(new_number - number);
        }
    }
    number = new_number;
}

If you’re going to store pointers in your vectors, there’s really no reason to iterate through them by reference. In fact, you’re just paying for a double indirection which you don’t even use.
But! If you’re going to store the actual listeners in your vectors, then, yes, you should take them by reference… but you should really take them by const reference, because you’re not going to be modifying them.
I generally recommend to use the universal form of range-for. This:
for (auto&& item : range)

always works, for everything, and never does the wrong thing. It should be the default thing you write whenever you write a range-for.
(And no, it is NOT the same as doing for (IntegerListener&& item : range). That usually won’t work… and it won’t work for your case. It’s auto&& or it’s a craps shoot. Only auto&& always works.)
However… if you want to be more explicit about what your code is actually doing, you could do:
for (auto& item : range) // to signal you will be modifying the items
// or
for (auto const& item : range) // if you'll just be reading them

These don’t always work, but they almost always work, and if you really mean what they say—that you’re either modifying the items or you’re definitely not and you’re just inspecting them—then they pretty much always work.
So I’d probably write:
for (auto const& integer_listener : integer_listeners)
    integer_listener.number_changed(number, new_number);

unless I was feeling lazy, in which case I’d use the auto&& form.
void add_number_changed_listener(IntegerListener &&integer_listener) {
    integer_listeners.push_back(&integer_listener);
}

This is really the only broken function in the code. Everything else is correct, though maybe not the most efficient, and maybe not following C++ best practices or styles.
But this function has two problems. First, it takes the argument by rvalue reference. I can’t imagine why you’d want to do that. It doesn’t really make any sense. What you’re saying with that is that you only want to take temporary-constructed integer listeners. In other words, you’re saying:
// this is fine:
integer.add_number_changed_listener(IntegerListener{f1, f2});

// but this is absolutely wrong, and should not compile:
auto il = IntegerListener{f1, f2};
integer.add_number_changed_listener(il);

But why? What’s wrong with making an integer listener and passing it to two integers? Maybe I have two integers that I want to keep track of changes to. Why am I banned from using the same listener for both?
The second problem with this function is that you only take the address of the listener. Even if you weren’t requiring temporary-constructed listeners, that’s an accident waiting to happen, because even if the listener isn’t temporary—which means it’s very likely to die almost immediately—it still might not live long enough to still be active when the dispatcher wants to signal an event.
You have two options here:

either you mandate that users keep listener objects around for as long as needed, and make it their problem to keep track of that (which would be a terrible, bug-prone design); or
you simply keep the listener object with the dispatcher, so it has to stick around as long as the dispatch object exists.

In other words, don’t muck around with pointers and the address-of operator ('&'). Just do the natural thing:
void add_number_changed_listener(IntegerListener integer_listener) {
    integer_listeners.push_back(integer_listener);
}

And even better, and more technically correct: you don’t really want a copy of the listener stored in the vector… you want the actual listener object. So you want to move what you were given into the array:
void add_number_changed_listener(IntegerListener integer_listener) {
    integer_listeners.push_back(std::move(integer_listener));
}

Now as a user of the class, I have control. I get to decide if I want to give you a temporary-constructed listener, or if I want to copy a listener to multiple integers. And no matter what I choose, everything just works.
That’s it for the line-by-line review! Overall, the only “problem” with it that would make me reject it from a code base I was responsible for is that the vector integer_listeners holds pointers rather than actual objects, and those pointers are almost certainly going to be dangling because add_number_changed_listener() only takes temporaries. If you only made two changes:

change integer_listeners to be a std::vector<IntegerListener> (not std::vector<IntegerListener*>); and
change add_number_changed_listener() to store (by copying or—better—moving) the passed listener, not just its address

then I would consider the code acceptable. (Though, of course, there are a number of other improvements you could make, like using std::function rather than raw function pointers`.)
To answer your concerns:

The design is pretty optimal, yes. There are a few minor touch-ups here and there that make it even more efficient, but the basic design is sound. And, actually, it’s a pretty good design, in my opinion.
Is the design good C++? Yes, I think so. Even without the changes I suggested (other than fixing those critical bugs), I’d say it fits well with good C++ philosophy. There are other ways of doing it, of course, and every design has its pros and cons. But this design is, I think, quite good. I’d use it.


I cannot believe this went unanswered for 5 and a half years (I guess I can, it is a difficult question to answer) - I'm going to try to answer it from the respect of early 2012, and the respect of today (mid 2017).

2012

The biggest concern I see comes from this line:

AsyncManager.Parameters["result"] = WorkflowInvoker.Invoke(wf, arguments)["MvcOutput"] as IDefineMvcOutput;

I don't know how WorkflowInvoker works, but I assume that it has the capability of throwing an exception, which means that your AsyncManager.OutstandingOperations.Decrement(); line would not be reached, and I wonder what other issues that might cause for your application. (Looking for operations that aren't there, for example.) I would consider a try/finally block, or decrement before your operation gets invoked. (You can probably consider "In Progress" as a non-outstanding operation.)

The other issue I see with your Lambda method is regarding the idea of "closures", and captured variables. In .NET the wf and arguments variables are still part of the local method and are simply referring to the local copy, which means if you modify either variable after queuing up the worker, you could end up with a different result. This may not be an issue with your infrastructure, but I feel it's worth pointing out none-the-less.

2017

Let's fast-forward five years and six months (which is an agonizingly long time) and examine what language features might make this a different process. I'm just going to post the form that takes advantage of the new language features, then we'll discuss where async/await might help you.

[HttpPost]
public void ConfigureAsync(ConfigureExportInputModel inputModel)
{
    if (inputModel == null)
    {
        throw new ArgumentNullException("inputModel");
    }

    var arguments = new Dictionary<string, object> { [nameof(inputModel.ExportType)] = inputModel.ExportType };
    var wf = new ErrorHandledExportWorkflow();

    AsyncManager.OutstandingOperations.Increment();
    ThreadPool.QueueUserWorkItem(o =>
            {
                AsyncManager.Parameters["result"] = WorkflowInvoker.Invoke(wf, arguments)["MvcOutput"] as IDefineMvcOutput;
                AsyncManager.OutstandingOperations.Decrement();
            });
}

public ActionResult ConfigureCompleted(IDefineMvcOutput result) =>
    this.ActionResultFactory.Create(this, result);

So it doesn't look much different, but you can see that it's just a bit shorter. The expression-bodied method syntax, the dictionary initializer, and the nameof operator. But what really makes a difference is the async/await of the TPL. This starts making our code come alive.

With the proper implementation, you can leverage async/await to really bring a good flow to the asynchronous nature of your code. If properly implemented on the WorkflowInvoker.Invoke method, you might get away with something like:

[HttpPost]
public Task<ActionResult> RunAsync(ConfigureExportInputModel inputModel)
{
    if (inputModel == null)
    {
        throw new ArgumentNullException("inputModel");
    }

    var arguments = new Dictionary<string, object> { [nameof(inputModel.ExportType)] = inputModel.ExportType };
    var wf = new ErrorHandledExportWorkflow();

    var result = await WorkflowInvoker.InvokeAsync(wf, arguments);
    return this.ActionResultFactory.Create(this, result["MvcOutput"] as IDefineMvcOutput);
}

This would allow you to await the whole method, and return the thread to the pool until done. By leveraging what .NET built-in with C#5.0, you can write succinct asynchronous code that doesn't have to worry about the overhead of performing the async operations. The framework and language really take that burden away from you.

Of course, this expects an InvokeAsync method on the WorkflowInvoker, which may or may not exist, and as such this is pseudo-/hypothetical code, but the idea should remain the same. You can read the MSDN article for more explanation of what is possible with this design.


Updating entities with EF (Delete, Add, Update) with one method

You shouldn't expose entities in WCF service. Every change in entity will cause WCF webservice change and incompatibility for existing consumers. I would create decicated data transfer objects for WCF webservice and use library like Automapper to handle property mapping.

EF entities often contain various properties (example: creation date, creator info), that shouldn't be modified, but when you expose whole entities, you allow this, which in future may cause security issues.

Small example (without Automapper):

public class EventDTO
{
    public int Id { get; set; }
    public DateTime EventDate { get; set; }
    public string Title { get; set; }
}

In webservice class:

public Event UpdateEvent(Guid sessionID, EventDTO eventDTO)
{
    using (IFSDB ifsdb = new IFSDB())
    {
        var event = ifsdb.Events.First(item => item.Id == eventDTO.Id);
        event.EventDate = eventDTO.EventDate;
        event.Title = eventDTO.Title;
        ifsdb.SaveChanges();
    }
}


First, let's break some of the loop bodies out into their own functions. If you're having difficulty reasoning about the behavior of your code, then you can definitely afford the (theoretical) performance hit of a function call.

import numpy as np
import matplotlib.pyplot as plt

def check_every_box_is_occupied(boxes):
    for box in boxes:
        if box == 0:
            return False
    return True

def check_birthday_paradox(boxes):
    for box in boxes:
        if box >= 2:
            return True
    return False

def run_test(number_of_boxes):
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    result = {
        'balls_for_paradox': 0,
        'balls_for_full': 0,
    }
    while True:
        boxes[np.random.randint(number_of_boxes)] += 1
        if check_birthday_paradox(boxes):
            result['balls_for_paradox'] = number_of_balls
            break
        number_of_balls += 1
    number_of_balls = number_of_boxes
    boxes = np.array([0] * number_of_boxes)
    while True:
        boxes[np.random.randint(number_of_boxes)] += 1
        if check_every_box_is_occupied(boxes):
            result['balls_for_full'] = number_of_balls
            break
        number_of_balls += 1
    return result

def run_tests(number_of_boxes, number_of_tests):
    print(number_of_boxes)
    average_frequency_birthday_paradox = 0
    average_frequency_every_box_is_occupied = 0
    for index in range(number_of_tests):
        result = run_test(number_of_boxes)
        average_frequency_birthday_paradox += result['balls_for_paradox']
        average_frequency_every_box_is_occupied += result['balls_for_full']
    plt.rcParams.update({'font.size': 15})
    return {
        'average_frequency_birthday_paradox': average_frequency_birthday_paradox / number_of_tests,
        'average_frequency_every_box_is_occupied': average_frequency_every_box_is_occupied / number_of_tests,
    }

def main():
    number_of_tests = 250
    birthday_paradox_graph = [[], []]
    every_box_is_occupied_graph = [[], []]
    boxes_max_num = 1000
    for number_of_boxes in range(10, boxes_max_num + 1, 1):
        results = run_tests(number_of_boxes, number_of_tests)
        birthday_paradox_graph[0].append(number_of_boxes)
        birthday_paradox_graph[1].append(results['average_frequency_birthday_paradox'])
        every_box_is_occupied_graph[0].append(number_of_boxes)
        every_box_is_occupied_graph[1].append(results['average_frequency_every_box_is_occupied'])
    plt.figure(1)
    plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')
    plt.title("Conajmniej jedna urna ma conajmniej dwie kule")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.figure(2)
    plt.title("Wszystkie urny są zapełnione")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')
    plt.show()

if __name__ == '__main__':
    main()

The above is a pretty literal translation of your code. I introduced some dictionaries as return values; tuples would have worked but would have required some kind of documentation. Explicit classes would be more maintainable, but let's not worry about that for this project.

Next, I'm pretty sure you have a math error in your calculations of the "every box occupied" condition. The line where you reset number of balls should be resetting it to 1, right?
I'm also going to use explicit else statements in this round, because I think they look better.

def run_test(number_of_boxes):
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    result = {
        'balls_for_paradox': 0,
        'balls_for_full': 0,
    }
    while True:
        boxes[np.random.randint(number_of_boxes)] += 1
        if check_birthday_paradox(boxes):
            result['balls_for_paradox'] = number_of_balls
            break
        else:
            number_of_balls += 1
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    while True:
        boxes[np.random.randint(number_of_boxes)] += 1
        if check_every_box_is_occupied(boxes):
            result['balls_for_full'] = number_of_balls
            break
        else:
            number_of_balls += 1
    return result

Now we can implement Slothario's suggestion, but we'll have to rethink how we're running these tests. The birthday paradox is easy enough, but to avoid checking every cell for the "all occupied" condition, we need to remember cells we've already visited. We can think of this as crossing items off a list.

def run_test(number_of_boxes):
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    result = {
        'balls_for_paradox': 0,
        'balls_for_full': 0,
    }
    while True:
        box = np.random.randint(number_of_boxes)
        boxes[box] += 1
        if 2 <= boxes[box]:
            result['balls_for_paradox'] = number_of_balls
            break
        else:
            number_of_balls += 1
    number_of_balls = 1
    boxes = set(range(number_of_boxes))
    while True:
        box = np.random.randint(number_of_boxes)
        if box in boxes:
            boxes.remove(box)
        if not boxes:
            result['balls_for_full'] = number_of_balls
            break
        else:
            number_of_balls += 1
    return result

We have two similar loops. In a lot of contexts I would suggest that they're different enough that they should go in completely separate functions, but since we're going for speed, maybe we should combine them.

def run_test(number_of_boxes):
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    unoccupied_indexes = set(range(number_of_boxes))
    result = {
        'balls_for_paradox': 0,
        'balls_for_full': 0,
    }
    while not (result['balls_for_paradox'] and result['balls_for_full']):
        box = np.random.randint(number_of_boxes)
        if not result['balls_for_paradox']:
            boxes[box] += 1
            if 2 <= boxes[box]:
                result['balls_for_paradox'] = number_of_balls
        if not result['balls_for_full']:
            if box in unoccupied_indexes:
                unoccupied_indexes.remove(box)
                if not unoccupied_indexes:
                    result['balls_for_full'] = number_of_balls
        number_of_balls += 1
    return result

Let's tidy up some other little things. You had a call to set the font-size of your plot inside one of the loops, I don't think that belonged. I also removed a print statement, which takes up more time than you might think. I'm also replacing several of the loops with list comprehensions, which won't improve performance but it's a little nicer to read. We could go a lot further in this direction, but I wanted to keep the basic structure of your code intact.

import numpy as np
import matplotlib.pyplot as plt

def check_every_box_is_occupied(boxes):
    for box in boxes:
        if box == 0:
            return False
    return True

def check_birthday_paradox(boxes):
    for box in boxes:
        if box >= 2:
            return True
    return False

def run_test(number_of_boxes):
    number_of_balls = 1
    boxes = np.array([0] * number_of_boxes)
    unoccupied_indexes = set(range(number_of_boxes))
    result = {
        'balls_for_paradox': 0,
        'balls_for_full': 0,
    }
    while not (result['balls_for_paradox'] and result['balls_for_full']):
        box = np.random.randint(number_of_boxes)
        if not result['balls_for_paradox']:
            boxes[box] += 1
            if 2 <= boxes[box]:
                result['balls_for_paradox'] = number_of_balls
        if not result['balls_for_full']:
            if box in unoccupied_indexes:
                unoccupied_indexes.remove(box)
                if not unoccupied_indexes:
                    result['balls_for_full'] = number_of_balls
        number_of_balls += 1
    return result

def run_tests(number_of_boxes, number_of_tests):
    results = [run_test(number_of_boxes) for _ in range(number_of_tests)]
    return {
        'average_frequency_birthday_paradox': sum([r['balls_for_paradox'] for r in results]) / number_of_tests,
        'average_frequency_every_box_is_occupied': sum([r['balls_for_full'] for r in results]) / number_of_tests,
    }

def main():
    number_of_tests = 250
    boxes_max_num = 1000
    all_results = [{
                        'n': number_of_boxes,
                        'results': run_tests(number_of_boxes, number_of_tests)
                   }
                   for number_of_boxes
                   in range(10, boxes_max_num + 1, 1)]
    birthday_paradox_graph = [
        [r['n'] for r in all_results],
        [r['results']['average_frequency_birthday_paradox'] for r in all_results]
    ]
    every_box_is_occupied_graph = [
        [r['n'] for r in all_results],
        [r['results']['average_frequency_every_box_is_occupied'] for r in all_results]
    ]
    plt.rcParams.update({'font.size': 15})
    plt.figure(1)
    plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')
    plt.title("Conajmniej jedna urna ma conajmniej dwie kule")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.figure(2)
    plt.title("Wszystkie urny są zapełnione")
    plt.xlabel("Liczba urn")
    plt.ylabel("Średnia liczba kul potrzebna do spełnienia warunku")
    plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')
    plt.show()

if __name__ == '__main__':
    main()

*Runs in ...
my paitence ran out.
But if I follow Pelionrayz and use boxes_max_num=1000 and number_of_tests=1, then it takes about 7 seconds.

(just a heads up that I didn't test ever iteration of this; so i don't know if the earlier versions will actually run.)


Conditionally creating new variables for data manipulation

You can make a couple easy changes to improve readability. First, use with or transform so you don't have to carry a lot of iris$. Second, reorganize your logical tests so each nested ifelse appear in the "if-false" part of the previous ifelse, not in the "if-true" part. Hopefully, this will make sense:

iris$Speciec2 <- with(iris,
  ifelse(!Species %in% c("setosa", "virginica"), as.character(Species),
  ifelse(Sepal.Length < 5,                       "Species1",
  ifelse(Sepal.Length < 7,                       "Species2",
                                                 "Species3")))
)

I think it reads a lot easier this way, where each line contains a test and the output value if the test is passed. If the test fails, we move onto the next line. And at the end, the last line contains the value if all tests have failed. I also like this layout because it looks a lot like how you would nest Perl's ternary operator:

result = condition1 ? value_if_condition1_is_true
       : condition2 ? value_if_condition2_is_true
       : condition3 ? value_if_condition3_is_true
       :              value_if_condition3_is_false

Another solution would be to use the cut or findInterval functions to handle the conditions you have on Sepal.Length. These functions become really handy when you have many cases ("breaks") in mind, although here you only have three. You could do:

new_labels <- cut(iris$Sepal.Length, breaks = c(-Inf, 5, 7, +Inf),
                  labels = paste0("Species", 1:3), right = FALSE)
iris$Speciec2 <- with(iris, ifelse(Species %in% c("setosa", "virginica"),
                                   as.character(new_labels),
                                   as.character(Species)))

Now about performance, since you mentioned it. Know that ifelse and cut are vectorized functions so unless you are handling many millions of rows or doing some high frequency trading, you should be fine :-)

Minor speed improvements might be made by replacing the ifelse with in-place replacements (x[idx] <- value), I let you decide if this is more readable:

iris$Speciec2 <- with(iris, {
  res <- as.character(Species)
  need_change <- Species %in% c("setosa", "virginica")
  res[need_change & Sepal.Length < 5]                     <- "Species1"
  res[need_change & Sepal.Length >= 5 & Sepal.Length < 7] <- "Species2"
  res[need_change & Sepal.Length >= 7]                    <- "Species3"
  res
})

Finally, switching to a data.table (from the R package of the same name) is always recommended when dealing with large size data.frames and when speed is a concern.


The main issue I have with this code is that you're calling .timeout() on a Promise instance; by default, Promise doesn't support this - this is a Bluebird only operation.

This means that your returned Promise must evaluate true for Promise <: BluebirdPromise, which is not something that can be guaranteed in all environments (especially if you do what you've done here and omit the declaration for require('bluebird').

I'd prefer to see something like this:

const BluebirdPromise = require('bluebird');

return new BluebirdPromise(function (resolve, reject) {
  //resolve my API call here.
})
.timeout(15000)
.cancellable()
.catch(BluebirdPromise.CancellationError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task cancelled', error);
})
.catch(BluebirdPromise.TimeoutError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task timed out', error);
});

At the very least, this makes it clear that you aren't using the standard ES6 Promise, but that you're using a specific version from Bluebird.

I've not used the timeout and cancellable methods, so I can't speak for how you could code that better specifically, so there's probably more to say here.


Sticking with the approach you used how about this as an alternative.

public override void Load(string elementText)
    {
        var ele = XElement.Parse(elementText);

        var xElement = ele.Element("FunctionKeys");
        if (xElement != null && xElement.HasElements)
        {
            _dliUnit.FunctionKeyList.AddRange(xElement
                               .Descendants("Name")
                               .Select(x => EnumHelper.GetEnum<Keys>(x.Value))
                );
        }
    }

I created a little Enum Extensions class just because I like typing GetEnum:

public static class EnumHelper
{
    public static T GetEnum<T>(string name)
    {
        if (IsValidEnumFor<T>(name))
            return (T)Enum.Parse(typeof(T), name);
        else
            throw new ArgumentException(typeof(T) + "does not contain a value member = " + name);
    }

    public static T GetEnum<T>(int number)
    {
        if (Enum.IsDefined(typeof(T), number))
        {
            return (T)Enum.ToObject(typeof(T), number);
        }
        else
        {
            throw new ArgumentException(typeof(T) + "does not contain a value member = " + number.ToString());
        }
    }

    public static bool IsValidEnumFor<T>(string name)
    {
        return Enum.IsDefined(typeof(T), name);
    }
}

Alternative - XmlSerializer

One alternative I have used in the past to parse Xml into objects is the .NET XmlSerializer.  In your case you might do something like:

StringReader sr = new StringReader(xml);

// Create an XmlSerializer object to perform the deserialization
XmlSerializer xs = new XmlSerializer(typeof(DLIUnit));
return (DLIUnit)xs.Deserialize(sr);

This may not work for you but I would recommend having a look into this class as it is fairly easy to use once you get going.  Once I got my head around the basics it helped immensely.


Instability

while(i <= mid && j <= right)  result[k++] = (vec[i] < vec[j])? vec[i++] : vec[j++];

Whenever vec[i] == vec[j], the above excerpt from your code will favour the element from the right chunk, which reorders equal elements. Instead you should say:

while(i <= mid && j <= right)  result[k++] = (vec[i] <= vec[j])? vec[i++] : vec[j++];

or even:

while(i <= mid && j <= right)  result[k++] = (vec[j] < vec[i])? vec[j++] : vec[i++];

Misc 1

while(i <= mid)                result[k++] = vec[i++];
while(j <= right)              result[k++] = vec[j++];

You could use std::copy from algorithm header file to do the above; it might be (or might not) be optimized for speed.

Misc 2

Actually, there is std::merge in algorithm; why not use it?

API

At this point, your implementation is restricted to std::vector. It is not hard to make it accept any sequence:

template<typename RandIt1, typename RandIt2>
void mergeSort(RandIt1 source_begin,
               RandIt1 source_end,
               RandIt2 target_begin,
               RandIt2 target_end)
{
    auto range_length = std::distance(source_begin, source_end);

    if (range_length < 2)
    {
        return;
    }

    auto left_subrange_length = range_length >> 1;

    mergeSort(target_begin,
              target_begin + left_subrange_length,
              source_begin,
              source_begin + left_subrange_length);

    mergeSort(target_begin + left_subrange_length,
              target_end,
              source_begin + left_subrange_length,
              source_end);

    std::merge(source_begin,
               source_begin + left_subrange_length,
               source_begin + left_subrange_length,
               source_end,
               target_begin);
}

template<typename RandIt>
void mergeSort(RandIt begin, RandIt end)
{
    auto range_length = std::distance(begin, end);

    if (range_length < 2)
    {
        return;
    }

    using value_type = typename std::iterator_traits<RandIt>::value_type;
    std::vector<value_type> aux(begin, end);
    mergeSort(aux.begin(), aux.end(), begin, end);
}

template<typename T>
void mergeSort(std::vector<T>& vec)
{
    mergeSort(vec.begin(), vec.end());
}

Hope that helps.

Peformance

In this Gist you can get everything needed for a performance demonstration. I get the following figures:

OP mergeSort in 3511 milliseconds.
cr mergeSort in 1653 milliseconds.
stable_sort in 1332 milliseconds.
Algorithms agree: true

Space consideration

At any given instant, you have \$\Theta(N)\$ worth memory allocated. However, if you count all std::vector<T> result(size);, you will get \$\Theta(N \log N)\$ worth memory allocated.

You can do better. You can allocate a vector that is of the same length and content as the input vector. Then, you merge from one vector to another; and at the next recursion level you swap their roles and so on. That way, you can eliminate

for(k=0; k < size; k++)
{
    vec[left+k] = result[k];
}

in the merging function.

Suppose also that we are sorting 8 elements. At the very highest recursion level you allocate a vector of 8 elements. After that you visit both left and right subranges of length 4 elements each. That's 8 elements in vector(s) more. You continue the same argument until you reach the bottom recursion level. Since each level allocates \$N = 8\$ worth memory, and there is \$\Theta(\log N)\$ levels total, you get \$\Theta(N \log N)\$.


You could empower IEditableObject. Here is a good article. Approach described will allow your model to do not mix concerns - they use memento design pattern.

UPDATE: I do not feel right by copy-pasting that article, so I would still recommend to have a look at it. Quick test though might look like the following:

1) Download and reference BindingOriented.Adapters project in your WPF application.

2) Create model:

public class Contact
{
    public string Name { get; set; }
}

3) Create view model (I used MvvmLight for RelayCommand):

public class MainViewModel
{
    public MainViewModel()
    {
        Contact = new EditableAdapter<Contact>(new Contact() { Name="Dmitry" });
        OKCommand = new RelayCommand(() => Contact.EndEdit());
        CancelCommand = new RelayCommand(() => Contact.CancelEdit());
    }

    public EditableAdapter<Contact> Contact { get; }
    public ICommand OKCommand { get; }
    public ICommand CancelCommand { get; }
}

4) Update MainWindow to include:

<StackPanel>
    <StackPanel.DataContext>
        <vm:MainViewModel/>
    </StackPanel.DataContext>
    <TextBox Text="{Binding Contact.Name}"/>
    <Button Content="OK" Command="{Binding OKCommand}"/>
    <Button Content="Cancel" Command="{Binding CancelCommand}"/>
</StackPanel>

It works :)