Yes.  I would go one step further and declare your functions as private static final, if possible.  The combination of those three keywords means that the code would be unaffected by any instance variable, any superclass, or any subclass, and is also not callable by any code external to the class.  Therefore, the compiler has enough of a hint that it could decide to inline the entire function.

I would also rename evenNumber(int number) to isEven(int number).  There is a convention in Java that functions named isSomething() return a boolean and have no side effects.  Your function meets those criteria.

To generate a random even number, you could just take random.nextInt() & -2 to mask off the least significant digit.  That would be more efficient than looping, testing, and discarding.  In that case, the whole question about helper functions would be irrelevant.

It's bad practice to create a new instance of Random every time you want to generate one random number, though.  The pseudorandom number generator actually carries some state, even if you don't think of it that way.  You should therefore use a private static variable to store the Random object.


Stanford developing calculator iOS app assignment

I have never seen the Stanford class or this example before, so I might be mentioning stuff that hasn't been covered yet in the class...

Inappropriate use of IBActions:

Much like viewDidLoad() and family, @IBActions are for telling your class that something has happened, not for telling it to do things. As such, you should name such functions to remind yourself of this fact. Also, that's why you don't call them directly in code.

For example, your appendDigit function doesn't actually append a digit. Sometimes it ignores the value (if the "digit" is "." and the text already has a dot in it,) and sometimes it wipes out the text and replaces it with the digit. This method exists to let your class know that one of the number keys was tapped, so a better name would be something like @IBAction func tappedNumberButton(sender: UIButton)

All your code is in the view controller, there is no Model:

You are writing a calculator app, but there isn't any expressed concept of a Calculator in your code. I would expect to see some sort of calculator class that deals with numbers and manipulating them. Something that exists independent of the view controller and could be used as a component in other apps that need to handle calculation.

Having a separate Calculator class would also make your code amiable to automated tests.

You seem to have two distinct states in your system as evidenced by your userIsInTheMiddleOfTyping variable. It would be interesting if you actually expressed that in two different classes, but that might be overkill for this particular project.

Your indentation seems consistent, but your use of carnage return isn't. Sometimes you use two CRs.


While loop uses extra variables - can this be cleaned up?

Basically, this code controls everything except the body of the loop: initialization, increment, and destruction. This suggests that the actual while should be inside State.World.Looping, and it should take another parameter, an Action or equivalent delegate, which the caller should pass in. For instance, the call would be rewritten:

state.World.Looping(reqComponents, () =>
{
    TimerComponent timer = state.World.GetComponent(TimerComponent.Type);

    if (timer.IsActive)
    {
        timer.TimeLeft -= gameTime.ElapsedGameTime.TotalSeconds;

        if (timer.IsFinished)
        {
            timer.IsActive = false;
        }
    }
});

and Looping itself could be modified to:

public void Looping(ComponentType reqComponents, Action loopBody)
{
    if (!HasComponents(reqComponents))
    {
       return;
    }
    CurrentEntity = 0;

    do
    {
       loopBody();
    } while (++CurrentEntity != EntityCount - 1);
}

I think I got the number of iterations right but I'm not completely sure.


You inner loop contains:

int differnce = Math.abs(Arrays.stream(array, 0, i).sum() - Arrays.stream(array, i, array.length).sum());

That does (i-0) operations for first sum and (array.length-i) for second, for a total of array.length-i+i-0=array.length. As the size of input is n=array.length that really gives O(n*n). Replacing for-loops with Streams doesn't improve complexity, only hides it a bit.


Allocating matrices for in-place modification

Answering some of your questions...

  Is passing arrays to functions memory safe?

No, not really, but the C language offers no other approach, so you just have to be extra careful, since neither the compiler nor the runtime will alert you if you try to access invalid or out-of-bounds memory.

  I am allocating matrices on stack and passing them to function to modify in place. Is this a standard practice?

It can be, yes. If you prefer to have them modified in place, it is fine. Some libraries prefer to have separate input and output parameters, and that tends to produce cleaner code, but sometimes it's simpler to just modify in place. E.g.: It would be annoying to have, for instance, a "make identity" function in a matrix library take two parameters, like: matrix_identity(const mat* in, mat* out). Much more convenient to just write:

matrix_identity(&matrix);

However, for arithmetical operations it would be more natural to have inputs and outputs:

mat a = { ... };
mat b = { ... };
mat result;
matrix_multiply(&result, &a, &b); // result = a * b

As to allocating on the stack, leave that up to the user. Your code should only be concerned with pointers to objects, how that's allocated is up to the caller. Leave the option for both, since stack variables are cheap, but sometimes one might have to use the global heap to extend lifetime.

Other details about your code:

The error codes you're returning in each function are irrelevant, since every function always returns the same MT_OK, which means they could very well be void functions. You don't have to make all functions return an error code for the sake of uniformity. Save the error codes for functions that can actually fail for some reason.
Since C doesn't have any construct for scoping names (like modules/namespaces), it is common practice to prefix your function names with a pseudo namespace, to reduce the chance of collisions. You could maybe prefix your function names with mat4_, e.g.: mat4_ translate(), mat4_identity(), mat4_mult_vec4() etcetera.
Don't redefine PI risking using less precision than the actual supported. Most math.h implementations will have M_PI defined, which you can use. You may still provide a fallback if necessary, but default to M_PI:

#ifndef M_PI
  #define M_PI 3.14159265f
#endif // M_PI

Which matrix layout are you using? Column major, I suspect? State that very clearly somewhere, like in a documentation comment in the header file, to leave no room for confusion.


In general I'd say it's a good design. You use dependency injection and provide all required parameters via the constructor. You also use an abstraction (interface) for the service but... it's not very useful.

Why do you need an INotificationService? To be able to send notifications without knowing how they are going to be sent. You receive a notification-service and want to call the Notify method to send a notification. But do you want to repeatedly send the same notification? I don't think so. Thus the Notify method should probably require a message that you want to send.

I can imagine that such a service would have this API. You don't return bool but nothing if it worked and throw an exception if it didn't. If you don't throw exceptions then the user cannot know what went wrong if a service wasn't able to send a notification.

public interface INotificationService
{
    void Notify(string subject, string message);
}

Not all services may support a subject but a subject and a message are the two properties that actually every notification has.

Now the mail-service needs only the address (don't abbreviate names like adress):

public class MailService : INotificationService
{
    readonly string _address;

    public MailService(string address)
    {
        _address = address;
    }

    public void Notify(string subject, string message)
    {
        // send notification
    }
}

The sms-service requires only the phone number and the sms-sender:

public class SmsService : INotificationService
{
    readonly string _phoneNumber;
    readonly ISmsSender sender;
    public SmsService(string phone, ISmsSender sender)
    {
        _PhoneNumber = phone;
        _sender = sender;
    }

    public void Notify(string subject, string message)
    {
        // send notification
    }
}

var smsNotification = new SmsService("12346789", "content" ,new SmsSender());

You shouldn't mix the vocabulary. If you create a SmsService then the instance is a smsService and not a smsNotification although in this case it is technically a notification because it can only send a single message over and over again. If this is the desired behavior then you shouldn't call it an INotificationService but an INotification. The names need to be clear otherwise the usage of your API is very confusing.

Ok, with the new design both services can still send messages but you can send a new message each time instead creating a new instance just to send a new message - so they are now real notification-services and not just notifications.

var smsService = new SmsService("12346789", new SmsSender());
smsService.Notify("Test1", "This is a message");
smsService.Notify("Test2", "This is another message");


The ResourceManager class
You should probably use a std::unordered_map<> (from the <unordered_map> header) instead of a std::map, since resources don't really need to be ordered as far as I can see. This will give you some speed, even if you're not concerned by that.
Consider throwing an exception from the getResource() function if the dynamic_cast<> fails. Right now, it is up the caller to check that the returned pointer is not null, it might be better if the function simply throws an exception so that client code does not have to wrap every single call with a check.
This is up to you, since now the client might have to wrap calls in try-catches. However, it certainly makes errors pop up a lot more visibly and at the call location, instead of possibly later if the client forgets to check for null.
The addResource implementation
You never check that resource is not null, which a pointer can be. Consider checking or taking a Resource& instead to ensure that you are operating on an existing value.
Your insertion into the map looks like this:
mResources.insert(std::pair<std::string, Resource*>(name, resource));

std::map<> and std::unordered_map<> both have the emplace() member function. The function takes the arguments to construct the key-value-pair internally (thus avoiding copy/move operations). You can instead write your return statement like so:
mResources.emplace(name, resource);

This looks cleaner and is more efficient.

Be careful with your map, I don't know what unload resource does, but it better call delete if that's (dynamically) how you're allocating your resources. However, a better idea might instead to use std::unique_ptr<> with a custom deleter. Here's a mock implementation:
#include <iostream>
#include <memory>

struct resource
{
    void unload_resource() { std::cout << "unloaded\n"; }
};

struct resource_free
{
    void operator()(resource* r)
    {
        r->unload_resource();
        delete r;
    }
};

int main()
{
    std::unique_ptr<resource, resource_free> pres{ new resource };
}

This will simplify the implementation of the destructor as std::unique_ptr<> takes care of properly releasing your resource. You can make an alias for ease of use: using resource_ptr = std::unique_ptr<...>. This allows you to write your map variable declaration in an easier to read way:
std::unordered_map<std::string, resource_ptr> mResources;


Counting valleys traversed below sea level, given elevation changes

There's nothing wrong with or "not functional" about your approach. This might be opinion territory, but personally I would consider using foldLeft as it might be more readable and you can potentially eliminate some of the complexity of your cases.

(also I got rid of n here as it is completely irrelevant, I know it's a problem from a website so you have to follow the format they gave you)

def countingValleys (steps: String): Int = steps
  .foldLeft((0, 0)) {
    case ((valleys, elevation), 'D') => (valleys, elevation - 1)
    case ((valleys, -1), 'U') => (valleys + 1, 0)
    case ((valleys, elevation), _) => (valleys, elevation + 1)
  }
  ._1


Very unorthodox placement of if-else clauses in C for handling special cases

I would say that the strong argument against the first example is that the else block starts right below the if and can be confused with a then block at first sight.
It's not about the order of the clauses, but only about formatting.
This is has the same condition and clauses, but it's not ambiguous:
if( i >= list->count )
    *result = 0;
else
{
    *result = i * 32 + 31;
    while( mask >> (*result % 32) ) (*result)--;
}

That said, I would personally prefer this formatting (though this second rewrite is less important and more subjective than the previous one):
if( i >= list->count )
    *result = 0;
else {
    *result = i * 32 + 31;
    while( mask >> (*result % 32) )
        (*result)--;
}


Since there aren't any loops in your code that aren't waiting for the user to provide some input, it's probably way premature to talk about efficiency. Is your code measurably slow? Does it leave you hanging? If not, unless you have an unusual need, save questions on efficiency for later.

So let's talk about some more important things: readability and maintainability. Here are some tips on ways to improve the readability and maintainability of your code. These aren't hard rules that you should never break (especially the one on comments); they are guidelines on ways to make your life easier that you should learn to bend when the guideline makes things awkward instead.

I hope this helps, even though it may be a lot to take in all at once. Feel free to ask follow-up questions and get other opinions.

Avoid Redundancy

Redundancy can show up in many forms. One example of it is in your declaration of arrays, using code like int betType[11] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1};. Unless there's something very special about the number 11, there's no reason to call it out. Instead just say int betType[] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1}; which will automatically determine the size of the array for you.

When you later check your bounds with while (betChoice < 1 || betChoice > 11) {, you can instead use a calculated size (_countof(betType) or sizeof(betType)/sizeof(betType[0])), or even use a std::vector<int> instead of an int[], and check against the vector's size().

This will help you avoid magic numbers that don't mean much later. After all, if someone asks you what's special about 11, would you think it's the number of available bet types? But if they asked what betTypes.size() meant, it would be easy to answer.

Another way redundancy shows up is in large blocks of repeating code. For instance, case 1 and case 2 have almost the same code. In fact I had to read it a couple times to find the part that was different. Sometimes this can be best handled by refactoring similar parts of code into functions, and passing parameters to them that control how they differ. Sometimes it's better just to extract the parts that are identical into simpler functions, and use them. I'll touch on this more below, but I certainly don't have the answer.

Avoid Obfuscation

In the code commented Displays a large dollar sign, there are a lot of casts from int to char so that cout prints the value as a character. But the characters in question are not that unusual. Just use the actual character you want to show, for example replacing

cout << endl << "       " << (char)36 << (char)36 << (char)36 << (char)36 << (char)36;

with

cout << endl << "       $$$$$"

This will not only be easier to type or update, it will be easier to read.

Avoid Comments

This recommendation is somewhat controversial, but it begins to target your question about functions. Instead of commenting what a line of code does, comment how a block of code does something unusual. When you're first starting out, everything seems unusual, but eventually you will see patterns and only need to comment on things that are not common patterns.

But then, instead of commenting what a block of code does, give it a name instead by putting it in a function. For example, you have several cases where you ask how much the user wants to bet on a number, then loop until they enter a valid number. You could extract this loop into a helper function like this:

int getBetAmount(int bankAccount)
{
    int betAmount;
    cin >> betAmount;
    while (betAmount < 1 || betAmount > bankAccount)
    {
        cout << endl << "You have $" << bankAccount << " in your bank account: $";
        cin >> betAmount;
    }
    return betAmount;
}

int _tmain() {
    : : :
    case 1:
        : : :
        cout << endl << "How much would you like to bet on the number" << betNumber << "? $";
        betAmount = getBetAmount(bankAccount);
        : : :
    : : :
    case 2:
        : : :
        cout << endl << "How much would you like to bet on the numbers" << betNumber << " and " << betNumber + 3 << "? $";
        betAmount = getBetAmount(bankAccount);
        : : :
}

Find some other code that doesn't change much and extract that into functions as well. For example, the code commented Checks if player won or lost their bet, I see creating a function you'd call like this:

case 1:
    : : :
    bankAccout = awardWinnings(betNumber == randomNumber, betAmount, betOdds, bankAccount);
    break;
case 2:
    : : :
    bankAccount = awardWinnings(betNumber == randomNumber || betNumber + 3 == randomNumber, betAmount, betOdds, bankAccount);
    break;

After you make these changes, ideally the parts that are different will start to stand out, and the parts that are the same will have good names that tell you what they do even if they don't have a comment. And then you can more easily avoid incorrect comments like case 2's Check if number is valid (between 1 and 36) that actually checks for 33.

You can also avoid comments by naming constants. Instead of starting with int bankAccount = 500 and then 500 lines later referencing 500 to figure out your overall winnings, perhaps declare const int StartingBankAccount = 500; and use the name instead of the number in both places. If you decide to change the initial account wealth, this also helps ensure your ending summary remains correct.

Avoid Bad Dice

While this is a toy program, and a person is unlikely to play long enough for it to matter, rand() % max is a flawed approach to generating random numbers. It's flawed in ways too subtle for me to explain (I understand it, but not well enough to explain it). However Stephan T. Lavavej knows it much better and explains it in a video called rand() Considered Harmful; watch it and use the approach he recommends if you want a more uniformly distributed random number.


I'm a little worried about your gsubs, but assuming this is what you want to do:

def replace_and_wrap(str)
  return nil if str.nil?
  %Q{'#{str.gsub(/\r\n?/, "").gsub(";","','")}'}
end

ots = replace_and_wrap(params["ot_code"])
multiple_circuit = replace_and_wrap(params["circuit_id_multiple"])
multiple_element_code = replace_and_wrap(params["multiple_element_code"])

Note that this changes the behavior of your code slightly: variables (like ots) are set to nil if the param is nil, rather than remaining undefined. Depending on how you are using these variables, this behavior is probably better anyway.


If I redraw it, It become a bit laggy.

In my tests, using createImageData and putImageData to fill the individual pixels ran about 3x faster than rect and fill.

You can replace this code:

GAContext.beginPath();
GAContext.fillStyle = "rgb(" + rG + ", " + gG + ", " + bG + ")";
GAContext.rect(xColor, yColor, 1, 1);
GAContext.fill();

With this:

pixelData[0] = rG;
pixelData[1] = gG;
pixelData[2] = bG;
GAContext.putImageData(pixel, xColor, yColor);

And before the loop, add this:

var pixel = GAContext.createImageData(1, 1);
var pixelData = pixel.data;
pixelData[3] = 255;

Test it out here. This Stack Overflow question is relevant. You may also be able to figure out a clever way to do this with gradients that would be much faster.


Avoid the object/array check and treat the return value the same way with JavaScript spread operator?

Object.assign && Array.flat
By the first example which does not have any type checking makes the throwing of errors in the second two examples look superfluous, a little over kill.
As the function Array.isArray is the more concise statement over the always ugly object test typeof obj === "Object && obj !== null you can use a simple ternary to call the correct function
You can use Object.assign rather than the long and slow object by object reduce method to merge objects.
And for the array Array.push, then Array.flat(1) depth of 1 for the arrays. To ensure you do not effect the input array first you would also need to copy it to a new array
Examples.
const merge = (first, ...rest) => {
    const arrays = (arr) => (arr.push(...rest), arr.flat(1));
    const objects = () => Object.assign({}, first,  ...rest);
    return Array.isArray(first) ? arrays([[...first]]) : objects();
}

Or a shortened form
const merge = (first, ...rest) => {
    return Array.isArray(first) ?
         (first = [[...first]], first.push(...rest), first.flat(1)) :
         Object.assign({}, first,  ...rest);
}

Update
Fixed bug as pointed out in comments.
From the same comment by ScottyJamison in which is presented an even better solution, using the rest operator on all the arguments resulting in...
const merge = (...items) => Array.isArray(items[0]) ?
    items.flat(1) :
    Object.assign({}, ...items);

or
const merge = (...items) => Array.isArray(items[0]) ? items.flat(1) : Object.assign({}, ...items);


Speed up computation on lists of lists in R (scalability issues)

You have two lapply calls in there, so essentially two hidden for loops contributing to the slow execution.

Here, one way to tap into faster compiled functions is to rely on the data.table package for merging (a.k.a. a database join) your two data sets.

First, we turn your two lists into two data.tables:

idx1 <- rep(seq_along(source.list), lengths(source.list))
idx2 <- rep(seq_along(target.list), lengths(target.list))

library(data.table)
X <- data.table(id = unlist(source.list), idx1 = idx1,
                pos = seq_along(idx1), key = "id")
Y <- data.table(id = unlist(target.list), idx2 = idx2, key = "id")

where idx1 and idx2 are the variables telling us in which element of source.list and target.list a specific item (id) belongs. Also pos is just a temporary row number we will use later to sort the data back, as the next statement below (the merge) shuffles things around:

Z <- Y[X, allow.cartesian=TRUE]
Z <- Z[order(Z$pos)]

At this point, if it's possible for you, I would recommend you stop here. By that, I mean to make the next steps of your analysis use this Z data.table rather than a nested list, as to avoid further slow processing loops (for/lapply/Map/etc.). However, if you really need the nested list output, you can do:

no_name_split <- function(...) unname(split(...))
gp1 <- factor(Z$idx1, seq_along(source.list))
gp2 <- factor(Z$idx2, seq_along(target.list))

res <- Map(no_name_split, no_name_split(Z$id, gp1),
                          no_name_split(gp2,  gp1))

Below is a simulation with a larger dataset, comparing computation times and checking that the results are identical:

set.seed(632)
source.list <- replicate(500, sample(100000, 1000), simplify = FALSE)
target.list <- replicate(555, sample(100000, 1055), simplify = FALSE)

system.time({
  idx1 <- rep(seq_along(source.list), lengths(source.list))
  idx2 <- rep(seq_along(target.list), lengths(target.list))

  library(data.table)
  X <- data.table(id = unlist(source.list), idx1 = idx1,
                  pos = seq_along(idx1), key = "id")
  Y <- data.table(id = unlist(target.list), idx2 = idx2, key = "id")
  Z <- Y[X, allow.cartesian = TRUE]
  Z <- Z[order(Z$pos)]

  no_name_split <- function(...) unname(split(...))
  gp1 <- factor(Z$idx1, seq_along(source.list))
  gp2 <- factor(Z$idx2, seq_along(target.list))
  res <- Map(no_name_split, no_name_split(Z$id, gp1),
                            no_name_split(gp2,  gp1))
})
#    user  system elapsed
#   3.394   0.382   3.646

system.time({
  result <- lapply(X = source.list, FUN = map.partition.R,
                   partitionlist = target.list)
})
#    user  system elapsed
#  23.943   5.329  36.999

identical(res, result)
# [1] TRUE


Vertically and horizontally center these HTML elements

You can simplify your HTML to this:

Title

$message

By adding classes, you can re-use CSS on more than one HTML element. The class floaters is applied to both of the divs that make up the top line. The class right is only applied to the left div on the first line to make it right aligned.

The #parent:after is one example of a clearfix. There are several other versions of clearfixes.

* {
    box-sizing: border-box;
}
#parent {
    margin: 0px auto;
    width: 50%;
    border-radius: 6px;
    border: 1px solid #CFCFCF;
}
#parent:after {
  content: "";
  display: table;
  clear: both;
}
.floaters {
    float: left;
    background-color:#E4E4E4;
    width: 50%;
    height: 3em;
    padding: 5px 12px 5px 0;
}
.right {
    text-align: right;
}
.centerme {
    float: left;
    clear: both;
    text-align: center;
    background-color:#EFEFEF;
    height: 3em;
    width: 100%;
    padding-top: 12px;
}

I have a working jsfiddle for you to look at.


Seemingly redundant conditionals...or not?

You have 3 different role values and 1 for not assigning anything, so you'll somehow need 4 discrete values to differentiate. But you could rewrite as:

if (isManager)
    Role = hasBackendAccess ? "FullAccess" : "Manager";
else if (hasBackendAccess)
    Role = "LimitedBackend";


Don't print anything or call die() from this class because it may breaks caller's code/page. For example, you may want to show customized error page when error occurs, but all text printed by your code will break and stops this. One point is return boolean, as already said. But I personally prefer using exceptions for that (and even more -- I create special excepton which extends standard Exception class. This approach allows to differentiate one exception from another.).
Get rid of chained method calls. Don't call verifyDatabaseConnection() from verifyNullFields(), verifyDatabaseExist() from verifyDatabaseConnection() and so on. Your method should do only one thing as declared in their name.
Rename data member to something more meaningful.
At your opinion: you may replace $this->user == NULL) check to is_null($this->user)
Also, when you will need to create similar class for PostgreSQL database (or abother DB) you should extract base class


Well, first you should create your own class for matrices. Your current ad-hoc representation is inefficient and lacks abstraction.
Options include:

Row-major or column-major.
Restricted to specific dimensions / square matrices.
Using an array of pointers to rows/colums or explicit mapping of coordinates to ids.

Is there a reason you insist that the result-matrix should be square? Seems gratuitious.
There's no advantage to modifying the first input instead of returning a new matrix. So, make both arguments constant and return the result instead.
If you don't need an object any longer after copying it, might moving be more appropriate, as it's potentially more efficient and less likely to throw?


Creating List of String elements that occur a certain amount of times using only the List ADT

This is more of a hint but unfortunately I cannot comment on your post.

As greybeard already mentioned, you could sort the List and then count the elements with equal firstName. A representation of the sorted List may give you an idea how to implement this:

List("Alice A", "Alice B", "Alice C", "Brian A", "Brian B", "Jason A", "Jason B", "Jason C", ...)

Another solution is to use a Collection that counts equal entries.

This Collection implementation is often available as Bag. This is unfortunately not included in the Java standard library, but implementations are available in Apache Commons. Note that you have to transform the List of firstName + lastName to a list that only contains the firstName. You can use a Transformer also available in Apache Commons that strips the lastName (the values of the resulting List will then be lazy evaluated).


Haskell 99, Problems 1-10 (simple list processing)

Solutions 1 and 2 are fine.

Solution 3: Find the Kth element of a list

The error message for 3 is a bit misleading: you can also get the error if the requested index is beyond the end of the list.  Strictly speaking, it should be an error to request a non-positive index as well.

Solution 4: Find the number of elements of a list

You should not need a helper function.

myLength :: [a] -> Int
myLength [] = 0
myLength (x:xs) = 1 + myLength xs

However, as @Franky points out, using a helper function can make it tail-recursive.

Solution 5: Reverse a list

You could write it as myReverse (x:xs) = (myReverse xs) ++ x, but it is much more efficient the way you wrote it using a helper function.  The helper should be scoped using a where clause (or let … in, which does the same thing).  It is customary to name trivial helper functions using the myReverse' convention.

myReverse :: [a] -> [a]
myReverse xs = myReverse' xs []
  where
    myReverse' []     rev = rev
    myReverse' (x:xs) rev = myReverse' xs (x:rev)

Solution 7: Flatten a nested list structure.

No helper is necessary.

data NestedList a = Elem a | List [NestedList a]

flatten :: NestedList a -> [a]
flatten (Elem x)      = [x]
flatten (List [])     = []
flatten (List (x:xs)) = flatten x ++ flatten (List xs)

Solution 8: Eliminate consecutive duplicated list elements

Again, no helper or accumulator is necessary.  Furthermore, you should avoid ++, as it works by inefficiently walking to the end of its LHS argument.

compress :: Eq a => [a] -> [a]
compress []     = []
compress (x:[]) = [x]
compress (x:y:zs)
  | x == y      = compress (y:zs)
  | otherwise   = x : compress (y:zs)

Problem 9: Pack consecutive duplicates of list elements into sublists

I don't think that packing an empty list should be an error.  Rather it should just return an empty list.

My advice is similar to the above.  I think that a helper function is needed, but not in that way.

pack :: Eq a => [a] -> [[a]]
pack [] = []
pack (x:xs) = pack' [x] xs
  where
    pack' run []  = [run]
    pack' run@(r:_) (x:xs)
      | x == r    = pack' (x:run) xs
      | otherwise = run : pack' [x] xs

Problem 10: Run-length encoding of a list

Again, I don't think that encoding an empty list should be an error.

The implementation would read more nicely, in my opinion, using a list comprehension and better naming.

encode :: Eq a => [a] -> [(Int, a)]
encode xs = [(length run, head run) | run <- pack xs]

In summary, accumulators are sometimes the right approach (as in myReverse), but often they are harmful.  Before using one, think hard about whether it is necessary and efficient.


More idiomatic way to move item from one dict value(list) to another?

I would propose something like so (given that you have assumed no dupes, etc)

function migrateValues(obj, srcKey, destKey, value) {
    return {
        ...obj,
        [srcKey]: obj[srcKey].filter(w => w !== value),
        [destKey]: obj[destKey].concat(value)
    };
}

We spread obj, and then overwrite the srcKey and destKey properties.

There are several reasonable ways to make obj[srcKey].filter and obj[destKey].concat avoid TypeErrors, which is best is dependent on what you have planned for the function.


Need help with valid knight moves in Chess

First of all, a function called GetValidKnightSquares shouldn't be translating chessboard locations. Any code that performs a distinct operation and can be named should be extracted into its own function. It makes everything much easier to read and understand. Name things.

Second, I would probably leverage whatever data structure you choose for your board to determine the valid moves on that board. The structure I'm going to choose looks like this:

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, "8a", "8b", "8c", "8d", "8e", "8f", "8g", "8h", -1,
-1, "7a", "7b", "7c", "7d", "7e", "7f", "7g", "7h", -1,
-1, "6a", "6b", "6c", "6d", "6e", "6f", "6g", "6h", -1,
-1, "5a", "5b", "5c", "5d", "5e", "5f", "5g", "5h", -1,
-1, "4a", "4b", "4c", "4d", "4e", "4f", "4g", "4h", -1,
-1, "3a", "3b", "3c", "3d", "3e", "3f", "3g", "3h", -1,
-1, "2a", "2b", "2c", "2d", "2e", "2f", "2g", "2h", -1,
-1, "1a", "1b", "1c", "1d", "1e", "1f", "1g", "1h", -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1

It's a one-dimensional array that represents the ranks and files of the  two-dimensional board. The negative ones are there to pad the board and make it easier to detect when a piece has moved out of play. (We'll see this later.) This type of data structure is called a Mailbox (because some old-timer thought it looked like one, I guess) and it's very common in chess programming.

Here's how to generate it:

// converts an index in the mailbox into its corresponding value in algebraic notation
function i2an($i) {
    $files = "abcdefgh";
    return 10 - floor($i / 10) . $files[($i % 10) - 1];
}

function generateEmptyBoard() {
    $row = array();
    for($i = 0; $i < 120; $i++) {
        $row[] = ($i < 20 || $i > 100 || !($i % 10) || $i % 10 == 9)
            ? -1
            : i2an($i);
    }
    return $row;
}

This gives us the array we saw above. All that's left is to use it:

function knightMoves($square, $board) {
    $i = an2i($square);
    $moves = array();
    foreach(array(8, -8, 12, -12, 19, -19, 21, -21) as $offset) {
        $move = $board[$i + $offset];
        if ($move != -1) {
            $moves[] = $move;
        }
    }
    return $moves;
}

// converts a position in algebraic notation into its location in the mailbox
function an2i($square) {
    return (10 - $square[0]) * 10 + strpos("abcdefgh", $square[1]) + 1;
}

Notice that the mailbox's borders make it very easy to tell when we've moved to a position off the board.

Here are some examples:

$board = generateEmptyBoard();
print_r(knightMoves("1h", $board));
print_r(knightMoves("5b", $board));
print_r(knightMoves("6c", $board));

Output:

$ php knights.php
Array
(
    [0] => 2f
    [1] => 3g
)
Array
(
    [0] => 6d
    [1] => 4d
    [2] => 3a
    [3] => 7c
    [4] => 3c
    [5] => 7a
)
Array
(
    [0] => 5a
    [1] => 7e
    [2] => 5e
    [3] => 7a
    [4] => 4b
    [5] => 8d
    [6] => 4d
    [7] => 8b
)

What's cool is that you can use this mailbox throughout your entire application by substituting some representation of actual pieces for the location names in the inner elements. It's useful for more than just your narrow problem, in other words.


I'm assuming you have some way to handle other image formats, like .bmp or .gif; if not to actually handle them, at least a way to tell the user "this service does not support that image type" or something of the sort.

public Object getAsObject(FacesContext arg0, UIComponent arg1, String urlStr) {

Looks like you've got some overhead in there, you don't use the arg0 or arg1, why are they in here? Why is your method name getAsObject when instead you're doing something like downloadImageFromUrlToBase64?

If your framework is troubling you like this, consider putting the actual work in a separate class or function and having a simple method that only passes what you need. That way you're less attached to the framework which you are not using.

String extension = urlStr.substring(urlStr.lastIndexOf(".")+1);

Here you have a bug; if I pass "jpeg" in here, you say 'the last index of "." is non-existent, so the return value will be -1, add one, is 0'. Meaning we substring from the start of the string, returning the full string.

You'll silently swallow the resulting MalformedURLException, so if there is going to be any feedback to the user, it's going to be along the lines of "something went wrong".

            final URL url = new URL(urlStr);
            final HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

            // I'm not sure I should be doing that here
            BufferedImage image = ImageIO.read(connection.getInputStream());

            urlImage.setBuffImg(image);

            connection.disconnect();

Here you indeed have the option of moving this to a separate method. I think it would help.

private BufferedImage downloadImageFromUrl(String url){ ... }

String str;

os = new ByteArrayOutputStream();
ImageIO.write(image, extension, Base64.getEncoder().wrap(os));
str =  os.toString(StandardCharsets.ISO_8859_1.name());

This looks like it has seen some heavy editing. There's a variable str declared, but oh wait, gotta do something else first, namely filling the buffer, and only then can we put it in the string. There's also a double space between the = and os.toString, which means (to me) that you should probably run your autoformatter more often or configure it to fix double spaces like that.

Anyway, there's no need to create a local variable before you're going to use it in this case, so just reorder the statements:

os = new ByteArrayOutputStream();
ImageIO.write(image, extension, Base64.getEncoder().wrap(os));
String str = os.toString(StandardCharsets.ISO_8859_1.name());

And give the local a better name too, I almost thought you were appending 'ISO_8859_1' to your urlImage.

os = new ByteArrayOutputStream();
ImageIO.write(image, extension, Base64.getEncoder().wrap(os));
String imageInBase64 = os.toString(StandardCharsets.ISO_8859_1.name());

Lastly, I don't know what you're doing with that user-agent string, but I don't think you're 4 browsers at once and it probably needs a comment.


Sort data from a text file in descending order using quick sort

tl; dr

Use sorted(lines, key=itemgetter(3), reverse=True) instead of your custom function. This is both faster, more efficient, easier to read and easily understood by anyone.

Style

Your variable names doesn't convey much meaning. I don't get what the d in d_val can mean (data ?). In general, abreviations put unnecessary mental burden on the reader so avoid them. Do not hesitate to use more intermediate variable also as you can both:

cache reused values;
name your object and thus document your algorithm a bit more.

My take on this would be:

def quick_sort(values):
    if len(values) < 2:
        return values

    pivot, *values = values  # Python 3 syntax, use `pivot, values = values[0], values[1:]` on Python 2
    lower = [x for x in values if x < pivot]
    upper = [x for x in values if x >= pivot]
    return quick_sort(lower) + [pivot] + quick_sort(upper)

Performances

Each time you call qsort, you’re building 5 new lists: two for the intermediate values and one for the returned value plus 2 for each d_val[1:]. This quintuple the amount of memory needed by quick_sort call. Luckily for you, these are shallow copies which means inner lists are not copied, only their reference count increases.

Speed

Creating all these lists means a lot of allocations and/or copies happening under the hood, which slows down the whole thing. A simple sort of 2500 values timed using the following code:

from operator import itemgetter
import timeit

def qsort(d_val):
    if len(d_val) <= 1:
        return d_val
    return qsort([lt for lt in d_val[1:] if lt < d_val[0]]) + d_val[0:1] + \
           qsort([ge for ge in d_val[1:] if ge >= d_val[0]])

def qsort_test_case(l):
    return qsort(l)

def sorted_test_case(l):
    return sorted(l, key=itemgetter(3), reverse=True)

def generate_data():
    data = '''ascon1 201707011 John 77.5 11.5 11.5 11.5
ascon1 201707012 Grld 70.0 11.5 11.5 11.5
ascon1 201707013 Josh 79.5 11.5 11.5 11.5
ascon1 201707014 Jess 67.5 11.5 11.5 11.5
ascon1 201707015 Jack 97.5 11.5 11.5 11.5'''
    data = '\n'.join(data for _ in range(500))
    for line in data.splitlines():
        name, date, n, d1, d2, d3, d4 = line.split()
        yield name, date, n, float(d1), float(d2), float(d3), float(d4)

def main():
    print(timeit.timeit('test(l)', setup='from __main__ import generate_data, qsort_test_case as test; l = list(generate_data())', number=100))
    print(timeit.timeit('test(l)', setup='from __main__ import generate_data, sorted_test_case as test; l = list(generate_data())', number=100))

if __name__ == '__main__':
    main()

Yields a runtime of 18.58127073900141 seconds for your quick sort versus 0.03511061900098866 seconds for sorted. 530 times slower, I guess quick sort is not the right name there.

Alternate approach

Instead of creating intermediate lists, you could have an helper function that sort in-place but accept start and stop indices as arguments; and the recursive call will only change these values. This means you'll have to wrap the first call in a function that will perform a copy of the original list, call this helper to sort the copy in-place, and return the copy; leaving the original list untouched.

The advantage of this approach is that you can now use any iterable as input, not necessarily lists:

def quick_sort(iterable):
    result = list(iterable)
    _quick_sort(result, 0, len(result) - 1)
    return result

def _quick_sort(values, begin, end):
    if end <= begin:
        return
    # TODO: implement quick sort using swaps

Genericity

Your qsort function does not sort the array the same way than the sorted call in your original code. This is due to the fact that each item will sorted according to its first element then second if it compares equal (then third…) in your implementation (implicit rule for list comparisons); whereas you are using itemgetter(3) in the sorted call to compare only the fourth element.

Adding this kind of genericity to your quick sort will cost you time, impair readability and understanding of the code and can become error-prone at some point. Whereas when using sorted you don't have to worry about this kind of details that comes for free.


Efficient ways of looking for start-key and processing data

Still problematic
The code still has the following issues:

newVal is set but not used:

    while(value == 97 && counter < 3)

should be:
    while(newVal == 97 && counter < 3)

Assuming the byte stream follows the protocol, address() will eat the first byte of the message.  In other words, the byte following the 97 97 97 header will be discarded.  This will in turn cause the message processor to eat one byte of the next address section.

There is no recovery mechanism for if the byte stream stops following the protocol.  The address() function doesn't look for a header, it just returns in the absence of a header.

Rewrite
I suggest this rewrite:
void loop(void)
{
    // Check if data is available in serial buffer
    while (RX.available()) {
        // Search for start key
        FindStartKey();
        // Process data
        for(int i = 0; i < 68; i++)
            processBytes(RX.read());
    }
}

void FindStartKey(void)
{
    int counter = 0;

    do {
        if (RX.read() == 97)
            counter++;
        else
            counter = 0;
    } while (counter < 3);
}


nginx serve static - images, js, css and proxy node.js server

This makes sense to me. You can add a few more directives, though.

In-memory caching of file metadata

Nginx has an in-memory cache for file metadata, which can improve performance. Here's a sample config:

open_file_cache max=10000 inactive=120s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

Sendfile

Nginx supports the syscall sendfile, which, as I understand, can directly spit bytes on disk into the network, without intermediary reading into ram, which is obviously faster. Here's an article about sendfile and co, and a basic config:

sendfile on;
tcp_nodelay on;
tcp_nopush on;

events

Outside of the server {} block, there are a few settings you can configure.

epoll on linux; if you're on a different OS consult the manual
multi_accept is generally recommended, and causes the worker process to accept as many connections as possible.

Here's a config:

worker_processes auto;

events {
  use epoll;
  multi_accept on;
}

I'd recommend looking further into things, for example by searching "nginx static performance" or similar, there are many articles. These are what show up from the top of my head. I don't see anything wrong with your config as a base, though.


Out parameters in C++

In C++, you should almost never use out parameters (variables taken by reference and used to return a value from a function), you can read this excellent article by Eric Niebler. There are few cases where out parameters can make sense:

When you want your return to be fast. And even then, return value optimization and move semantics may still be faster.
When you have several output values. For example, you want to assign a value to a function and return whether it succeeded:

bool assign(int from, int& to)
{
    if (from != 0)
    {
        to = from;
        return true;
    }
    return false;
}

But even for this situation, there are better solutions such as boost:optional to return both a value and whether it succeeded or not. And if you need several error values, use exceptions. And if you need to actually return several values, you general want to pack them into a dedicated struct or a std::tuple.
Input-output parameters: sometimes, you want to take a parameter, read from it, and then write to it again. That is still a valid use case (but these are not strict out parameters anymore).

In your case, it seems that getSanitizedDouble could simply return the read long double instead of having an out parameter.

Type correctness

You could improve your type correctness:

That's also a naming issue: I don't expect a function named getSanaitzeDouble to return a long double, but to return a double.
The literal used in the expression long double pi = 0.; is incorrect: 0. is a double. The correct long double literal should be 0.0L. We could also use 0.0l, but the l suffix is really too close to 1 not to be dangerous.

Order your includes

Alphabetical order is something you should always use to order your headers (at least in a logical group of headers). That allows a faster search to check whether some headers has already been included:

#include <cctype>
#include <cmath>
#include <iostream>
#include <limits>


It is difficult to judge without full code, but while keeping things mutable (please use a more descriptive names, a future you will thank you):

public class StatusModel
{
    public IndividualStatus Status { get; set; }
    public int StatusId { get => (int)Status; set => Status = (IndividualStatus)value; }
    public bool InProgressStatus => Status == IndividualStatus.InProgress;
    public bool SubmittedStatus => Status == IndividualStatus.Submitted;
    public bool DisqualifiedStatus => Status == IndividualStatus.Disqualified;
    public bool DisqualifiedOrSubmittedStatus => DisqualifiedStatus || SubmittedStatus;
    public bool JustFinished(StatusModel stored) =>
          stored.InProgressStatus && DisqualifiedOrSubmittedStatus;
    public bool JustSubmitted(StatusModel stored) =>
        JustFinished(stored) && SubmittedStatus;
    public bool StillInProgress(StatusModel stored) =>
        !JustFinished(stored) && !DisqualifiedStatus;
}

As a next step you could also define an implicit conversion operators from/to int/enum types and make this class immutable.

public class StatusModel
{
    public static implicit operator StatusModel(IndividualStatus status) => new StatusModel(status);
    public static implicit operator IndividualStatus(StatusModel model) => model.Status;
    public static implicit operator StatusModel(int id) => (IndividualStatus)id;
    public static implicit operator int(StatusModel model) => (int)model.Status;
    StatusModel(IndividualStatus status) => Status = status;
    public IndividualStatus Status { get; set; }
    public bool InProgressStatus => Status == IndividualStatus.InProgress;
    public bool SubmittedStatus => Status == IndividualStatus.Submitted;
    public bool DisqualifiedStatus => Status == IndividualStatus.Disqualified;
    public bool DisqualifiedOrSubmittedStatus => DisqualifiedStatus || SubmittedStatus;
    public bool JustFinished(StatusModel stored) =>
          stored.InProgressStatus && DisqualifiedOrSubmittedStatus;
    public bool JustSubmitted(StatusModel stored) =>
        JustFinished(stored) && SubmittedStatus;
    public bool StillInProgress(StatusModel stored) =>
        !JustFinished(stored) && !DisqualifiedStatus;
}

It is a bunch of code (C# is a ridiculously verbose language), but it would be very easy to have more logic here, adding anything status related would be a very cheap operation.

private void HandleStatusChanges(
    Models.Database.Individual storedIndividual,
    ref Models.Domain.IndividualDm individual)
{
    if (individual.Status.JustFinished(storedIndividual.Status))
        SetFinishedIndividualFormValues(ref individual);
    if (individual.Status.JustSubmitted(storedIndividual.Status))
        SendSubmittedFileEmail(individual);
    if (individual.Status.StillInProgress(storedIndividual.Status))
        SendStatusChange(individual);
}

I would also define and associate custom JsonConverter and TypeConverter with StatusModel, so it will look like a status integer ID for asp.net (see an example here).

P.S. Generally speaking, data entity types should never be visible in the business core:
https://blog.cleancoder.com/uncle-bob/2016/01/04/ALittleArchitecture.html


The way you implemented escaping some symbols, running eval, and finally restoring the escaped symbols, looks fine.

Have you escaped everything to make this safe?
That's hard to tell.
And will it be future-proof?
Now that's impossible to tell.
You just cannot know if a future version of Bash will introduce something that should be escaped and leave your script vulnerable until patched.
That's unlikely for sure, but this is an ugliness that any blacklisting approach cannot escape.

Most importantly, do you really need this? (As @200_success pointed out in a comment.)
It seems you don't.
If you need to parse key=value pairs from a config file,
then I suggest to do just that,
implement just enough parsing that you need.
The solution will be specialized for the specific use case,
but that will make it safe, and free of any present or future problems with eval.


Display resources for each factory in the Rocket Valley Tycoon

I would turn this into one class that takes a list of ingredients and cost tuples. The resulting object can be added with another of its instance or multiplied with a number.

from collections import defaultdict

class Ingredient:

    def __init__(self, *ingredients):
        self.d = defaultdict(int)
        if len(ingredients) == 1 and isinstance(ingredients[0], str):
            # special case for base ingredients
            self.d[ingredients[0]] = 1
        else:
            for ingredient, amount in ingredients:
                self.d[ingredient] += amount

    @property
    def ingredients(self):
        return list(self.d.keys())

    @property
    def amounts(self):
        return list(self.d.values())

    def __rmul__(self, other):
         # allows doing other * self, where other is a number
        return Ingredient(*zip(self.ingredients, [other * x for x in self.amounts]))

    def __add__(self, other):
        # allows self + other, where other is another Ingredient
        return Ingredient(*zip(self.ingredients + other.ingredients,
                               self.amounts + other.amounts))

    def __str__(self):
        return str(list(self.d.items()))

Then you can define the base items and any derived item is just algebraic manipulations:

coal = Ingredient("Coal")
water = Ingredient("Water")
copper_ore = Ingredient("Copper Ore")
carbon = 2 * water + 4 * coal
copper_plates = 20 * copper_ore + 10 * carbon
print(copper_plates)
# [('Copper Ore', 20), ('Water', 20), ('Coal', 40)]


Class to help dealing with files, with lazy properties

In Python it's conventional to use a single underscore to indicate that a method is only for internal use (see PEP8). The double underscore is intended to solve a particular problem, namely avoiding conflict with a method of the same name in another class, when the classes are combined via inheritance. Since you don't have to worry about that problem here, you don't need the double underscore.
In Python 2.6 or later, a simple way to avoid magic numbers would be to make a collections.namedtuple:

from collections import namedtuple

MimeTypeAndEncoding = namedtuple('MimeTypeAndEncoding', 'type encoding')

and then in _mime_type_and_encoding write:

return MimeTypeAndEncoding(*MimeTypes().guess_type(self.abspath))

and in mime_type:

return self._mime_type_and_encoding.type

But this won't work for you because you are stuck on 2.5. But you could do much the same thing (if a bit more long-windedly) using a class:

class MimeTypeAndEncoding(object):
    def __init__(self, type, encoding):
        self.type = type
        self.encoding = encoding

In Python 3.2 or later you could implement lazy_property like this, using functools.lru_cache:

from functools import lru_cache

def lazy_property(method):
    "Decorator for a property that caches the result of the first call."
    return property(lru_cache(1)(method))

(This won't work for you because you're stuck on Python 2.5, but I think it's neat.)


I'd recommend against using ALL_CAPS for class-names. It's not really in accordance with C++ conventions.

template<size_t n, size_t r>
struct IS_SQUARE {
   static const bool value = IF<n == r*r,
                true,
                IF<GREATER<n, r*r>::ret,
                   IS_SQUARE<n, r+1>::value,
                   false>::ret
                >::ret;
};

You can replace the outer if with || (if foo then true else bar is equivalent to foo || bar) here to get rid of one level of nesting and simplify the condition a bit. One might think that you can also replace the inner if with &&, but that won't work because template-instantiation doesn't short-circuit in the way you'd want it to when using logical operators (i.e. foo && Bar<baz> will try to instantiate Bar<baz> even if foo is false, leading to infinite recursion in this case).

template<size_t n>
struct SQUARE {
   static const bool value = IS_SQUARE<n, 1>::value;
};

You might want to use 0 instead of 1 as the starting value here. Otherwise you'll get incorrect results for n=0 (which is a square of itself and should thus return true).

template<>
struct SQUARE<1> {
   static const bool value = true;
};

This is redundant because IS_SQUARE<1, 1> (or IS_SQUARE<1,0>) is true anyway.

Apart from the nitpicks listed above, your code looks fine (or as fine as TMP code ever looks, anyway). However it can be completely replaced using constexpr, which still gives you compile-time evaluation (including the ability to use the result inside template arguments or static_assert), while being greatly more readable:

The beauty of C++11's constexpr feature is that it allows you to write compile-time expressions using normal C++ syntax, instead of encoding everything using template classes. You're not allowed to use loops or any side-effects, so you still have to use the recursive approach you used (as opposed to the iterative approach you'd probably use at run-time), but it can be greatly simplified by expressing it as a simple recursive function instead of a bunch of templates:

constexpr bool is_square(size_t n, size_t r=0) {
    return (r*r == n)  ||  ( (r*r < n) && is_square(n, r+1));
}

int main() {
    static_assert(is_square(1), "must be square");
    static_assert(is_square(4), "must be square");
    static_assert(is_square(5), "must be square"); // compile error
}

As a learning-exercise for template meta programming this version is completely useless, of course, as it does not actually contain any templates. But it's definitely more readable (and more writable as well) and can be used in any scenario where the template-version can be used. So in any real C++11 meta-programming project, I'd always recommend using constexpr over templates when it's possible. This way you can perform your calculations in functions that look like C++ functions (well, C++ functions that are written in a surprisingly functional style) and use templates to define classes (which depend on the results of those calculations).


My little attempt basically takes items that are repeated and puts them into their own separate conf files and just include them into the main conf files. On my servers, I structure them as such:

global
    include1.conf
    include2.conf
    include3.conf
sites-available
    site1.conf
    site2.conf

And the includes are included in the SA conf files. Not good for performance, but negligible.

Anyways, here's an idea:

upstream upgrade-release{
    server 127.0.0.1:8000;
}

upstream upgrade-staging{
    server 127.0.0.1:8010;
}

server {
    listen 80;
    server_name www.upgrade.sg upgrade.sg;

    access_log  /var/log/nginx/upgrade.access.log;
    error_log   /var/log/nginx/upgrade.error.log;

    root /home/upgrade/npcec/release/src/npcec;

    include media_static.conf;

    location /robots.txt {
        alias /home/upgrade/npcec/release/src/npcec/static/robots.txt;
        access_log off;
    }

    location /favicon.ico {
        alias /home/upgrade/npcec/release/src/npcec/static/favicon.ico;
        expires max;
        access_log off;
    }

    location / {
        include proxy.conf;
        proxy_pass http://upgrade-release;
    }
}

server {
    listen 80;
    server_name staging.upgrade.sg;

    access_log  /var/log/nginx/upgrade.access.log;
    error_log   /var/log/nginx/upgrade.error.log;

    root /home/upgrade/npcec/staging/src/npcec;

    include media_static.conf;

    location /robots.txt {
        alias /home/upgrade/npcec/staging/src/npcec/static/robots.txt;
        access_log off;
    }

    location /favicon.ico {
        alias /home/upgrade/npcec/staging/src/npcec/static/favicon.ico;
        expires max;
        access_log off;
    }

    location / {
        include proxy.conf;
        proxy_pass http://upgrade-staging;
    }
}

In media_static.conf:

location /media/ {
    expires max;
    access_log off;
}

location /static/ {
    expires max;
    access_log off;
}

In proxy.conf:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;

Also, instead of proxy_pass http:// perhaps consider using proxy_pass $scheme. Perhaps someone with more experience with Nginx confs will follow up with a way to store certain bits and pieces in variables or will offer a better solution than mine (I for one would love to know a better way of doing things)


measuring the time taken to copy a std stl container

First regarding the correct approach.

printf usage: My output of hash for every case after 200000 trials was always 85899345920000, which is incorrect - due to wrong printf specifiers  - "%c;%d;%d;%lu;%llu\n". Correct ones are  "%c;%d;%d;%lld;%lld\n" if you declare totalTime and hash as long long. Why not use cout i wonder?
Using float for division results. Then again after fixing this in some cases of a small container with few elements i've kept getting totalTime = 0. Thats not good, so you'd want to use a floating variable to store the duration divided by NUM_OF_TRIALS. Otherwise the precision is reduced due to implicit conversion of the division result to integer.
Preparing for measurement. Also as this part goes:

T container;
container.reserve(NUM_OF_ELEMENTS);
for (int i=0;i<NUM_OF_ELEMENTS;i++)
{
    container.push_back(*(new NonPrimitiveType<OBJECT_SIZE>));
}

You're just wasting time here by searching memory to reallocate. Since stl container call default ctor your above code could be replaced with:

T container(NUM_OF_ELEMENTS);

And this will save you lots of time for redundant calls to new here.
sizeof(int) == 4 is true only generally. Use int32_t which gives that guarantee, and then OBJECT_SIZE/4 makes sense. Or better yet divide OBJECT_SIZE by sizeof(int32_t). That way nothing is going to surprise you in the future.
I'd also avoid calling every test together:

copyContainer<vector<NonPrimitiveType<16>>, 16>();
copyContainer<vector<NonPrimitiveType<64>>, 64>();
copyContainer<vector<NonPrimitiveType<256>>, 256>();
copyContainer<vector<NonPrimitiveType<1024>>, 1024>();
copyContainer<vector<NonPrimitiveType<4096>>, 4096>();

Make a switch statement and call only one of them per run, so as to avoid compiler further optimizing the switches between those statements.
If you turn off optimization flags, then you'll get quite an interesting picture of what's happening but your insights wont be applicable once the optimizations kick in. I think its true that measuring timings without optimization flags set to true is quite pointless.

Your code with -O3 optimization:

auto begin = chrono::high_resolution_clock::now();
for (int i=0;i<NUM_OF_TRIALS;i++)
{
    T copy = container;
    hash = hash + copy.at(0).x[1];
}
auto end = chrono::high_resolution_clock::now();

transforms to:

92 [2]      for (int i=0;i<NUM_OF_TRIALS;i++)
0x407d06  <+0x0046>        85 c0                    test   eax,eax
0x407d08  <+0x0048>        0f 8e 02 02 00 00        jle    0x407f10 <copyContainer<std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > >, 16u>()+592>
0x407d0e  <+0x004e>        31 f6                    xor    esi,esi
0x407d10  <+0x0050>        c7 45 c8 00 00 00 00     mov    DWORD PTR [ebp-0x38],0x0
0x407d17  <+0x0057>        c7 45 cc 00 00 00 00     mov    DWORD PTR [ebp-0x34],0x0
0x407d1e  <+0x005e>        66 90                    xchg   ax,ax
95 [1]          hash = hash + copy.at(0).x[1];
0x407daa  <+0x00ea>        8b 43 04                 mov    eax,DWORD PTR [ebx+0x4]
0x407db0  <+0x00f0>        99                       cdq
0x407db1  <+0x00f1>        01 45 c8                 add    DWORD PTR [ebp-0x38],eax
0x407db4  <+0x00f4>        11 55 cc                 adc    DWORD PTR [ebp-0x34],edx
92 [3]      for (int i=0;i<NUM_OF_TRIALS;i++)
0x407db7  <+0x00f7>        83 c6 01                 add    esi,0x1
0x407dbf  <+0x00ff>        39 35 3c f0 40 00        cmp    DWORD PTR ds:0x40f03c,esi
0x407dc5  <+0x0105>        0f 8f 55 ff ff ff        jg     0x407d20 <copyContainer<std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > >, 16u>()+96>
97 [1]      auto end = chrono::high_resolution_clock::now();

So - you're correct that compiler optimizes out the actual copy and leaves the sequential increment of  hash by 1 up to NUM_OF_TRIALS times.

Now, when you write  T copy = container; in a loop you're actually calling Ctor of T, copy assignment operator of T, copy ctor, and then dtor. Then loop counter increments and again 4 calls. Also since nothing is happening to 'T copy', you're getting the same address on the stack reused for the copy and have the stack top pointer moving up and down, while the memory for the elements of the container on the heap also get reused.

If you declare a set outside the loop:

unordered_set<int *> vAddr;//(NUM_OF_TRIALS + 1);
vAddr.insert(&(container[0].x[1]));

and inside the loop add vAddr.insert(&(copy[0].x[1])); then by calling vAddr.size() after the loop you should get the actual number of distinct memory location used by first element. Answer is 2. One for container and one for copy.

In a real life application you'd probably copy the container and let it be consumed by some other function, meaning that a call to T copy = container would probably have to allocate a new space for copy's elements on the heap. So while moving the stack pointer up down is a single instruction, what can become a bottleneck is allocating new memory on the heap.

So with this in mind, if you provide a copy ctor that wont really help measuring imo. I'd try to narrow down your request. What do you actually want to measure? Copy of arrays with dtor? Without dtor? Memory reallocation on the heap?

If you declare T copy outside the loop

T copy;
auto begin = chrono::high_resolution_clock::now();
for (int i=0;i<NUM_OF_TRIALS;i++)
{
    /*T*/ copy = container;
}

then your code with -O3 flag produces the following disassembly:

96 [1]      auto begin = chrono::high_resolution_clock::now();
0x407c11  <+0x0091>        e8 7a 9a ff ff           call   0x401690 <_ZNSt6chrono3_V212system_clock3nowEv>
0x407c16  <+0x0096>        89 c6                    mov    esi,eax
        97 [2]      for (int i=0;i<NUM_OF_TRIALS;i++)
0x407c18  <+0x0098>        a1 3c e0 40 00           mov    eax,ds:0x40e03c
        96 [2]      auto begin = chrono::high_resolution_clock::now();
0x407c1d  <+0x009d>        89 d7                    mov    edi,edx
        97 [3]      for (int i=0;i<NUM_OF_TRIALS;i++)
0x407c1f  <+0x009f>        85 c0                    test   eax,eax
0x407c21  <+0x00a1>        7e 1c                    jle    0x407c3f <copyContainer<std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > >, 16u>()+191>
        99 [1]          /*T*/ copy = container;
0x407c23  <+0x00a3>        8d 45 d0                 lea    eax,[ebp-0x30]
0x407c26  <+0x00a6>        8d 4d dc                 lea    ecx,[ebp-0x24]
0x407c29  <+0x00a9>        89 04 24                 mov    DWORD PTR [esp],eax
0x407c2c  <+0x00ac>        e8 8f 07 00 00           call   0x4083c0 <std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > >::operator=(std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > > const&)>
0x407c31  <+0x00b1>        83 ec 04                 sub    esp,0x4
        97 [4]      for (int i=0;i<NUM_OF_TRIALS;i++)
0x407c34  <+0x00b4>        83 c3 01                 add    ebx,0x1
0x407c37  <+0x00b7>        39 1d 3c e0 40 00        cmp    DWORD PTR ds:0x40e03c,ebx
0x407c3d  <+0x00bd>        7f e4                    jg     0x407c23 <copyContainer<std::vector<NonPrimitiveType<16u>, std::allocator<NonPrimitiveType<16u> > >, 16u>()+163>
        103 [1]     auto end = chrono::high_resolution_clock::now();

It calls the copy assignment operator and copy ctor without dtor. And you're spared the calls to .at operator and incrementation of hash. Though even if you leave it the timings will be quite close. Such alteration seems more or less close to your broadly stated purpose.


I do not know Ruby, but from my Python knowledge, it is not good to use eval in a real program.  When you use eval, it executes the code directly, so accidental/experimental input can have unwanted results, or even destroy the system.  Also, this has the potential for a hacker who has limited access to the system to run this program and do whatever they want as long as they have access to it, instead of cracking in deeper and doing whatever they are trying to do.

See this question for a detail discussion about eval in Ruby.

This question is about python, but also has good points.


Sum the remainders of ai%aj given an array "a"

A drop in the bucket – but it will increase the performance a little bit at least.

Use foreach instead of for

foreach is faster than a for-loop. So using foreach-loops will decrease the computing time for large inputs. It will also make your function a bit easier, as you don't have to create the $len-variable:

function sumOfRemainders($numbers) {
    $sum = 0;

    if (1 === count($numbers)) {
        return 0;
    }

    foreach ($numbers as $a)
        foreach ($numbers as $b)
            $sum += $a % $b;

    return $sum;
}

Now, for a single run on a small input like your example [2, 5, 3, 3, 5] the difference is neglectable.

However, here a a few benchmarks, when running with large input arrays:

 1000 values  |  original:  0.16s  |  new:  0.08s
 7000 values  |  original:  7.05s  |  new:  4.46s
10000 values  |  original: 14.70s  |  new:  8.84s
20000 values  |  original: 58.67s  |  new: 35.91s

The tests where run with MAMP's PHP 7.2.1 on the CLI on a i7 2.5GHz with 16 GB RAM.

Here are both versions running 5000 values on 3v4l.org:

Original
New version

Unfortunately you can't run more then 5000 values before running into their time limit.

Here's the original script I used for the benchmark.

Basically this is a variant of the Cartesian product. Here's a short read about Efficient Cartesian Product algorithm on Stackoverflow.


You have a URL endpoint with a numeric parameter to retrieve an asset and generate a PDF report. But the parameter is not validated. Django will ensure that the value is numeric, thanks to the way you defined the endpoint, but the asset might not exist.
When a nonexistent asset is requested, the program will crash.

Since kwargs is a parameter of get_context_data, it would be better to access it directly, rather than through self.kwargs.

Since Django ensures that the pk parameter exists, you can write simpler like this:

pk = kwargs['pk']


I am concerned that you are not digesting the advice given in previous reviews, because you are ONLY to call htmlspecialchars() just before you print to an html document (print to screen).
Effectively, you only need to handle whitespace related characters.  Since you seem to be concerned with handling multibyte characters, the unicode flag should be used on your regex patterns.  See this relevant SO page: Multibyte trim in PHP?
$stmt->execute([
    'message' => filter_var(
        preg_replace(
            ['/^\s+|\s+$/u', '/\s{2,}/u'],
            ['', ' '],
            $_POST["message"]
        ),
        FILTER_SANITIZE_STRING
    )
]);

If you are using FILTER_SANITIZE_STRING to strip tags, please see some potentially buggy behavior in the comments at https://www.php.net/manual/en/filter.filters.sanitize.php
P.s. I'd probably not use a named parameter in the prepared statement; there is only one bound parameter so there is no chance of confusion.


I would suggest to add some guard evaluation.

if (string.IsNullOrEmpty(search))
    return new DataTableDTO();

You can also convert string 'search' to lower case ones at the beginning of method.

search = search.ToLower();

Then you can ommit the first condition in Where statement:

.Where(search.Length > 0,


Python lazy dict with iterator in constructor

1. Design

I think that it's a mistake to inherit from dict. My reasoning is as follows:

LazyDict is effectively read-only: that is, setting an item does not update the underlying iterator. (In the described use case, you can't update the compressed file image through this dictionary.) So it is misleading to offer (as you do) a __setitem__ method (and similarly for update, pop, setdefault and other mutating methods).
Programmers are used to the equivalence of dictionary methods: for example, they "know" that d.get(k) behaves just the same as d[k] if k in d else None. But in your implementation it does not — calling d.get(k) does not consult the iterator but calling k in d or d[k] does. This seems like a recipe for confusion and bugs.

So I think the better approach is not to inherit from dict, but to have a dictionary as an attribute. This means that users will only be able to call the methods that you choose to implement, instead of accidentally calling through to methods on the underlying dict. This approach also makes the code clearer, because you can distinguish key in self from key in self._dict without needing to use super() or have pylint annnotations.

2. Other review comments

The parameter to the __getitem__ and __contains__ methods would be better named key.
The exception raised from a failed key lookup should be KeyError, not AttributeError, for consistency with dict.
The exception raised on a failed key lookup should include the failed key, for consistency with dict and to help programmers track down errors.
It's a good idea to keep try: ... except: ... blocks as small as possible, so that you don't accidentally capture exceptions that you weren't expecting. In this case you are expecting a StopIteration from the call to next so that's the only line that needs to be protected.
It's conventional to give attributes that are not intended to be used outside of the class (like iterator) the prefix _.

3. Revised code

class LazyDict:
    """A dictionary built on demand from an iterator."""
    def __init__(self, iterator):
        self._dict = {}
        self._iterator = iterator

    def __getitem__(self, key):
        if key in self:
            return self._dict[key]
        else:
            raise KeyError(key)

    def __contains__(self, key):
        while key not in self._dict:
            try:
                k, v = next(self._iterator)
            except StopIteration:
                return False
            self._dict[k] = v
        return True

Now someone who tries to call the get method will get an exception instead of silently getting the wrong result.


Linq sorting on sort order of inner group

What about something like this:

assets.OrderBy(a => a.GalleryItems != null &&
                    a.GalleryItems.Any()
                    ? a.GalleryItems.Min(gi => gi.SortOrder)
                    : 1000)

It's actually a bit faster, since sorting the inner list takes longer than just getting the minimum value.


c# Efficient solution: Sequence generator for a pattern

public static void GenerateSequence() {
    double tenPower(double n) => Math.Pow(10, Math.Floor(Math.Log10(n)+1));
    double build(double n) => n * tenPower(n + 1) + n + 1;
    double merge(double n1, double n2) => n1 + n2 / tenPower(n2);

    var n = 1;
    var ans = new double[16];
    for (int j1 = 0; j1 < 16; ++j1) {
        n += j1;

        var whole = build(n);
        var frac = build(n + 2);
        ans[j1] = merge(whole, frac);
    }

    foreach (var a in ans)
        Console.WriteLine(a);
}


Type definitions for simple NPM package that generates OAuth 1.0a authorization header for Twitter API using native https nodejs module

Narrow the requestMethod Its type should be narrower. There are only a small number of possible methods. Instead of string, you should permit only those which make sense. You probably want something like:
requestMethod?: 'GET' | 'POST' | 'PUT' | 'DELETE' // etc

This will both reduce typos (eg, prevent someone from accidentally using 'PUST') and make it clear that the method should not just be any string, but one of a few particular strings.
String params? You have
queryParams?: Record<string, string>
bodyParams?: Record<string, string>

But, do both parameters really have to be only string keys with string values? That doesn't sound right. For example, I would hope and expect to be able to do:
queryParams: { 1: 'foo' } // turns into `1=foo`

or
queryParams: { foo: 1 } // turns info `foo=1`

or maybe even
queryParams: { foo: false } // turns info `foo=false`

If the library can handle those sorts of inputs and serialize them properly, which I'd hope it could, the type definitions should reflect that.

The JS can be improved a bit too:
Callbacks You can pass the reject callback alone to .on('error':
req.on('error', (error) => {
  reject(error)
})

can be
req.on('error', reject)

JSON parsing and errors
res.on('end', () => {
  resolve(JSON.parse(data))
})

What if data happens not to be JSON-parseable? Then an error will be thrown, but the Promise will not reject - it'll remain pending forever. Better to enclose that in a try/catch, and call reject if parsing fails.
Narrower response type? You currently have:
export default function (
  oAuthOptions: OAuthOptions,
): <T>(requestOptions: RequestOptions) => Promise<T>

without any constraint on T. You might consider explicitly requiring T to be a plain value when deserialized - that is, you wouldn't want people to be able to pass in a function type, or an object type where the object contains non-primitives (other than other plain objects and plain arrays). Maybe use something like AsJson in jcalz's answer here.
type AsJson<T> =
  T extends string | number | boolean | null ? T :
  T extends Function ? never :
  T extends object ? { [K in keyof T]: AsJson<T[K]> } :
  never;


In-place quicksort algorithm in Python 2

Your swap function is pointless. It would be far more clear just to switch the order directly in the right hand side of every assignation.

Also, in the second for loop. I'm not sure you're supposed to iterate from 0. At best it should be from start. Remember, the idea of quicksort is that you only modify the part of the array that corresponds to the function, [start, end) in this case. However, with that loop, you're now making O(n^2) iterations, which can be improved like this:

p = ar[end-1]
idx_le = start
idx_gt = end-2
while idx_le <= idx_gt:
    if ar[idx_le] <= p:
        idx_le += 1
    else:
        ar[idx_gt], ar[idx_le] = ar[idx_le], ar[idx_gt]
        idx_gt -= 1

ar[idx_le], ar[end-1] = ar[end-1], ar[idx_le]
return ar

The main idea is to keep track where the elements less than p should be placed, same with the elements greater than p. The new recursion should be [start, idx_le) [idx_le+1, end).


Magic numbers

Right off the bat I see some magic numbers

moves = {"tackle": range(18, 26),
         "thundershock": range(10, 36),
         "heal": range(10, 20)}

What does that mean?  Being familiar with Pokemon I'd assume damage, or something, but that won't necessarily be apparent to the user.

ABCs

You have your base class, Character.  It would benefit from being an abstract base class

For example,

import abc

class Character(metaclass=abc.ABCMeta):

    def __init__(self, starting_health):
        self.current_health = starting_health

    @abc.abstractmethod
    def attack(self, other):
        raise NotImplementedError

I've done a few things here.  For one, I've used more clear variable names.  The input parameter health is actually the starting_health of the character, while self.health is actually referring to the current_health of the character.  Better variable names make code easier to read.

The meat of this is the abc stuff.  By giving the Character class a metaclass of abc.ABCMeta (don't worry about what a metaclass is) we're saying that it cannot be instantiated directly if it has any abstract methods or properties.  With this definition, if you then tried to do this

char = Character(100)

you would get the following error:

TypeError: Can't instantiate abstract class Character with abstract methods attack

This carries into sub-types as well.  It is a way of guaranteeing that all classes you instantiate that should override a method do override it.

Moves

Your moves should probably be classes.  This will make it much, much easier to extend this, and simplify some other behaviors.  I'd look at something like this

from enum import Enum

DamageTypes = Enum('DamageTypes', 'DAMAGING HEALING STATUS')
Types = Enum('Types', 'ELECTRIC NORMAL')

class Move(metaclass=abc.ABCMeta):

    @abc.abstractproperty
    def damage_type(self):
        return NotImplemented

    @abc.abstractproperty
    def move_type(self):
        return NotImplemented

    @abc.abstractmethod
    def health_change(self, modifiers=None):
        return NotImplemented

class Thundershock(Move):
    _max = 36
    _min = 10

    @property
    def damage_type(self):
        return MoveTypes.DAMAGING

    @property
    def move_type(self):
        return Types.ELECTRIC

    def health_change(self, modifiers=None):
        if modifiers is None:
            return random.randint(self._min, self._max)
        else:
            # Do something here if they have some ability that reduces electric damage, or whatever

I did a few things here.  The first was the Enums.  Enums let you group related constants together.  For example, now I can do something like

if move.move_type is Types.ELECTRIC:
    # Has lightningrod ability, immune to electric moves
    return 0

without having a magic number.  I then gave the class some properties (i.e. attributes that I can get/set without using parentheses) as well as some methods (attributes that are functions).  This gives you a slightly more well organized codebase, and is easy to extend.  Just add a new subclass.

Now in your Player class you can do something like

def attack(self, opponent)
    while True:
        try:
            move = moves[str.lower(input("stuff"))]
        except KeyError:
            print("Not a valid move, try again!")
        else:
            if move.move_type is MoveTypes.HEAL:
                self.health += move.health_change(None)
            elif move.move_type is MoveTypes.DAMAGIN:
                opponent.health -= move.health_change(None)
            else:
                opponent.status = move.status_effect(None)
            break

which to me is much cleaner, and also easier to extend if you add move types.  It doesn't rely on the specific strings of the names (can you imagine typing all ~600 moves that exist in Pokemon?) just on what sort of effect they have.

Weighted randomness

I won't repeat everything here, but Ned Batchelder has a good suggestion for how to handle weighted randomness here

Attack order

You should randomise this.  Good guys don't always go first :)

String formatting

Instead of doing

print("The health of the CPu is now {0.health}.".format(enemy)

just do

print("The health of the CPU is now {}.".format(enemy.health)

Improving your base class

As per @200_success's answer below, you should expand the functionality of your Character base class.  For example, attacking, healing, and taking damage are all shared between characters (mostly).  What if you did this?

class Character(metaclass=abc.ABCMeta):

    def __init__(self, starting_health):
        self.current_health = starting_health

    def attack(self, other, modifiers):
        move = self.get_move()
        if move.move_type is MoveTypes.DAMAGING:
            other.damage(move.health_change(modifiers))
        elif move.move_type is MoveTypes.HEAL:
            self.heal(move.health_change(modifiers))
        elif move.move_type is MoveTypes.STATUS:
            other.status(move.status_effect(modifiers))
        else:
            raise NotImplementedError

    @abc.abstractmethod
    def get_move(self):
        raise NotImplementedError

I've consolidated the act of attacking and abstracted away the only part that changes - how they pick their move.  Now you can do

 class Player(Character):

     def get_move(self):
         while True:
             move = moves[str.lower(input(""))]
         except KeyError:
             print("No such move")
         else:
             return move

 class Enemy(Character):

     def get_move(self):
         # do some pseudo random stuff
         return move

And you don't have to repeat the attacking logic, and new types of characters only need to override how they pick a move.


Removing and counting words that appear more than once

Your algorithm seems fine. It doesn't reveal any special tricks to me, but I also don't see any unnecessary steps. I think I'd have written it myself that way. The only part that I might have done differently is the regex; I'm not sure that one is fully correct.

So on an algorithmic level you're doing perfectly fine. However, the implementation suffers from spelling issues.

Comments

First, you have some comments.

    // replace the special characters
    String freeString = longString.replaceAll("[^\\w\\s-]", "");
    //the new string is
    System.out.println("freeString ::  " + freeString);
    //Calculate the length of the string
    String[] countOfString = freeString.split(" ");

Comments are nice, they help understand what's going on... but so does the code. Of course replaceAll replaces things, we already know that the new string is the freeString, and that String.split calculates the length of the string is actually not what it does.

You should replace your comments with comments with non-obvious things about what the code does (What does your regex actually do?), or comments about why the code does.

Variable Naming

Variable naming should be based on what the variable stores - usually its "semantic type". A "syntactic type" would be a String, Integer and so on. The "semantic type" is what it means - "inputString", "validatedString", "splittedString", "stringsToLoopThrough"... some of these are better than others. A semantic type doesn't have to include the syntactic type - you can have variable names like "index", "key", "value", without containing any notion of syntactic type. Usually the syntactic type is inferred, and at other times, it doesn't matter what the type is, just that it's the index/key/value/whatever.

Based on that, I think you should name countOfString words, uniqueString uniqueWords, countMap wordCountMap, and countString cleanedLongString.

countOfString seems to indicate a number. But it's a string array instead. A string array containing the words of the longString. So words seems like a fitting name. It certainly seems logical that if you split a longString on a space, you will get words.

uniqueString to uniqueWords is because of two reasons. First, by changing to Words, we signal that this variable is related to the words variable. Second, by pluralizing the variable name from String to Strings (or Word -> Words), we say this is a "collection" of sorts. Something which holds multiple values.

countMap to wordCountMap is to signal the relationship with words.

countString to cleanedLongString has two reasons, first to again note a relationship with another variable, this time with longString. Second, I add the cleaned because you have cleaned the special characters out of the original string.

The names aren't ideal yet - longString seems like a bad name, considering it doesn't have to be a longString, and it doesn't signal that it needs to be cleaned first.


Which is the most correct pattern for using Stack.Pop?

Program defensively and use option 1.

Since the Stack class provides the ability to check whether it contains anything before trying to Pop a value from it, you should do the check and avoid using the exception for flow control.

If you want to avoid doing the if check throughout your application, you could create a TryPop extension.

public static class StackExtensions
{
    public static bool TryPop<T>(this Stack<T> stack, out T value)
    {
        if (stack.Count > 0)
        {
            value = stack.Pop();
            return true;
        }

        value = default(T);
        return false;
    }
}

It could be used in the following way:

T resource;
if (availableResources.TryPop(out resource))
{
    // use `resource` for something
}

It's worth noting that this approach is only suitable if the Stack is not accessed concurrently! - If it is, and you are using .NET 4.0 onwards then you should use ConcurrentStack, otherwise create your own concurrent stack which encapsulates a Stack and manages access to it with locks.


Calculating time deltas between rows in a Pandas dataframe

Use the diff().

    x['time_delta'] = x.timestamp.diff().fillna(x['time_delta'])

This works as below, in a simpler example.

You could use the diff() Series method (with fillna to replace the first value in the series):

s = pd.Series([11, 13, 56, 60, 65])
s.diff().fillna(s)
0    11
1     2
2    43
3     4
4     5
dtype: float64

This was compiled from the comments below the current best answer (which I failed to see and kept searching), and the stack overflow link that explained it with fillna so I am hoping this can be lifted up to the top for future seekers. Happy data processing!


Get the next bigger number by rearranging the digits of the input integer

It's not so much the implementation.
With problems like these (typical coding competition ones) it's always the same, that you have to find a clever algorithm instead of writing down as code a straightforward implementation of the problem description.
I haven't myself analyzed the problem, but I'd try to answer some questions:

Of all possible permutations, might it be enough to just exchange 2 digits? Or: Can you be sure that including a third digit into the exchange is irrelevant (result below the original number, result identical to the 2-digit case, or result higher than the 2-digit result, but not between the original number and the 2-digit result)?
If you can prove two digits to be enough, which are the two digits that give the smallest result (greater than the original number)?

Maybe it helps to do some examples by hand and see some pattern.


Map reduce tester ported from bash to Python

It's strange to use map_reduce = lambda ... to define a method. This is the same, written the common way:

def map_reduce(self, mapper_name, reducer_name, datafile_name):
    run(
        ['python', path.join(self.top_path, reducer_name),  # Reduce
         run(['sort',  # Shuffle, could be replaced with python `sorted`
              run(['python', path.join(self.top_path, mapper_name),  # Map
                   path.join(self.top_path, 'data', datafile_name)])])])

And this hack of calling python -> sort -> python is not fine at all. Python can certainly sort. Then your pipeline would become python -> python -> python, and at that point it's beyond silly to call subprocesses for this. You should do the whole thing in a single Python process, instead of 3 different processes.

Refactoring with map and reduce

Here's one way to refactor mapper to use Python's map function:

def line2cols(line):
    return line.strip().split('\t')

def has6cols(cols):
    return len(cols) == 6

def cols2out(cols):
    return '{}\t{}'.format(*cols)

def mapper():
    return map(cols2out, filter(has6cols, map(line2cols, read_input())))

And here's an example reducer using Python's reduce:

def reducer(seq):
    def f(a, b):
        if len(a) > len(b):
            return a
        return b
    return reduce(f, seq, '')

This is quite stupid, it just finds the longest string in the sequence.

I hope this helps.

UPDATE

It's a bit difficult to understand what you're trying to do.

  My MapReduce tester is clearly ported from Shell, short of args=None for line in args or read_input(), what's a better way of importing->testing the function outside of subprocess?

When I read this I didn't quite get what you're talking about shell. In the code I saw you're calling Python, twice, which is clearly not fine.

Let me try again, to guess what you're trying to do. Maybe you have a Python mapper script, and you have a Python reducer script, which you use in some framework? And you want to write some unit tests to check that these scripts in fact work? I mean the scripts as black boxes, as in, you want to test the complete scripts, rather than the underlying Python functions / classes? I'm really just guessing here, maybe I'm completely wrong.

If this is indeed what you want, then don't. Don't try to test the scripts, test the underlying implementation. If the implementation passes, the scripts should print correct output too. If you want to test the script outputs in addition to the underlying implementation, then you'd be just testing the basic ability to print, which seems rather pointless.


Very simple implementation of observer pattern in C++

Don't pass by pointer. There is no ownership associated with it (and it can be NULL and thus you need to test for that).

class Publisher {

    // Is the publisher taking ownership of the observer?
    void add_observer(Observer*);

Is your class taking ownership?

If the answer is yes (you take ownership and thus control lifespan). Then you should pass the object using a smart pointer that allows transfer of ownership.

    void add_observer(std::unique_ptr<Observer> obs);

If the answer is sort of. We are taking shared ownership (ie there might be other objects that are also using it). Then you pass using a smart pointer indicating shared ownership.

    void add_observer(std::shared_ptr<Observer> obs);

If the answer is NO then you pass a reference (as a reference can not be NULL) and also indicates that you don't have onership.

    void add_observer(Observer& obs);

If you do take ownership you need to do some work in the destructor of your publisher to make sure that you correctly relinquish ownership when the publisher dies.

If you don't have an ownership claim. This also means that the lifespan of the object may not live as longer as the publisher so you also need a way for the object to remove itself if it dies first and for the publisher to notify the observer that it has dies so it does not de-register itself from a dead object.

   void del_observer(Observer& obs);


You can improve your code by using vectorization to speed up the computation of Euclidean distances in the inner loop. The code would be:

knn <- function(mat, k){
   n <- nrow(mat)
   if (n <= k) stop("k can not be more than n-1")
   neigh <- matrix(0, nrow = n, ncol = k)
   for(i in 1:n) {
      euc.dist <- colSums((mat[i, ] - t(mat)) ^ 2)
      neigh[i, ] <- order(euc.dist)[2:(k + 1)]
   }
   return(neigh)
}

Notice that I also made a few changes:

list is a function in R so calling your object list is a pretty bad idea. Also, in the R language, a "list" refers to a very specific data structure, while your code seems to be using a matrix. So calling that input mat seemed more appropriate.
Similarly, there is a dist function in R so it is a bad idea to name your variable this way. I chose euc.dist since you were computing an euclidean distance.
order already returns an index, so the whole idea of column-biding your indices and distances was not necessary: you just need a vector of distances.

The code above might still be a bit too slow because of the computations inside the for loop. If the dimensions of your matrix are not astronomical, you could compute the matrix of distances at first using a compiled function. I once tested about a dozen of packages and found that fields::rdist (written in Fortran) was the fastest. If you do not wish to install it, you can use the base::dist function. The code would look like this:

knn <- function(mat, k){
   n <- nrow(mat)
   if (n <= k) stop("k can not be more than n-1")
   neigh <- matrix(0, nrow = n, ncol = k)
   library(fields)
   dist.mat <- rdist(mat, mat)
   for(i in 1:n) {
      euc.dist <- dist.mat[i, ]
      neigh[i, ] <- order(euc.dist)[2:(k + 1)]
   }
   return(neigh)
}

If my first suggestion is still too slow and your matrix is so large that my second solution cannot be used, you might want to use a mix between the two approaches, where you loop on chunks of rows, i.e. rely on rdist(chunk_of_rows_from_mat, mat). But I'll leave that to you as an exercise :-)

Finally, I will point out that if you are interested, you could search CRAN or the internet for a package that does exactly what you are after. KNN is a  very common tool and there must be packages (compiled from C) that already do it much faster than this code will do. But not much to be learnt there...


While your code works and uses type signatures, it's missing documentation. It's not clear from your description or your code what splitter's intended result will be on a given input. Documentation and tests are therefore highly welcome.

Also, it's not clear why you've added an underscore to replace_. And your code is missing at least one include for =~. I assume that you just forgot to include that import line in your question and it is in your actual code.

That being said, the fullstop library is—according to its own documentation—a placeholder library:

  Note that this package is mostly a placeholder. I hope the Haskell/NLP
  communities will run with it and upload a more sophisticated (family
  of) segmenter(s) in its place. Patches (and new maintainers) would be
  greeted with delight!

Your quarrel about the line endings also comes from segment, since it hard-codes the allowed punctuations:

-- https://hackage.haskell.org/package/fullstop-0.1.4/docs/src/NLP-FullStop.html#stopPunctuation
stopPunctuation :: [Char]
stopPunctuation = [ '.', '?', '!' ] -- <<<<

Unfortunately, you cannot expand stopPunctuation, since content in parentheses (like this) does not lead to a new sentence. Note that .) and ." aren't valid in some languages, though, they require ). and "., so it's not clear what you try to achieve there (see comment above documentation above).

So all in all, well written, but without additional explanation or documentation there is no way to check whether the function actually does what you want. I also suggest you to add some tests.


Uses of barriers for one main thread controlling n threads

The threading mechanics mostly look correct.  Your main thread and your subthreads only share the mCommandToExecute and commands variables.  The subthreads only read them between mWaitForCommand and mWaitForAllDone, and the main thread reads and writes the mCommandToExecute between mWaitForAllDone and waitForCommand.  So no one is writing to this data while anyone else is reading it, and your data is thread-safe.

However your subthreads do not have any exit condition, so I expect the pthread_join will hang on the first one.  When you reach that point, all your subthreads will be waiting for the next command.  Joining the thread does not terminate it.  It simply allows you to synchronize their termination. You need to add some signal for the subthreads to terminate, and then you need to invoke that signal and then pthread_barrier_wait(mWaitForCommand) to allow each subthread to proceed to check the termination signal.

One simple way to do this, if it's practical, would be to make the termination step the final "command".  Rather than sending the termination command, the subthreads could recognize it and just return immediately.  Your main thread would need to avoid waiting on mWaitForAllDone for that last command, though.

I assume you will have some other code which handles lost connections, closing the accepted connections after the threads terminate, etc.  You do not seem to allow for stalled threads such as might occur in many network situations. If a client does stall, it will stall your entire system of threads.  I assume this is intentional or else you have timeouts and handlers for such occurrences in your real code.