From a once over;

I would not split statements like

this.$status.addClass('error')
    .text(message);

over 2 lines, I would reserve that treatment for the longer statements.
You seem to cheat with the simpleness of your call, Form knows already the error messages with this.errors and the validation types with this.required. These should have come in as options.
I tend to comment all my regular expressions with my intent and an example, that might be overkill for your regular expressions
In Form.prototype.process it would have been simpler to have var self = this and use self instead of using $.proxy(. While using closures is not a panacea, it should also not be avoided at all costs.
You seem to like shortcuts, consider

return filled = false;

instead of

filled = false;
return false;

filled && this.submit($(this.$form).serialize()); <-- Too hacky
Why is this code removing the shake css class, it never assigns it..
On the whole it seems Form.prototype.update could be written in a smarter way, but I would have to see an actual snippet working to get started on that


It seems to me that what you need is the State pattern.


OO design of Reverse Polish Notation Calculator

You can add more flexibility by storing a mapping from a String to a Token in a Map. After populating the map, you'll just need to look up for the token in it instead of writing a a long sequence of if-else blocks.

That is, you can define and populate it like this:

Map<String, Token> operators = new HashMap<>();
operators.add("+", new Plus());
// other operators go here

and then use it like this:
operators.get(str).calc()

This way, you just need to define a new subclass of the Token and add its instance to the operators map to define a new operator.

You can make the code even more flexible by passing this map as a parameter to the processInput method to decouple reading the input from the computations (this way, a client will be able to define his own subclass of the Token and pass it to this method).

I'd also rename the Token. Operator or Operation seems more appropriate to me (because a number is also a token, so this name is more precise).

There's also no point in having static members in the RPNCalculator class. It makes it non-reusable and might create a bunch of issues in a multithreaded environment. I'd suggest to make all members non-static and encapsulate them properly (and pass a reference to an instance of this class to the constructor of the concrete Token subclasses).

You can also decouple the operators from the calculator completely by changing the signature of the calc method to public int calc(int a, int b) (it might be an issue for non-binary operators, though).

You can improve your code by handling the errors more carefully. For instance, if the number of tokens on the stack is more than one in the end of the evaluation, your code will return some value, but it should be an error ("1 2" is not a valid expression, is it?). You can check such cases and throw an appropriate exception.


That method is fine, and is the one I use. As for a better way? I don't know, seems just fine to me. However, there are some other things that could be improved with this script, and that may be why you feel there might be a better way.

For one, that's some really messy HTML... I would try and separate your PHP from your HTML as much as possible. This is a little harder to do when not using MVC, but can still be accomplished by abstracting your larger bits of code. Also, you are using PHP short tags, but then not using PHP template syntax, this seems counter productive. The purpose of the short tags is to make your code cleaner and make it non-PHP user friendly. Of course, I'm not endorsing PHP short tags, I think you should avoid them, as you are not always guaranteed to have a server that will support them. Lastly, your code is pretty repetitive, the best thing for repetitive stuff like this is loops. For example, here's a sample of how my version of this form would look.

<?php
$fields = array(
    'name',
    'age',
    //etc...
);
?>

<?php foreach( $fields AS $field ) : ?>

<?php $value = isset( $_SESSION[ 'form' ] [ $field ] ) ? $_SESSION[ 'form' ] [ $field ] : ''; ?>

<label for="<?php echo $field; ?>">What is your <?php echo $field; ?>?
<input type="text" name="<?php echo $field; ?>" value="<?php echo $value; ?>" maxlength="60" />

<?php if( ! isset( $_SESSION[ 'errors' ] [ $field ] ) ) : ?>

<label class="error" for="<?php echo $field; ?>"><?php echo $_SESSION[ 'errors' ] [ $field ]; ?>

<?php endif; ?>

<?php endforeach; ?>

Of course, even this seems really messy to me, though I can't think of much more, besides using MVC, to do to this to make it cleaner. Also, notice I removed the "id" attribute from your input tag. When your tag has a name, it doesn't need an id, you can just call it with the name. Example:

alert( document.form.name.value );//may not work, dont think "form" is valid name

Take a look at PHP's filter_input() function. Its available as long as your PHP version is >= 5.2. It also has some validation flags if you're interested.

$form[ 'name' ] = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );

Keep in mind the "Don't Repeat Yourself" (DRY) principle. There are a lot of violations of it here. I demonstrated how to avoid it with your form above, you can do something similar for the processing script.


Extension method to get results of type T from a cache

Logically, it makes sense to me that you would want to tie a key to a Func.  This method could then just take the string and then delegate the responsibility to decide how to fetch the value to another class.  Also, a few nitpicky points about what is actually there.  I consider using letters as variables poor practice since it gives no context as to how it will be used.  I would rename "f" to something like "retrieve" or "fetch".  Also, there is no guarantee that running "f" will actually give you a non null value.  In that case, I doubt you would want to store null in your cache.


My thoughts:

Imho Database should not belong to Utilities namespace. Working with database is likely a core part of your application, "Utilities" suggest auxiliary tools to make your life easier. But maybe the class does something different than I expect
Is there a reason to keep all your application in Metin2 namespace but have separate Exceptions namespace with Metin2Exception? If it's for code completition, then a good IDE should only suggest classes inheriting from Exception in these contexts.
Metin2::__constructor(): can Utilities\Database throw Metin2Exception? If not, then it's not really useful to throw exception only to catch it right away and echo
It's worth considering using specialized Exception classes and keep Exception messages for details. That is because you can't catch Exception based on its message, but only class. Here you could have ConnectionFailedException extends Metin2Exception.
Instead of echoing Exception message I would recommend making a function/class, that would enable you to redirect error messages to file, as it's not recommended to be printing out application messages for users to see. This way you'll also be able to log them.
On a similar note you may take a look at set_exception_handler, that lets you assign a function/method to handle uncaught exceptions. And from that you can try either making your own or using a 3rd party exception handlers, which combined with set_error_handler that can be used for conversion of errors to exceptions can really improve your programming. Examples: https://github.com/nette/tracy or ... maybe http://raveren.github.io/kint/ (I'm sure there's another as nice as Tracy, but I can't remember its name).
You can remove dependency of Autoloader on a global constant by adding a static property and using a setter to set its value
When Autoloader finds out the target filepath does not exist, it does not react in any way ... maybe at least log it somehow, if not throw exception?
What's the purpose of Testdb? I would discourage from using a service location especially when it comes to testing ... why not pass the $db as an argument?


Selecting an algorithm and key for Java Card encryption

I would focus on eliminating the inner switch statements.  You could try to eliminate the outer switch as well, but it's probably not worthwhile, especially for a resource-constrained environment.

byte[][] desKeys = new byte[][] {
    null, DESKey1, DESKey2, DESKey3, DESKey4
};

try {
    switch (buf[ISO7816.OFFSET_P1]) {
      case 0x01:
        doSingleDES(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
        return;
      case 0x02:
        doEncrypt(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);
        return;
      default:
        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }
} catch (ArrayIndexOutOfBoundsException badP2) {
    ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}


Ideas for simplificaton - Logic to choose which view to load

Based on your answer, you should put the mapping in an array and create a for each loop. Maybe it would also be a good idea to extract the strtoupper($hardwarename) in a local variable that you don't do it in any if in the worst case. In addition to that you missed to add a default case, which might lead to an error in loading the template. Furthermore you have to move the longer DELL check in front of the shorter otherwise you will never reach this branch.

private function checkhardwarename($hardwarename)
{
    $mapping=array("HP"=>"hp",
                   "DELL%20SF"=>"dell_sf",
                   "DELL"=>"dell");
    $hardwarename=strtoupper($hardwarename);

    foreach ($mapping as $needle=>$viewname)
    {
        if (strpos($hardwarename, $needle) !== false) return $viewname;
    }

    return "default";
}


Neither is all that good. It seems that you just apply functions at random to your data in the hope that some of them will protect you, which is not the correct approach to security.

How to properly defend against XSS

First of all, the correct approach to XSS is to HTML encode data when outputting it. That is where the vulnerability is create, and that is where it should be prevented.

There are three important reasons for this:

When outputting, you know the context, which is important to defend against XSS (is it inside script tags? inside a HTML attribute? What attribute? A JavaScript context attribute? Are there quotes around it? What quotes? ...)
You really can't be sure when outputting data that it was previously secured (can data get into the database in other ways than GET/POST? etc).
Your data will not be clean anymore, which may break your website (eg when sending an email, or when using passwords (with your function, "a<super!secure^password" would become a)).

Note that there are contexts in which HTML encoding may not be enough to prevent XSS.

Improving your Code

Why are you using different cleaning functions for array values and non-array values in selfValidator? It doesn't make any sense to treat these differently.

For that matter, if you would use the same functions, you would have duplication in your code, which should be removed (either by using recursion or by extracting the cleaning to a separate function).

Also:

Use more spaces, eg around <, =, etc (just use any IDE to fix formatting issues for you).
Your variable names are not consistent. Sometimes you use secured_output and sometimes data. When things are named differently, you make a reader of the code wonder why that is (eg is data maybe not secured)?
Your Validator comment doesn't really add any information, I would just remove it (and give the functions a more fitting name instead). You could create PHPDoc style comments instead, documenting the behavior of your function in-depth

The cleaning functions you use

I think it would be a good idea to look at the functions you do use in-depth, to get a real understanding what each of them does. Ideally, you take a look at the PHP documentation for this, but here is a short overview:

trim: remove whitespace, may be useful, depending on the situation
stripslashes: ONLY use this when magic quotes are enabled. Stripping slashes does nothing for security, and it makes your data unclean if magic quotes are disabled (which is the default).
htmlentities: This is what you generally want to use to prevent XSS when outputting data in most contexts.
strip_tags: Not really all that useful. Doesn't prevent XSS in as many contexts as htmlentities, and makes your data dirtier than htmlentities (see my password example above).
filter_var: These functions are great when first accessing GET/POST values, to restrict what characters are allowed (as defense in depth, NOT as only defense). If you know that you need only alphanum, it's good to restrict the characters, etc (just in case that you do have vulnerabilities in other parts of your application, this will make it harder to exploit them). But: You can't just apply filter_var to all values that you will ever receive. It's again context dependent. If you expect an id, only accept integer. If you expect an email address, use that filter. But if you eg expect a password, filtering it is a bad idea, as it reduces the complexity of the password.


A couple of tips for unit testing:

One test case per subject: so you should definitely split the cases
Ideally no logic at all: avoid loops
Duplication is acceptable: clarity is most important

I would write this way:

public void testNotEquals_IfNameChanged() {
    ProgressableItem itemWithDifferentName = copyOf(item);
    itemWithDifferentName.setName("Not the same " + item.getName());
    assertThat(itemWithDifferentName, not(item));
}

public void testNotEquals_IfDescriptionChanged() {
    ProgressableItem itemWithDifferentDescription = copyOf(item);
    itemWithDifferentName.setDescription("Not the same " + item.getDescription());
    assertThat(itemWithDifferentDescription, not(item));
}

public void testNotEquals_IfProgressChanged() {
    ProgressableItem itemWithDifferentProgress = copyOf(item);
    itemWithDifferentName.setProgress(item.getProgress() + 1);
    assertThat(itemWithDifferentProgress, not(item));
}

public void testNotEquals_IfMaxChanged() {
    ProgressableItem itemWithDifferentMax = copyOf(item);
    itemWithDifferentName.setMax(item.getMax() + 1);
    assertThat(itemWithDifferentMax, not(item));
}

Since you never change item, you don't really need the setUp method:

private final ProgressableItem item = new ProgressableItem("item", "test item", 0, 100);

Of course just because it's final nothing prevents you from mutating it.

To be extra safe and stay efficient, you could create an unmodifiable ProgressableItem, for example:

private final ProgressableItem item = new ProgressableItem("item", "test item", 0, 100) {
    @Override
    public void setName(String name) {
        throw new UnsupportedOperationException();
    }
    // ... + the other setters too
};


Rather than using a std::vector and using the indices to specify the host and path, we can create a little struct and refer to the members by name:
struct URL
{
  std::string host;
  std::string path;
};

So we can refer to url.host instead of url.at(0).

As pointed out in the comments, the parsing method could be more accurate and comprehensive. It's fine to only support a small subset of the url syntax, but we should at least check that we got what we expected in the string.
In this case, I think we should:

Throw an error if we don't find a dot.
Either throw an error if we don't find a slash, OR set the path part of the url to "/" to ensure that our GET request is valid.

int MAXDATASIZE = 1024;
...
char buf[MAXDATASIZE];

This doesn't compile for me. MAXDATASIZE must be a constant.
We can remove the need for a separate constant by using std::array:
std::array<char, 1024> buf;
// now we can use buf.size() :)

Even for something small like this, it's probably worth writing our own socket class. This provides some cleanup safety (RAII), as well as making the code in main() a lot simpler and easier to read by removing some of details of the network code. e.g. something like the following:
struct socket
{
public:

    socket();
    explicit socket(struct addrinfo const& address);

    socket(socket const&) = delete;
    socket& operator=(socket const&) = delete;

    socket(socket&& other);
    socket& operator=(socket&& other);

    ~socket();

    std::size_t send(char const* data, std::size_t data_size);
    std::size_t receive(char* buffer, std::size_t buffer_size);

    bool is_open() const;
    void close();

private:

    SOCKET m_handle;
};

We could also move the address lookup out of main() into a separate function, and keep the addrinfo in a unique pointer with a custom deleter that calls freeaddrinfo(). Something like:
std::unique_ptr<addrinfo, std::function<void(addrinfo*)>> lookup_address(std::string const& node, std::string const& service, int ai_family, int ai_socktype, int ai_protocol, int ai_flags = 0)
{
  auto ai_hints = addrinfo();
  // ... set up hints!

  auto output = (addrinfo*) nullptr;
  auto result = getaddrinfo(node.c_str(), service.c_str(), &ai_hints, &output);
  // ... check errors!

  return { output, [] (addrinfo* ai) { freeaddrinfo(ai); } };
}

So we might end up a main like:
int main(int argc, char** argv)
{
  if (argc != 3)
    throw std::runtime_error("Unexpected argument count!");

  auto url = parse_url(argv[1]);
  auto address = lookup_address(url.host, "80", AF_UNSPEC, SOCK_STREAM, 0, 0);

  if (!address)
    throw std::runtime_error("Failed address lookup!");

  auto s = socket(*address);

  if (!s.is_open())
    throw std::runtime_error("Failed to connect!");

  auto request = "GET " + url.path + " HTTP/1.1\r\n\r\n";
  auto sent = s.send(request.c_str(), request.size() + 1);

  if (sent != request.size() + 1)
    throw std::runtime_error("Failed to send request!");

  auto buffer = std::array<char, 1024>();
  auto received = s.receive(buffer.data(), buffer.size());

  if (received == 0)
    throw std::runtime_error("No data received!");

  std::ofstream(argv[2]).write(buffer.data(), received);
}

(code not compiled or tested).


Improving script performance for looping unparalleled arrays

Instead of iterating through the inner array multiple times, it might be faster to create a map for the inner array beforehand and then test for a match within the map. (I think this will only work if they're arrays of strings, though.)

var arr_vals = ["74","f4e3","22","r31","17","hundernds"]; // could have 500+ items
var arr_items = ["r31","22","65","100"]; // could have 50 items

var vals_len = arr_vals.length;
var items_len = arr_items.length;

var map_items = {};
for(var j = 0; j < items_len; ++j) {
  map_items[arr_items[j]] = 1;
}

for( var i = 0; i < vals_len; ++i) {
  if(map_items[arr_vals[i]]) {
    // match!
  }
}

Perf test


This is not generating correct pairwise combinations.

Input data

[['Requests'],
    ['Create','Edit'],
    ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Created By','Modified By','Request Id','Resolution','To Address','Account Name','Priority','Channel','Category','Sub Category'],
    ['None','is','isn\'t','contains','doesn\'t contain','starts with','ends with','is empty','is not empty'],
    ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Mark Spam','Resolution','To Address','Due Date','Priority','Channel','Category','Sub Category']]

Result by Microsoft PICT

http://pastebin.com/cZdND9UA

Result by your code
http://pastebin.com/EC6xv4vG

This generates only for NONE in most of cases such as this

Requests    Create  Account Name    None    Category
Requests    Create  Account Name    None    Channel
Requests    Create  Account Name    None    Description
Requests    Create  Account Name    None    Due Date


You could simply put your maps in a map, as the mapRouting function is nothing but a simple lookup.

Prepare somewhere

private static final Map<String, Map<String, String>> MASTER = new HashMap<>() {
   {
       put("ACTION", ACTION);
       put("ENVIRONMENT", ENVIRONMENT);
       put("RULE_TYPE", RULE_TYPE);
   }
};

And simply access that map:

public static Map<String, String> mapRouting(String mapName) {
    return MASTER.get(mapName);
}

BTW: in times of Java 10 you should really use Map.of instead of anonymous map subclasses.


Dict lookup with type conversion and fallback

I prefer the explicit form of the code, because we’re minimising the amount of code that can throw. It makes it very clear exactly where we expect the exception to occur, and we don’t risk catching an unexpected exception that’s hiding in our try block.

As it happens, we can actually do away with the first try/except block. This operation – look up a key, if it’s missing, use a default – is common enough that it’s covered by the standard library; specifically, dict.get(). You can use the single line:

rv = self.get(key, default)

Separately, I’d rename the type keyword. It’s better to avoid using the same names as the built-in functions – it can be a source of subtle bugs, and just causes confusion.


Take first 12 bits of a number if longer than 12

There is a lot of room for improvement here, but first, let us talk about code style and best practices.

using namespace std; is not a good practice, because it can make your code harder to read if you are using a lot of standard functionality and introduce hard-to-spot name resolution problems. While that is less likely to be an issue in short programs, I still advise you to not use it (creating good habits is worth a lot in the long run!).
Don't do too much on a single line! In particular, don't int num, total = 0, x = 0, sizeOfStack, foo[12], i = 0;, because, on the one hand, you are likely to forget an initializer or a part of a type here and, in the worst case, end up with undefined behavior, and, on the other hand, it is just hard to read for everybody not familiar with your code (such as I). Please split that line up into multiple definitions and declarations. Also, ...
Initialize and use variables as locally as possible. This not only prevents scope pollution, but also increases the readability of your code. As a reviewer, I don't want to (and even cannot) keep a mental map on more than a handful of variables, especially if I have to remember them through large blocks of code where they don't even appear once.
To my understanding at least, the term decimal implies floating point numbers, not just integers. Please think about clarifying, e.g. by writing "decimal integers" or something alike.
Your code does (probably) unexpected thing for numbers smaller than 0. Since you take input as an int and also do virtually no error checking, you could end up with the user inputting a negative number, for which your code will output 0 for the binary and 0 for the decimal representation. If you don't want to accept negative numbers at all, num should be unsigned. If you do, change your implementation to work correctly for those. Either way, you should do input verification on the numbers (or non-numbers) you get.
Don't use std::endl. If you want a newline, simply write '\n'. The reason is that std::endl does more than the name suggests. In particular it writes a '\n' and flushes the underlying buffer which is very rarely what you want or need to do because it seldom yields any benefits and can decrease performance.
Order your includes. In general, alphabetic ordering is expected to enable fast header verification for people reading your code.
Write meaningful comments. In particular, follow the DRY principle in comments as well as code, which means that s.push(total); // push 'total'(?) onto the stack, for example, should go without the comment because it only repeats what the code does. Instead, try to us comments to give reasons as to why you're doing something, and don't overuse them because you've read somewhere that "the more comments, the better". Usefulness and clarity are key.
foo is not exactly what I would call a good variable name. Most of your other names are good, but this one identifier is definitely not. How about something along the lines of binaryDigits instead?
If you have access to anything >=C++11, use nullptr in place of NULL because NULL is fragile and convertible to a lot of things that are not actually pointers.

You asked

  I am wondering if there is a better way to write this code?

and the answer to that is yes. The main idea of your current implementation is to use a stack with your numbers binary digits, which is wasteful (and probably slow) in comparison to just doing the operation in place using bitshifting.

The algorithm that I would propose works like this:

1. Find the highest set bit (= most significant set bit/mssb) in the input
2. Shift the number right so that the mssb is in 12th position

which should be simple enough to implement. Let's walk this through step by step:

There are different algorithms for finding the most significant bit, but usually an iterative approach works well enough. The general idea is to iterate the number bitwise from the most significant to the least significant bit, checking whether the current bit is set. If it is, return the current bit position. In code, this might look like this:

static unsigned find_mssb(unsigned const num) {

    unsigned const num_bit_count = sizeof num * CHAR_BIT;

    unsigned flag = 1u << (num_bit_count - 1u);

    //num_bit_count is also the index of the msb
    unsigned index = num_bit_count;
    while (index) {

        if (num & flag) {
            return index;
        }

        flag >>= 1u;
        --index;
    }

    return 0u;
}

It is important to note that the least significant byte has the index 1, not 0, because we reserve 0 for the occasion that no bit is actually set. Alternatively, if you use either gcc or clang, there is the builtin __builtin_clz which returns the number of leading zeroes, greatly simplifying the computation:

static unsigned find_mssb(unsigned const num) {

    unsigned const num_bit_count = sizeof num * CHAR_BIT;

    //__builtin_clz(0u) is undefined behavior
    if (num) {
        unsigned leading_zeroes = __builtin_clz(num);
        return num_bit_count - leading_zeroes;
    }

    return 0u;
}

Now that we have a way to find the most significant set bit, let's move on to step
Shifting the number right so that the most significant set bit is in the 12th position. This is trivial to do. In code:

unsigned mssb = find_mssb(number);

if (mssb < 12u) {
  //error message, exit, ...
}

number >>= mssb - 12u;

And we're done.

Putting all of this (and some bits of supporting code) together, a reworked version of your program could look something like this:

#include <algorithm>
#include <climits>
#include <iostream>
#include <limits>
#include <sstream>

static unsigned find_mssb(unsigned const num) {

    unsigned const num_bit_count = sizeof num * CHAR_BIT;

#ifdef __GNUG__

    if (num) {
        unsigned leading_zeroes = __builtin_clz(num);
        return num_bit_count - leading_zeroes;
    }

#else
    unsigned flag = 1u << (num_bit_count - 1);

    unsigned index = num_bit_count;
    while (index) {

        if (num & flag) {
            return index;
        }

        flag >>= 1;
        --index;
    }

#endif

    return 0;
}

static std::string binary_representation(unsigned num) {

    std::ostringstream representation;

    while (num) {
        representation << (num & 0x1u);
        num >>= 1;
    }

    std::string str {representation.str()};
    std::reverse(str.begin(), str.end());

    return str;
}

int main() {

    std::cout << "Please enter an integer\n> ";
    unsigned number;
    std::cin >> number;

    unsigned mssb = find_mssb(number);

    if (mssb < 12u) {
        std::cout << "The number you entered is too short. Its binary"
            " representation is only " << mssb << " bits long, which is"
            " less than the required length of 12. In binary, your number is "
            << binary_representation(number) << ".\n";
        return 0;
    }

    number >>= mssb - 12u;
    std::cout << "The trimmed number is "<< number
            << ". The 12 most significant bits are "
            << binary_representation(number) << '\n';
}

Edit: As TobySpeight mentioned in the comments, the bit length of char is not dictated by the standard, so assuming each byte has eight bits is not portable. Instead, the standard library offers CHAR_BIT instead, which is now used in the updated code.


I question the validity of this exercise. I wouldn't really expect the percentages to line up for a long, long, long time. Possibly never. Running a few times I got anywhere from 290k to nearly 8 million. That's a lot of die rolls, and a pretty wide range.

That said, we can certainly improve your code. First, there's random.randint() which is more directly what you want. Let's just put that in a function:

def die_roll():
    return random.randint(1, 6)

Now we don't need that weird 7.

Next, results should be ints. After all, we're iterating upward. We only need to convert them to floats when we do the calculation. We can also use itertools.count() for the loop:

results = [0] * 13
for count in itertools.count(start=1):
    results[die_roll() + die_roll()] += 1

Ok, now that we have our results, we need to compare against expected. Rather than doing a list copy, division, round on every element - let's go one at a time. After all, if the percentage for 2 doesn't line up, why even calculate the percentage for 3?

The percentage for any one roll is:

round(1. * r / count, 3)

for r in results. And the expectation is e in expected. We want to iterate over both lists simultaneously... "zipping" through them. For that, there's itertools.izip():

if all(round(1. * r/count, 3) == e
       for r, e in itertools.izip(results, expected)):
    break

Lastly, don't hardcode your percentages! These have well defined values. We have a pyramid (0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1) that we just multiply by 1/36. So that's:

def prob(x):
    count = x-1 if x <= 7 else 13-x
    return round(count/36., 3)

expected = [0.0] + [prob(x) for x in range(1, 13)]

So the full solution is:

import random
import itertools

def prob(x):
    count = x-1 if x <= 7 else 13-x
    return round(count/36., 3)

expected = [0.0] + [prob(x) for x in range(1, 13)]

results = [0] * 13

def die_roll():
    return random.randint(1, 6)

for count in itertools.count(start=1):
    results[die_roll() + die_roll()] += 1

    if all(round(1. * r/count, 3) == e
           for r, e in itertools.izip(results, expected)):
        break

print count

Dropping Floats

Floating point arithmetic is always slow. We could do a bit better by keeping everything integral:

import random
import itertools

def prob(x):
    count = x-1 if x <= 7 else 13-x
    return 1000*count/36

expected = [0] + [prob(x) for x in range(1, 13)]
results = [0] * 13

def die_roll():
    return random.randint(1, 6)

for count in itertools.count(start=1):
    results[die_roll() + die_roll()] += 1

    if all(1000 * r/count == e
           for r, e in itertools.izip(results, expected)):
        break

print count

Generalize arbitrarily

Sometimes, the people want an over-engineered solution. So let's give them an over-engineered solution! We can use itertools.product() to help us determine the odds of particular die rolls. Everything else is straightforward:

def roll_until_match(sides=6, num_dice=2):
    c = collections.Counter(sum(p) for p in
                            itertools.product(xrange(1, sides+1), repeat=num_dice))

    expected = [1000 * c.get(i, 0) / (sides ** num_dice)
                for i in xrange(sides * num_dice + 1)]

    results = [0] * (sides * num_dice + 1)

    def die_rolls():
        return sum(random.randint(1, sides) for _ in xrange(num_dice))

    for count in itertools.count(start=1):
        results[die_rolls()] += 1

        if all(1000 * r/count == e
               for r, e in itertools.izip(results, expected)):
            break

    print count
    print results


In my opinion No. There is hardly any behaviour at all. As soon you say "I have this method in my service layer" it make it much more obvious. Service layer provide communication and pretty much should orchestrate things. That's it.

Note that Unit tests are good but have it unnecessary written they become a maintenance issue.

Test your code which has behaviour from the customer's requirements point of view.

Typically you would have an acceptance type test or an integration test to cover service layer and other layers as well.


That's fine as far as it goes.
Though I am not sure why you want all the added complexity for a problem that seems to be already solved.

What I think we all want is to stream containers in a logical way, that is consistent across containers.

Your basic example:

for(auto const& el: c) {
    std::cout << sep() << el;
std::cout << "\n";

This is a specialization of how I would want containers to be stremed:

auto sep = one_off("", sepObject);
stream << beginMarker;
for(auto const& el: c) {
    stream << sep() << el;
stream << endMarker;

So for example:

// An array looks like this:
[ 1, 2, 3, 4, 5, 6 ]        // Note terminator is "]\n"

// A map look like this:
{ a => b, c => d, e => f }

So would it be not more logical to define a container streamer object.

std::Container  c = {1,2,3,4,5};
ContainerStream(std::cout) << c;

Then you can use traits to define the beginMarker, endMarker and sepObject.

Or alternatively rather than wrapping the stream we could potentially wrap the container in something that knows how to print it (and generalize that).

std::cout << jsonExport(c);


Print a array of size n*n, with borders as 1's and fill rest of element with 0's

Have you alread checked out np.pad?
import numpy as np
n = int(input("Enter a number:"))
np_box = np.pad(np.zeros((n-1,n-1)), 1, constant_values=1)


Transforming markdown files in folders into a documentation

First change - extract iteration logic to its own generator:

def markdown_files(config):
    sources_dir = config['sources_dir']
    for root, dirnames, filenames in os.walk(sources_dir):
        for filename in fnmatch.filter(filenames, '*.md'):
            yield os.path.join(root, filename)

def main():
    config = get_user_config(os.getcwd())
    for path in markdown_files(config):
        html_block = transform_html_into_markdown(path)

        # ...

For one, this eliminates a level of nesting, which is always a good thing

Also you can add things like exclude paths to your config at a later date, without having to change your processing code. Note that this might require you to rethink passing sources_dir into get_html_file_path, as any filtering logic might end up duplicated...

Second change: wrap the entire processing routine in a single function:

def process_file(config, path):
    html_block = transform_html_into_markdown(path)

    # ...

def main():
    config = get_user_config(os.getcwd())
    for md_path in markdown_files(config):
        process_file(config, md_path)

So that later you can parallelize it, if you really need to:

import multiprocessing
import functools  # we can't directly pass a lambda into map

pool = multiprocessing.Pool()
pool.map(
    functools.partial(process_file, config=config),
    markdown_files(config)
)


LINQ for generating all possible permutations

English language

These are relatively minor issues, but fixing them might help other people to use / maintain your code.

The verb corresponding to permutation is permute.
I'm pretty sure that reminder is intended as remainder.

Code

    public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)
    {
        return permutate(source, Enumerable.Empty<T>());
        IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix) =>
            !reminder.Any() ? new[] { prefix.ToArray() } :
            reminder.SelectMany((c, i) => permutate(
                reminder.Take(i).Concat(reminder.Skip(i+1)).ToArray(),
                prefix.Append(c)));
    }

To return a permutation of source it is necessary to find all of the elements of source, so I think this is a case where the first thing the method should do is to fully evaluate source (e.g. with ToList() or ToArray()), and then work with that list rather than source. Apart from the efficiency benefits, that guarantees that all of the permutations will be permutations of the same size and elements, even if source has side-effects.

There are a couple of things you can then do with a list to make it much more efficient. Either you can use a standard "next permutation" algorithm (see Wikipedia: for arbitrary inputs it can be done by permuting an array of integers and copying the operations on the array of T) or you can recursively select an element from the first k, swap it to position k, recurse on k-1, and then swap it back. When k==0 you instead copy the entire array and yield the copy. This avoids building up chains of Append and the overheads of Take/Skip/Concat. I expect that the most efficient would be the "next permutation" approach, because it is non-recursive and so doesn't wrap coroutine in coroutine.


World resource system for Adventure Game/RPG

A few notes:

All IResource properties have public setters. Are you absolutely certain that other code should be able to modify those? I'd recommend making these read-only unless you have specific reasons not to.
ConvertQualityToString and GetResourceYield look like internal helper methods. Making them part of the IResource interface creates a very confusing API: what's the difference between resource.Yield and resource.GetResourceYield()? With the way the code is structured, I'd expect these methods to be protected.
Are you sure that string is a good type for Quality? If you've got a fixed number of qualities an enum is a more strongly-typed and descriptive choice. And if different qualities have different characteristics then perhaps a Quality class makes more sense. Try to avoid writing 'stringly-typed' code.
ConvertQualityToString gives a 33% chance for each quality. Likewise, GetResourceYield always produces yields between 1 and 25. Are you sure that's applicable to all resources and in all circumstances? Should quality and yield even be determined by a Resource instance itself? What if, for example, some enemies should have a higher chance of dropping high-quality resources? Or what if you want to provide player upgrades that increase the average resource yield?
What's the point of that Granite class? There's no custom logic in there, and the resource name itself is sufficient to distinguish between different resources.
In ConvertQualityToString, there's no need for that local quality variable: you can let each case return a value directly (which also allows you to remove those break statements).
ConvertQualityToString is a strange name: it doesn't really convert anything. Inaccurate and confusing names tend to make code more difficult to work with.


High performance wrapper for CSPRNG arc4random(3)

result = random % range

You can only do this if range is constrained to be much smaller than the maximum value of random.  Imagine a 2-bit PRNG that returns a value from 0 to 3.   When your function is invoked with range 3, return value 0 will be twice as common as 1 or 2.

random_32b /= range;
full_32b /= range;

This is going to exhibit obvious bias when the result has a small number of bits.  Imagine a range of 3 and a 4-bit random pool.  On exit, full_32b will equal 5 but random_32b will only equal 5 one time in 15.

There are three good ways to go about this:

choose an acceptable margin of bias (expressed as a fraction);
divide range by that fraction;
select enough bits to make max(random) larger than the result of the division;
return a simple modulus.

For example, 1% bias is 0.01.  If the range is 10, the random number needs a maximum larger than \$10/0.01 = 1000\$.
That's ten bits.

select enough bits to represent range
repeat until the result is smaller than range.

Example: for a range of 10, consume four bits and discard results larger than 9.

select enough bits to represent range, plus a couple more, to represent a multiple of range.  Call the multiplier \$i\$.
repeat until the result is smaller than \$i * \$range
divide result by \$i\$

This last approach combines the advanatages of first two: you get bias-free numbers and mostly predictable runtime.

Example: approach #2 with a range of 9 consumes four bits per attempt, and discards almost half of the results.  With 5 bits, instead of 4, you keep results from 0-26 (i.e., range\$*3\$) and divide them by 3.  Discard 27 or larger—that's only 5/32 attempts wasted.  With 6 bits and range of 9, values 0-62 are usable (range\$*7\$), and only one possible value (63) will be discarded.

In all cases, consume bits by bit-shifting (or dividing by powers of two).  Integer division with arbitrary denominators won't work.


Optimization for SQLite result set parsing

I have missed the whole point of your program but these comments might be useful to you anyway :

dict_generator

I might be wrong but dict_generator(large_dict) looks like large_dict.iteritems() (Python 2) / large_dict.items() (Python 3).

create_result_generator

 while True:
     result_set = c.fetchall()
     if not result_set:
         break
     else:
         return(row for row in result_set)

This loop does not seem very loopy to me. What about :

 result_set = c.fetchall()
 if result_set:
     return(row for row in result_set)

Also, it seems to hilight a bigger issue about the fact that the connection might not be closed.

find_longest_tandem_repeat

In :

     try:
         sequence_dict[row[3]].append(row[2])
     except KeyError:
         sequence_dict[row[3]] = []
         sequence_dict[row[3]].append(row[2])

seems to be equivalent to

     sequence_dict.setdefault(row[3],[]).append(row[2])

Also, I don't know where row is coming from at this stage.

In :

 for key,value in dict_generator(sequence_dict):
     sortList = sorted(value)
     for i in range (0, (len(sortList)-1)):
         if((sorList[i+1]-sorList[i]) == (sorList[i+2]-sorList[i+1])
             == (sorList[i+3]-sorList[i+2]) == (len(key))):
               tandem_repeat[key] = True
     sortList = []

Naming (sortList/sorList) is either wrong or very confusing.
There is no point in doing sortList = [].
You can probably break once you've done tandem_repeat[key] = True because new iterations won't do much anyway.

     print(max(k for k in tandem_repeat.keys() if tandem_repeat[k] is True))

might as well be :

     print(max(k for k,v in tandem_repeat.items() if v))


Readability

        int counter = 0;
        int num = 3;
        int index = 1;
        int[] primes = new int[100000000];
        primes[0] = 2;

I find this order confusing.  Consider

        // 2 is the first prime and the only one that is even, so process it separately
        int[] primes = new int[100000000];
        primes[0] = 2;
        int index = 1;

        // 3 is the next prime after 2; i.e. the first odd prime
        int candidate = 3;

Oops, did I forget something?  What happened to counter?  I took it out entirely as unnecessary.  As it was only used in the loop, if I had included it, it would have looked like

        for (int counter = 1; counter < primes.length; ) {

And I would have replaced the while loop as well.  But I actually think that it's easier to just remove counter and use index instead.  More on that later.

By breaking the code up into clumps and adding comments, it is easier to see how the lines of code relate to each other.  It was not obvious to me on first read that index indexed primes.  Now that is much clearer.  And it is clearer why it starts at 1 rather than 0.

I prefer the name candidate to num.  It is clearer about what is being tracked there.

Robustness

        while(counter < 99999999){

Why 99999999?  After staring at it for a bit, I realized that this is because counter is only counting the numbers after 2.  Why?  I would find it easier to say and understand

    while (index < primes.length) {

First I tried it with counter set to 1 initially.  But then I realized that that made counter an exact duplicate of index.  So we can ditch counter entirely.

For either, it is more robust to limit by primes.length.  In the original code, if you changed the length of primes, you had to manually change the loop definition to match.  This way, it will match automatically.

I also find it clearer to limit based on index, as that is what is actually problematic.

Delegate

Consider replacing the entire body of the main method with two method calls.

        int[] primes = findPrimes(100000000);
        displayPrimes(primes);

Now the main method itself does just one thing, call two methods.  Each method can do just one thing:

Set the primes array.
Display the primes.

Even better might be to add a Primes class.

        Primes primes = new Primes(100000000);
        primes.initialize();
        primes.display();

This also offers some efficiency optimizations that static methods don't.  More on that later.

Optimization

But your real question was optimization, so let's think about that.

All your candidates are going to be odd numbers.  You already took advantage of the fact that 2 is the only even prime.  You can take advantage of that again by rewriting isPrime to

    public static boolean isPrime(int candidate) {
        // 2 is the only even prime
        if (candidate % 2 == 0) {
            return candidate == 2;
        }

        if (candidate < 2) {
            return false;
        }

        return isOddPrime(candidate);
    }

And then

    // only returns useful results for odd numbers equal to 3 or more.
    private static boolean isOddPrime(int candidate) {
        for (int factor = 3; factor <= candidate / factor; factor += 2) {
            if (candidate % factor == 0) {
                return false;
            }
        }

        return true;
    }

How does this help?  Notice that the situations checked in isPrime will never return true for your candidates.  The smallest one is 3, so never less than or equal to 2.  You increment by 2, so never even.  So it will always drop through to the isOddPrime check.  Therefore, we can replace the isPrime call with an isOddPrime with no change in results.

And isOddPrime is more efficient.

It saves a modulus operation and two comparisons.

This should be obvious.  Those are in isPrime prior to the call to isOddPrime.  There's a third comparison that never runs on these candidates anyway, so we won't count that.
It only checks every other number, as it can skip all the even factors.

It uses the same start at 3 and increment by 2 logic as the main method.
It only checks factors up to the square root of the candidate.

This is probably the least obvious.  But factor <= candidate / factor is the equivalent of factor * factor <= candidate or factor <= sqrt(candidate) for all positive values of factor.

We can do this safely because at least one of any pair of factors must be less than or equal to the square root.  Otherwise their product will be greater than the number.

This won't matter much at the beginning, but there is a big difference between checking every number up to a thousand and every number up to a million.

Alternative

Instead of creating a new candidate factors list each time, use your primes instead.  This works best if you have a separate primes' class with something like

    int[] primes;

    public PrimesList(int size) {
        primes = new int[size];
    }

Now primes is available to every non-static method in the class.  So your isOddPrime could become

    private boolean isOddPrime(int candidate) {
        for (int prime : primes) {
            if (prime > candidate / prime) {
                return true;
            }

            if (candidate % prime == 0) {
                return false;
            }
        }

        return true;
    }

This saves checking non-prime odd numbers like 9, 15, 21, etc.  Those will never work because you already checked their factors.  E.g. for 35, you already checked that it's not divisible by 5 and 7, so you already know that 35 won't work.

Further

You optimized out even numbers.  It's also possible to optimize out candidates divisible by three.  Instead of incrementing by 2 every time, you can increment by 2 and then 4 and repeat that cycle.  So you'd check 5, 7, skip 9, 11, 13, skip 15, etc.   I won't go into this here, as it probably doesn't add much performance.  But here is an example that uses this optimization.

Sieve

The Sieve of Eratosthenes is another possibility, but sieves don't do so well with limits on the number of primes.  They are designed to be limited by the candidate pool.  So you might find yourself needing to implement a sieve with a rolling segment.  That's extra work, so you might prefer to avoid it.

An example of a windowed sieve that you could modify to work by segments.


Simple bash script for opening a repository in the browser from the command line

Some things:

You don't need the function keyword to define a function.
You can combine sed commands by separating them by ;: sed 's/\.git//;s/https:\/\///;s/ssh:\/\///;s/git:\/\///;s/git@//'
This can be shortened down to a single statement: sed 's/\(\.git\|https:\/\/\|ssh:\/\/\|git:\/\/\|git@\)//'
Fortunately you can get rid of picket fences in sed by using a different separator: sed 's#\(\.git\|https://\|ssh://\|git://\|git@\)##'
I'd use getopt or getopts for option handling. Which one to use is a bit of a religious issue, but getopt supports long options (--help and the like), while getopts is more portable.
It is recommended to use upper case only for variables exported in the shell, and lower case for other variables.
This is maybe more of a personal preference, but rather than creating a function called I'd create a script with the same name and move the contents of the browse-repository function to the end of the script. That way there's no pollution of the function name space, and no need to source the script. Just put it for example at /usr/local/bin/browse-repository and run. An added advantage of this is that you don't need the function name prefixes anymore.
I'm not sure how portable open is. On my system:

$ open http://www.example.org
Couldn't get a file descriptor referring to the console

Alternatively you could use x-www-browser, but I fear that's even less portable (Debian & derivatives only IIRC). I don't know if there's something more portable available.

All in all a very nice script.


CodeIgniter maintain data through Controllers

You need to extend CI_Controller with your code and extend your classses from your custom class, not default. I'll try to explain:

At first create MY_Controller.php at /application/core/ with next content:

     <?php

     class MY_Controller extends CI_Controller {
              function __construct() {
                      parent::__construct();
                          // Your checks here
              }
     }

     ?>

Now edit your controllers like this:

was

class Support extends Ci_Controller {

will be

class Support extends MY_Controller {

Now your controller will use constructor from your MY_Controller and still use CodeIgniter's default controller class.

You can read more from the manual.


The code you have is nicely formatted, and well documented, etc. ... but, as a singleton, it has a number of problems....

The two most glaring are:

It is not a singleton

Earth real = Earth.getInstance();
Earth.setEarth(null);
Earth alternate = Earth.getInstance();
if (real != alternate) {
   System.out.println("Oops...");
}

The synchronization.

You suggest in your comments that the getInstance() needs to be synchronized to avoid thread problems... but your other setter/getter methods are not synchronized.... as a result, threads all over the place can be getting stale, wrong, and otherwise incomplete populations, ages, etc.

As an example of a singleton 'best use case', this one has some problems... ;-)

But, that's sort of OK, since Earth has problems anyway!


Scheme has a built-in function called gcd, which computes the greatest common divisor. You don't need to write your own version. (gcd 1080 720) returns 360.

One other thing I should mention is that, as a matter of style, you should prefer to use quote rather than backquote if you have nothing to unquote.


Computing predicates of multiple items avoiding duplication of iteration code

Key here is to identify that both functions check whether there are at least n members that match a certain condition.

So we introduce a Matcher interface :

public interface Matcher<T> {

    boolean matches(T candidate);

}

Which we then use to make a method hasAtLeastNMatches(). And both methods can be implemented by calling that.

public class TeamValidator {

    public boolean isThereALeader(List<Member> team) {
        return hasAtLeastNMatches(team, Is.Leader, 1);
    }

    public boolean areThereAtLeast2NewJoiners(List<Member> team) {
        final DateTime aMonthAgo = DateTime.now().minusMonths(1);
        return hasAtLeastNMatches(team, Is.NewJoiner, 1);
    }

    private boolean hasAtLeastNMatches(Iterable<Member> members, Matcher<Member> condition, int minimumNumberOfMatches) {
        int count = 0;
        for (Member member : members) {
            if (condition.matches(member) && ++count >= minimumNumberOfMatches) {
                return true;
            }
        }
        return false;
    }

    private static enum Is implements Matcher<Member> {
        Leader {
            @Override
            public boolean matches(Member candidate) {
                return candidate.getRole().equals("Leader");
            }
        },

        NewJoiner {
            @Override
            public boolean matches(Member candidate) {
                return candidate.startingDate().isAfter(DateTime.now().minusMonths(1));
            }
        }
    }

}

Method hasAtLeastNMatches() can obviously also be reused ouside this class. In fact this kind of reuse is so common that several open source code projects offer these kinds methods and interfaces: e.g. Apache commons collections and Guava . In fact what I called Matcher they both call Predicate.


Generating parallel random numbers in a thread-safe way and using them in computations implemented by class method

what is the problem with just creating a range of random number generators from <random> and assign each to a thread?

Mind that using thread_local might not be a good way, as initialization of random number generators is costly. Also i do not know, how therngs would be seeded in a thread_local environement.


This might not really be an answer, but I suggest you to check out linq.js.
So yes, there is already an implementation of this and you can look at the code to compare and it will help the "learning purposes" you're aiming for.

Example implementation of any :

 // Overload:function()
    // Overload:function(predicate)
    Enumerable.prototype.any = function (predicate) {
        predicate = Utils.createLambda(predicate);

        var enumerator = this.getEnumerator();
        try {
            if (arguments.length == 0) return enumerator.moveNext(); // case:function()

            while (enumerator.moveNext()) // case:function(predicate)
            {
                if (predicate(enumerator.current())) return true;
            }
            return false;
        }
        finally {
            Utils.dispose(enumerator);
        }
    };

I personally don't have the required experience in JavaScript to give you my opinion on your implementation. Good luck !


Is this a fast implementation of reversing a string?

Over all, this is good, but there's unfortunately some very major performance problems, and I have a few minor design suggestions.

A string can be reversed quite trivially in linear time. Your algorithm is quadratic.

You can just do a single backwards loop over the input string instead of this convoluted nested loop.

Since mon_string_rev doesn't alter string it should be a pointer to constant character.

Instead of asserting that out isn't null, it might be better to simply return null instead. That allows the caller to handle the error instead of program termination (and when assertions are disabled, it avoids a rather nasty segfault...).

If you're using C99 or newer (and you should be), then declare variables in the tightest scope possible (i.e. declare i in the for loop).

return !1;... what? Just return 0, or, better yet, return EXIT_SUCCESS.

Any time you have an infinite loop terminated by a simple condition, just rewrite it to directly use that simple condition. Terminating 'infinite' loops are very hard to understand when you weren't the person who wrote them, so any time they can be avoided they should be.

Just to illustrate, your loop could instead be: for (; len >= 0; --len) { ... }.

It doesn't really apply here since instrumentation was clearly the main purpose, but in general it's a bad idea to have functions output anything unless their sole purpose is output. (Sorry if you already know this :).)

When it doesn't meaningful affect performance or usability, I like to have the caller manage memory. It's more flexible, and it's more explicit (no question of "wait... do I release this???").


Finding the root of a function by Bisection Method

A std::vector<T> vec is an arbitrary collection of Ts. vec might contain none, one or many elements. However, you want to model an interval, which consists of exactly two elements. A std::vector<T> therefore isn't the correct container for an interval.

You could use std::pair<double, double> instead, or just write your own variant:

struct interval_type {
    double lower_bound;
    double upper_bound;
};

Next, try to initialize the variables instead of just declaring them. While we're at it, try to come up with better names, e.g. instead of

  double a;
  double b;
  double c;

  a = interval[0];
  b = interval[1];

write

  double lower = interval.lower_bound; // if you use the struct from above
  double upper = interval.upper_bound;

c's scope is too large, by the way. It's just necessary inside the loop, so we can limit its life time, but we need to break in this case:

  do
  {
    const double midpoint = (lower + upper) / 2.0;

    if (f(midpoint) == 0)
    {
      a = midpoint;
      b = midpoint;
      break;
    }
    else
    {
      if (f(lower) * f(midpoint) > 0)
      {
        lower = midpoint;
      }
      else
      {
        upper = midpoint;
      }
    }
  } while (upper - lower > eps);

Other than that, the test f(value) == 0 is usually too strict, since floating point arithmetic can be a finicky beast. std::abs(f(value)) <= some_eps works well enough most of the times.

Other than that, I suggest you to allow other functions than a fixed f. Something along

template <typename F>
interval_type bisection(F && f, interval_type interval, double eps = 1e-8){

}

comes to mind. As you can see, there is no reason to change the interval in place. Just return a new one.


Calculator using Shunting Yard algorithm

Minor remarks:

The java convention is to put the opening { on the same line, not on a new line. It's great that you're consistent in your style though!
If you're doing the calculations using BigDecimal anyway, why not do that all the way and store the intermediat values as BigDecimal's as well in your stack?
method name isHighPrecedence wasn't immediately clear to me which one was the higher precedence. Not sure how to fix this one easily though.

Bigger idea:

I like how you used an enum for the Operators. This gives a nice list of all the possible (known) operators and an easy place to check if things like precedence are implemented correctly.

What I would do though, is go a step further. In java, an Enum is still a full class (except that all instances are created on class loading, you can't create new instances). This means that you can also provide methods there. I would expect the precedence comparison to be put in there. Although initially this might still be a bit clunky with the bracket handling (more on that later).

Another nice candidate is parsing an operator from a string. This can easily be implemented as follows:

    public static Operator from(String oper) {
        for (Operator operator : Operator.values()) {
            if (operator.sign.equalsIgnoreCase(oper)) {
                return operator;
            }
        }
        return NIL;
    }

What most people don't know, is that you can also override methods for each of the instances. The evaluate is a perfect candidate for this one. For example:

private enum Operator
{
    ADD(1, "+") {
        @Override
        public BigDecimal evaluate(BigDecimal left, BigDecimal right) {
            return left.add(right);
        }
    },
    SUBTRACT(2, "-") {
        @Override
        public BigDecimal evaluate(BigDecimal left, BigDecimal right) {
            return left.subtract(right);
        }
    },
    ... [include all operators here]
    };

    final int precedence;
    final String sign;

    Operator(int precedence, String sign)
    {
        this.precedence = precedence;
        this.sign = sign;
    }

    public abstract BigDecimal evaluate(BigDecimal left, BigDecimal right);

That way, if you have an operator you can just call
outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));

Changing the operator stack to actually contain Operator instead of String got me in a little bit of trouble storing the opening bracket on there. Since the idea is to first parse the operand from the input string, let's also add an Operand for the closing bracket, and a default option for a missing operand (that we can abuse for number inputs as well).

    OPEN_BRACKET(0, "(") {
    @Override
        public BigDecimal evaluate(BigDecimal left, BigDecimal right) {
            throw new IllegalStateException("Cannot apply bracket operand to left and right numbers");
        }
    },
    CLOSE_BRACKET(0, ")") {
        @Override
        public BigDecimal evaluate(BigDecimal left, BigDecimal right) {
            throw new IllegalStateException("Cannot apply bracket operand to left and right numbers");
        }
    },
    NIL(0, "") {
        @Override
        public BigDecimal evaluate(BigDecimal left, BigDecimal right) {
            throw new IllegalStateException("trying to evaluate invalid operator");
        }
    };

updating the evaluateExpression method to work with Operators required a little bit of reordering to handle the numbers correctly again:

public static BigDecimal evaluateExpression(String infix)
{
    Stack<Operator> operatorStack = new Stack<>();
    Stack<BigDecimal> outputStack = new Stack<>();

    for (String currentToken : infix.split("\\s"))
    {
        Operator currentOperator = Operator.from(currentToken);
        if (currentOperator == Operator.OPEN_BRACKET)
        {
            operatorStack.push(currentOperator);
        } else if (currentOperator==Operator.CLOSE_BRACKET)
        {
            while (Operator.OPEN_BRACKET.equals(operatorStack.peek())) {
                Operator higherPrecedenceOperator = operatorStack.pop();
                BigDecimal operandLeft = outputStack.pop();
                BigDecimal operandRight = outputStack.pop();
                outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));
            }
            operatorStack.pop();
        } else if (currentOperator != Operator.NIL)
        {
            while (!operatorStack.isEmpty() && operatorStack.peek().isHigherPrecedence(currentOperator)) {
                Operator higherPrecedenceOperator = operatorStack.pop();
                BigDecimal operandLeft = outputStack.pop();
                BigDecimal operandRight = outputStack.pop();
                outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));
            }
            operatorStack.push(currentOperator);
        } else
        {
            outputStack.push(BigDecimal.valueOf(Integer.valueOf(currentToken)));
        }
    }

    while (!operatorStack.empty())
    {
        Operator higherPrecedenceOperator = operatorStack.pop();
        BigDecimal operandRight = outputStack.pop();
        BigDecimal operandLeft = outputStack.pop();
        outputStack.push(higherPrecedenceOperator.evaluate(operandLeft, operandRight));

    }
    return outputStack.pop();
}

This got me thinking. What do we have to change to allow the bracket operantors to just evaluate similarly to the other operators instead? We could first update the current evaluate method to take the outputStack instead of a left and right operand. That way the Operator can decide how many numbers it needs. Specifically for the brackets, we also need to pass in the Operator stack so that the opening bracket can just push itself on the stack, and the closing bracket can pop the stack untill it finds an opening bracket.

private enum Operator {
    ADD(1, "+") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            BigDecimal right = numbers.pop();
            BigDecimal left = numbers.pop();
            numbers.push(left.add(right));
        }
    },
    SUBTRACT(2, "-") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            BigDecimal right = numbers.pop();
            BigDecimal left = numbers.pop();
            numbers.push(left.subtract(right));
        }
    },
    MULTIPLY(3, "*") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            BigDecimal right = numbers.pop();
            BigDecimal left = numbers.pop();
            numbers.push(left.multiply(right));
        }
    },
    DIVIDE(4, "/") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            BigDecimal right = numbers.pop();
            BigDecimal left = numbers.pop();
            numbers.push(left.divide(right));
        }
    },
    OPEN_BRACKET(Integer.MIN_VALUE, "(") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            operatorStack.push(this);
        }
    },
    CLOSE_BRACKET(Integer.MAX_VALUE, ")") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            while (!operatorStack.isEmpty() && operatorStack.peek() != OPEN_BRACKET) {
                operatorStack.pop().evaluate(numbers, operatorStack);
            }
            if (operatorStack.isEmpty()) {
                //no open bracket found!
                throw new IllegalStateException("closing bracket requires earlier matching opening bracket");
            }
            operatorStack.pop();
        }
    },
    NIL(0, "") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            throw new IllegalStateException("trying to evaluate invalid operator");
        }
    };

    private final int precedence;
    private final String sign;

    Operator(int precedence, String sign) {
        this.precedence = precedence;
        this.sign = sign;
    }

    public static Operator from(String oper) {
        for (Operator operator : Operator.values()) {
            if (operator.sign.equalsIgnoreCase(oper)) {
                return operator;
            }
        }
        return NIL;
    }

    public boolean isHigherPrecedence(Operator other) {
        return this.precedence <= other.precedence;
    }

    public abstract void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack);
}

Quick note that I also updated the priority values for the open and close brackets so that they're handled correctly while going through the stack. This way we can greatly simplify the evaluateExpression implementation as well:

public static BigDecimal evaluateExpression(String infix) {
    Stack<Operator> operatorStack = new Stack<>();
    Stack<BigDecimal> outputStack = new Stack<>();

    for (String currentToken : infix.split("\\s")) {
        Operator currentOperator = Operator.from(currentToken);
        if (currentOperator == Operator.NIL) { //number (or error from unknown operator?)
            outputStack.push(BigDecimal.valueOf(Integer.valueOf(currentToken)));
        } else {
            while (!operatorStack.isEmpty() && !operatorStack.peek().isHigherPrecedence(currentOperator)) {
                Operator higherPrecedenceOperator = operatorStack.pop();
                higherPrecedenceOperator.evaluate(outputStack, operatorStack);
            }
            operatorStack.push(currentOperator);
        }
    }

    while (!operatorStack.empty()) {
        operatorStack.pop().evaluate(outputStack, operatorStack);
    }
    return outputStack.pop();
}

The best part about implementing the Operators this way? We can easily add new operators, and they're not limited to 2 operands either! For example, adding the following Operand to the enum class:

    ABS(5, "abs") {
        @Override
        public void evaluate(Stack<BigDecimal> numbers, Stack<Operator> operatorStack) {
            numbers.push(numbers.pop().abs());
        }
    },

is all we need to do to then input things like "abs -2" which gets resolved to "2".


Keeping only maximum date rows in a group

You can use ROW_NUMBER to rank your data according to date for each combination of id and question; then simply select the row with a ROW_NUMBER of 1:
WITH tbl_max_date AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY id, question ORDER BY date DESC) AS rn
  FROM tests2.o1.mc
)
SELECT *
FROM tbl_max_date
WHERE rn = 1

If you could have more than one row with the same maximum value per group, you can use RANK in place of ROW_NUMBER, as that will give all rows with the same value the same ranking. For example:
WITH tbl_max_date AS (
  SELECT *,
         RANK() OVER (PARTITION BY id, question ORDER BY date DESC) aS rn
  FROM tbl_src
)
SELECT *
FROM tbl_max_date
WHERE rn = 1


PHP checking for array key or using default value

One quick change you can do is making use of ternary operator instead of writing if else block.

$my_variable = array_key_exists('possible_key', $array)
               ? $array['possible_key']
               : 'my default value';


I just wanted to write that the code looks completely fine to me, until...
assertEquals(false, isBalanced("[["));

I''m sure you'll find the error :-)
Otherwise two small remarks:

Personally I'd have the function return true for an empty string instead of throwing an exception.

Stack is outdated. I'd use a Deque implementation instead.

EDIT: I'm sorry, but I just realized something else: Your program doesn't fulfill the requirement O(n/2) for space complexity.


Math.pow(x, 2) -> x*x

A pet peeve of mine is people calling Math.pow() just to square a number.  To me it seems faster and simpler to just multiply the value by itself.

Shadowing variable names

In interact(), you use the variables x and y.  I would avoid using variable names that shadow instance variables.  I would call these variables dx and dy instead.

X and Y distances

Look closely at your x/y distance calculations functions:

public double calculateDistX(Body other) {
    double x1 = this.getX();
    double x2 = other.getX();
    return Math.sqrt(Math.pow(x2 - x1, 2));
}

It actually just does this:

public double calculateDistX(Body other) {
    return Math.abs(this.getX() - other.getX());
}

This shorter version is also less prone to roundoff errors.  But in fact, I would even remove this function, because it will be more useful to use to preserve the sign of the subtraction than to hide it (read below)

Splitting up interact and update

Your interaction function should do no more than modify the acceleration of the object.  Once the body has interacted with all other bodies, its acceleration will have the final acceleration for that timeslice.  After that, you should have an update function which takes the acceleration and applies it to the velocity, and then applies the velocity to the position.  I'll show an example of that below.

Simplifying the interaction function

Looking at your interaction function, there are a lot of places that can be simplified.  First, if you retained the sign of the x/y distances, you wouldn't need all those if statements.  Second, a lot of the force calculations are related to each other and can be merged into a smaller set of calculations.  In fact, when I rewrote your function, it became this simple:

public void interact(Body other) {
    double dx = other.getX() - x;
    double dy = other.getY() - y;
    double r  = calculateDistance(dx, dy);
    double r3 = r * r * r;

    /* calculate accelerations for both bodies */
    ax += other.getMass() * dx / r3;
    ay += other.getMass() * dy / r3;
    other.addToAx(mass * -dx / r3);
    other.addToAy(mass * -dy / r3);
}

public void update() {
    vx += ax;
    vy += ay;

    ax = 0;
    ay = 0;

    x += vx;
    y += vy;
}

Further simplifications

If you don't actually need the current velocity of the object other than to update the position (e.g for collisions), you can get rid of the acceleration entirely and operate directly on the velocity.

Edit: Also, I think that multiplications are faster than divisions, so you could also invert r3 so that you only need to do one divide.  You can also precompute dx/r^3 and dy/r^3 to reduce the number of multiplies:

public void interact(Body other) {
    double dx = other.getX() - x;
    double dy = other.getY() - y;
    double r  = calculateDistance(dx, dy);
    double inv_r3 = 1.0 / (r * r * r);

    /* Precalculate force component (1/r^2) times direction (dx/r) = dx / r^3 */
    dx *= inv_r3;
    dy *= inv_r3;

    /* calculate accelerations for both bodies */
    vx += other.getMass() * dx;
    vy += other.getMass() * dy;
    other.addToVx(mass * -dx);
    other.addToVy(mass * -dy);
}

public void update() {
    x += vx;
    y += vy;
}


Sieve of Eratosthenes performance; Scala very slow compared to Node.js

Lists vs. Arrays

The Scala version of your code ran surprisingly slower because you used a ListBuffer. In Scala you can think of a List as a traditional linked-list. Lists don't provide random access to their contents. That is, accessing an object at index n requires O(n) time. This really slowed down your code because you index into A in both your inner and outer for-loop.

To fix this problem you can simply use a different data structure like an Array.

object Sieve extends App {
  val n = 100000
  val a = Array.fill(n + 1)(true)
  a(0)  = false
  a(1)  = false
  val k = scala.math.sqrt(n).toInt

  for (i <- 2 to k; if a(i))
    for (j <- i * i to n by i)
      a(j) = false

  val res = a.zipWithIndex.filter(_._1).map(_._2)
  assert(res.length == 9,592)
}

Other Notes

_._1 represents accessing the first element in a tuple
Tuples are one indexed
So if we have a tuple t we can access the 5th element with t._5
The first underscore is what is known as placeholder syntax. For example:

    val a = List.range(0, 9)
    val b = a.map(i => i + 1)
    val c = a.map(_ + 1)       // placeholder syntax

In the above code snippet b and c are equivalent
When we are using a map operation on a List of tuples we can combine the tuple element access operator (t._N) and placeholder syntax. As a result we get code that looks something like:

    val res = a.zipWithIndex.filter(_._1).map(_._2)


weird function name pyth

Did you mean pythagoras? Oh, no, you meant distance.

what does bezier do?

What are f,g? It looks like it returns two values based on t, but it is not clear to me what the expressions signify. How did you get those expressions?

It probably derives somehow from f(x) = sqrt(1-x^2) and its derivatives.

Maybe it would help if you could show us what the code looks like for the arclength of the arc formed by f(x) = 1 between -1 and 1 (it should return 2).

arc length algorithm

Also, the arc-length runs the risk of running into a recursion-error. And it's slow due to function calls.

Suggested implementation (typed on phone, untested):

def arclength(f, low, high, error):
    p_low, p_high = f(low), f(high)
    length = 0
    todo = [(low, high, p_low, p_high, distance(p_low, p_high))]

    while todo:
        segment = todo.pop()
        middle = (segment[0] + segment[1])/2
        p_middle = f(middle)
        d_left = distance(p_middle, segment[2])
        d_right = distance(p_middle, segment[3])

        if abs(d_left + d_right - segment[4]) < error:
            length += d_left + d_right
        else:
            todo.append((low, middle, p_low, p_middle, d_left))
            todo.append((middle, high, p_middle, p_high, d_right))

    return length

This has the following invariants on todo

all tuples are of the form (t0, t1, f(t0), f(t1), distance(f(t0), f(t1))).
at each iteration, a segment is split in two
if the change in value from splitting up is small enough, the resulting length is added to length
else: the separate segments are both added back to todo.

(The f is in this case bezier, this allows you to replace it with other curve-defining functions like (cos(t), sin(t)))


Keep your global environment clean - no need to define nums and numVals globally. Just create them in the main function and pass them to the appropriate functions.

nums := initSlice(size)

You can save on memory by creating the sortArr array at the initialization phase, and pass it along with arr.

go mergeSort(arr[:len(arr)/2], res[:len(sortArr)/2], leftMS)
go mergeSort(arr[len(arr)/2:], res[len(sortArr)/2:], rightMS)

You can init numVals to 100 and then change it if an arg was provided:

size := 100
if len(os.Args) >= 2 {
    size, _ = strconv.Atoi(os.Args[1])
}

Add a buffer to leftMS and rightMS. This way their goroutines will be closed when they are done. Currently if the right side is done before the left, then it will have to wait because you are reading leftMS first.

leftMS, rightMS := make(chan []byte, 1), make(chan []byte, 1)

Comments always start with an empty space: //Combine both sides -> // Combine both sides


Making a list from user input - follow-up

The PEP8 document I linked to in my answer on your previous question has a section around imports and how you should structure them. Some of the main points:
# This is ok.
from tkinter.filedialog import askopenfilename, asksavefilename

# System libraries, then 3rd party, then local
import sys
import tkinter
import mymodule

As a general guideline, it is not prudent to do: from module import *. This is because that single line imports ALL submodules in a module which, depending on how large the module is, can pull in a lot of extra, not needed stuff.
Now, I will not tell you which imports you don't need, mainly because I feel that the 'how' and 'what' ideas behind imports is something best learned on your own with some light prodding and guidance. I will say this, these two import statements are equivalent:
import tkinter
tkinter.filedialog.askopenfilename(...)

from tkinter import askopenfilename
askopenfilename(...)

Using the above ideas, you'll find you have a few not-needed imports. Also, a quick search-and-find in a text editor will show another import that is not needed (HINT: search for showerror).
As another rule of thumb: import only what you need and be as specific as is prudent.


Lowest Common Multiple of 1 to n in Ruby

Definitely your code looks like C directly translated to Ruby. Let's refactor the first two methods:

def prime?(n)
  (2..n-1).none? { |x| n % x == 0 }
end

def primes_upto(n)
  (2..n-1).select { |x| prime?(x) }
end

Of course prime? should be checking only 2 and odd numbers until sqrt(x) as candidates. Although you probably should be using the library in the core: Prime.

Calculating the lcd using a table is a possible way to do it, granted, but having the standard formula lcm(a, b) = a * b / gcd(a, b), and gcd being easily calculated with Euclides algorithm, well, I don't see why you'd choose that other way.

Anyway, note that to get the lcm of three numbers you can do lcm(a, b, c) = lcm(a, lcm(b, c)) (you get the idea for N numbers), and since Ruby >= 1.9 has Integer#lcm, you could simply write a left fold of the range:

(1..20).reduce(:lcm) #=> 232792560

BTW, that's how you could implement Integer#lcm in 1.8, a direct translation of the formulas:

class Integer
  def gcd(b)
    b == 0 ? self : b.gcd(self % b)
  end

  def lcm(b)
    (self * b) / self.gcd(b)
  end
end

A final advice: project-euler is about maths. When doing maths you should try to use expressions (functional programming) instead of statements and change of state (imperative programming). Try to do these problems without any of these: each, var = some_initial_value, push, bang_methods!, break, return, *=, +=, delete, while, ... Instead, you should be using: map, select, reduce, detect, zip, any?, all?, flatten, take_while, lazy (Ruby 2.0)... More on functional programming with Ruby.


Some notes:

(photos, identification, testers, id) = ([], [], {}, 0)

may become

photos, identification, testers, id = [], [], {}, 0

as parentheses are superfluous (and even it's recommended not use them).

for (subdirectorys, directorys, files) in os.walk(dir):

may become

for __, directorys, __ in os.walk(dir):

as the names subdirectorys and files are never used (not two consecutive underline symbols - __ - for ignoring their values).

Instead of maintaining the value of id manually (initializing it to 0 and then increase it by id += 1) you may use Pythonic way with help of enumerate() function - the very first line of you code will totally omit id:

photos, identification, testers = [], [], {}

and your for loop

    for subdirectory in directorys:

becomes

    for id, subdirectory in enumerate(directorys):

Two notes about your if statement

        if(f_extension.lower() not in
                ['.png','.jpg','.jpeg','.gif','.pgm']):

Python is not C/C++/Java, so outermost parentheses are superfluous.
Your may prepare your list of extensions in advance

    EXTENSIONS = '.png .jpg .jpeg .gif .pgm'.split()       # split() creates a list

(nice method for saving some typing, isn't it?), and then use it:

    if f_extension.lower() not in EXTENSIONS:

(note the use of uppercase letters for a constant list).


If you don't need to count the number of occurences, use a Set:

private readonly ISet<string> data = new HashSet<string>();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData);
}

If you need to count the occurences, you should use a Dictionary:

private readonly IDictionary<string, int> data = new Dictionary<string, int>();

public void AddNewData()
{
    string someData = GetData();
    if (data.ContainsKey(someData))
    {
        data[someData]++;
    }
    else
    {
        data[someData] = 1;
    }
}

Alternatively, you could just use a List and calculate the counts when you need them, using the LINQ GroupBy extension method:

private readonly ICollection<string> data = new List<string>();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData); // data might contain duplicates
}

public void PrintData() // use LINQ to count number of occurences
{
    foreach (var entry in data.GroupBy(x => x))
    {
        Console.WriteLine("{0} {1}", entry.Key, entry.Count());
    }
}


String reversal, capitalize vowels, lowercase consonants

We have a namespace called StringOperation,
a class called Program,
and methods called Main,
ProcessInput, Shift,
regions called Entry, Logic.

Looking from a high level,
this program could do anything,
as these terms are completely meaningless.
Strive to find more meaningful names for your program elements,
so that readers can have a clue what the program is about without having to fully read the implementation.
If I can see in front of me the logical pieces of the puzzle,
the mental burden of understanding what goes on in each element would be much reduced.

I know that all self-respecting programmers know by heart that 97 means the ASCII code of the letter A, 101 the letter E, 105 the letter I, ...
Wait a minute, no, actually that's not a requirement,
I don't think anybody should have to know at a glance what these numbers mean in your case statements.
A better way would be to write like this:

case 'A':
case 'E':
case 'I':
// ...


DISCLAIMER: You haven't properly defined "better" so I'll assume you're talking about performance

You're fixing the wrong problem.

Under the assumption that your retailer is an instance of some Retailer POCO, you should properly normalize your data and extract the Address data into a separate Table / POCO.

Then you can stop generating HTML in some Controller code and instead do something like:

retailer.Address.ToHTMLString();

This is significantly cleaner and allows central modification of "ToHTML" rules.

In addition to that I don't think you actually have to care about the performance difference between these two. Have you profiled your code and proved that this is the bottleneck? If it isn't.... It's good enough I'd say.
You seem to be falling prey to the problems described in Eric Lippert's Performance Rant


Registering multiple keypresses simultaneously, very slow

What is impacting you performance so heavily is the creation of Tuples everytime you recieve a keypressed event.

creating objects is slow. What you should do instead is, directly apply the changes to the moving objects (your two pong-thingies).

private void GameForm_KeyDown(object sender, KeyEventArgs e)
{
   var pressedKeys = inputKeys.Where(key => Keyboard.GetKeyState(key));
   foreach(Keys key in pressedKeys)
      switch(key){
         case Keys.Up:
             leftPong.Positon += FIXEDVALUE;
             break;
         case Keys.Down:
             leftPong.Position -= FIXEDVALUE;
             break;
         //continue...


Excluding a long list of words with grep

First of all, avoid excessively long lines that force reviewers to scroll horizontally far far right. You can break lines to manageable length like this:

MANWIDHT=80 man "$LINE" | head -20 | grep -v NAME | grep -v 1 | \
grep -v SYNOPSIS | grep -v SYNOPSYS | grep -v OVERVIEW | grep -v VERSION | \
grep -v VERSION | grep -v INTRODUCTION | grep -v 5 | grep -v ABSTRACT | \
...

You are using too many temporary files. You could chain the commands together in a single pipeline, without unnecessary temporary files:

compgen -c | while read -r LINE; do
    MANWIDHT=80 man "$LINE" | head -20 | grep -v NAME | ...
done | sed -e 's/^$/%/' > fortune-rtfm

Instead of a chain of grep -v word1 | grep -v word2 | grep -v word3,
you can use a single grep with multiple -e parameters like this:

grep -v -e word1 -e word2 -e word3

A single grep process instead of dozens will certainly run much faster.

A simple echo is the same as echo -en '\n', but better in every way.

Finally, instead of a long grep with all the terms you want to exclude, you can put them in a file, one word per line, and use the -f flag of grep to use that list. Then the script can be shortened to:

#!/bin/bash

compgen -c | while read -r LINE; do
    MANWIDHT=80 man "$LINE" | head -20 | grep -v -f words.txt | grep -v '^$' && echo
done | sed -e 's/^$/%/' > fortune-rtfm

@Sundeep pointed out a few important things in a comment. MANWIDHT is misspelled, it should be MANWIDTH.
Also, since the patterns are fixed strings (as opposed to regular expressions), it's good to add the -F flag so that grep can optimize the matching. Lastly, you might want to match whole words instead of parts of words. If that's the case, add the -w flag. This is equivalent to wrapping each pattern within \<...\>. (The effect is that for example "VERSIONING" is matched by grep VERSION, but by grep -w VERSION.)

The content of words.txt, sorted for easier reading, is something like this (just the first bunch of lines):

1
2
3
4
5
8
ABRT
ABSTRACT
ARGUMENTS
AUTHOR
CHECK
COMMAND
COPYING
... (and so on)

If you want to keep all the patterns inside your script file, you can do that too, for example like this:

compgen -c | while read -r LINE; do
    MANWIDHT=80 man "$LINE" | head -20 | grep -vFf <(cat << EOF
1 2 3 3 4 5 8
ABRT ABSTRACT ARGUMENTS AUTHOR
CHECK COMMAND COPYING COPYRIGHT
DESCRIPTION DOCUMENTS Description
EXAMPLE
FORTUNE
Help
INTRODUCTION Introduction
Local
NAME NOTE Name Note
OPTIONS OVERVIEW
PROLOG
QUERYING
SEE STATUS SUMMARY SYNOPSIS SYNOPSYS SYNTAX
UNIX USAGE Usage
VERSION
case
EOF
) | grep -v '^$' && echo
done | sed -e 's/^$/%/' > fortune-rtfm


Not being able to use the standard libraries suggests you are doing embedded work.  A more typical approach for calculating sine in that situation would be to:

Translate angles from a 360 degree system to a 256 degree system;
Store sine values for all 256 possible degrees in a lookup table.

You lose a lot of accuracy, but you gain a lot of speed.


Blurring a given image using moving average in Python 3

First, I think this code arguably abuses tuple destructuring to declare and reassign variables. Declaring multiple variables on a line generally hurts readability, just to save a line/some keystrokes. I would write everything out fully, even if that comes with the cost of verbosity. I'd also space it out a bit:

def my_blur_image1(a):
    result = []
    for i in range(len(a)):
        row = []
        for j in range(len(a[i])):
            total = a[i][j]
            count = 1
            if i + 1 < len(a):
                total += a[i+1][j]
                count += 1

            if j + 1 < len(a[i]):
                total += a[i][j+1]
                count += 1

            if i - 1 > -1:
                total += a[i-1][j]
                count += 1

            if j - 1 > -1:
                total += a[i][j-1]
                count += 1

            row.append(round(total/count, 2))

        result.append(row)

    return result

Twice, you have something along the lines of

lst = [] # Create a list
for i in range(len(a)):
    res = # Calculate some result
    lst.append(res)

I think the logic could be broken up, and could make use of some list comprehensions. This is basically the scenario that list comprehensions (and map) are intended for. Iterating over a list to produce a new list is a very common operation.

I'm not necessarily recommending this way, but it does show an alternative, more functional way of approaching the problem. I'll say that my way ended up a fair bit slower than yours. On my machine, yours takes roughly 14 seconds for a 2000x2000 matrix, while my version takes 25 seconds unfortunately. You didn't tag performance though :D

# Returns whether or not i,j is inbound for a given a matrix
def inbounds(i, j, a):
    return 0 <= i < len(a) and \
           0 <= j < len(a[i])

# Returns the inbound pixel values on and surrounding the given point
def inbound_pixels_around(i, j, a):
    # I figured it was best to hard-code the indices instead of using several "if"s like you had done
    # That way, I can make use of looping to reduce some duplication
    # If diagonal pixels were included, this could be generated by another comprehension instead
    indices = [(i, j), (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]

    # Iterate over the indices.
    # Remove the ones that are  out of bounds, and use the inbound ones to index the list
    return [a[i][j] for (i, j) in indices if inbounds(i, j, a)]

def my_blur_image2(a):
    # A 3D-array. Each pixel has been replaced by a list of inbound neighbor values
    inbound_neigh_rows = [[inbound_pixels_around(i, j, a) for j in range(len(a[i]))]
                          for i in range(len(a))]

    # Then iterate ever each set of neighbors, and divide the sum of the neighbors by their length
    # This does away with needing an explicit "count" variable
    return [[sum(neighs) / len(neighs) for neighs in row]
            for row in inbound_neigh_rows]

I'm making fairly extensive use of list comprehensions here. I'm using them to filter out non-inbound cells in inbound_pixels_around using inbounds, and to generate neighbors and their average values in my_blur_image2.

test_data = [[1, 2, 3],
             [4, 5, 6],
             [7, 8 ,9]]

print(blur_image(test_data))
print(my_blur_image1(test_data))
print(my_blur_image2(test_data))

[[2.33, 2.75, 3.67], [4.25, 5.0, 5.75], [6.33, 7.25, 7.67]]
[[2.33, 2.75, 3.67], [4.25, 5.0, 5.75], [6.33, 7.25, 7.67]]
[[2.3333333333333335, 2.75, 3.6666666666666665], [4.25, 5.0, 5.75], [6.333333333333333, 7.25, 7.666666666666667]]

Updated to make use of comparison chaining. Thanks @Mathias.


Traversing un-ordered list and appending attibute values to the list item

Here are some tips:

1) Don't create variables if they're only used once or are a don't perform complex operations.

Old Code:

var num_sub_uls = $sub_uls.length;
var count_icount = 0;
if(num_sub_uls > 0) {

New Code:

var count_icount = 0;
if($sub_uls.length) {

2) Provide the base when using parseInt().

Old Code:

count_icount = parseInt($child_a.attr('data-icount'));

New Code:

count_icount = parseInt($child_a.attr('data-icount'), 10);

3) Eliminate commented code sections.

Old code:

var sub_lis = $sub_uls.find('a');
//console.log('Total anchors: '+sub_lis.length);
sub_lis.each(function(index2) {

New Code:

var sub_lis = $sub_uls.find('a');
sub_lis.each(function(index2) {

4) Simplify if conditions by using Truthy & Falsey .

Boolean(undefined); // => false
Boolean(null); // => false
Boolean(false); // => false
Boolean(0); // => false
Boolean(""); // => false
Boolean(NaN); // => false

Boolean(1); // => true
Boolean([1,2,3]); // => true
Boolean(function(){}); // => true

More here

Old Code:

if(num_sub_uls > 0) {

New Code:

if(num_sub_uls) {

5) Use .append() to append text to an element in jQuery.

Old Code:

var a_txt = $child_a.text();
$child_a.text(a_txt+' ('+count_icount+') ');

New Code:

$child_a.children('a').append( ' (' + count_icount + ') ' );

6) Simplify your if and else conditions.

Check if count_icount is greater than 0, instead of checking for sub_list.length;

Old Code:

if(num_sub_uls > 0) {
    var sub_lis = $sub_uls.find('a');
    sub_lis.each(function(index2) {
        count_icount += parseInt($(this).attr('data-icount'));
    });
} else {
    count_icount = parseInt($child_a.attr('data-icount'));
}

New Code:

$sub_uls.find('a').each(function(index2) {
    count_icount += parseInt($(this).attr('data-icount'));
});
if( !count_icount ){
    count_icount = parseInt($this.children('a').attr('data-icount'), 10);
}

7) Use .data() instead of .attr() to access properties that begin with data-.

.data() Documentation

Example:

Fruits

Use

$("#thing2").data( "icount" ) == "9";

Instead of

$("#thing2").attr( "data-icount" ) == "9";

Final code:

$(function () {
    $("#tree li").each(function () {
        var $this = $(this),
        count_icount = $this.find("a").data('icount');

        $this.children('ul').find('a').each(function () {
            count_icount += parseInt($(this).data('icount'), 10);
        });
        if (!count_icount) {
            count_icount = parseInt($this.children('a').data('icount'), 10);
        }
        $this.children('a').append(' (' + count_icount + ') ');
    });
});

Demo: http://jsfiddle.net/GQkB8/2/


Project Euler 8: Largest product in a series in Functional Programming (FP)

Some notes about your code:

(function () {. Is this old-style wrapping really needed? Isn't this a node.js script?
You parsed INPUT manually from the question. You should probably leave the input as similar as possible to how it's stated and do the parsing programatically.
const multiply = (acc, val) => acc * val;: The variable names reveal how the function is used; instead, keep it generic: const multiply = (x, y) => x * y;. Consider also creating the abstraction product, the product of all numbers in an array.
parser(latestMaxProduct, number.slice(1)); You should use recursive calls as a last resort, only when higher-level abstractions (map, filter, reduce, ...) are not enough.
I'd separate generic functions from the specific code used in the problem. Re-using generic abstractions is one the fundamental principles of FP.

I'd write:

const range = (start, end) => Array.from(new Array(end - start), (x, i) => i + start);
const groupsOf = (xs, n) => range(0, xs.length - n + 1).map(i =>  xs.slice(i, i + n));
const product = xs => xs.reduce((acc, x) => acc * x, 1);
const maximum = xs => Math.max(...xs);

const euler8 = () => {
  const unparsedDigits = `
    73167176531330624919225119674426574742355349194934
    96983520312774506326239578318016984801869478851843
    ...
  `;
  const groupSize = 13;

  const digits = unparsedDigits.replace(/[^\d]/g, "").split("").map(c => parseInt(c));
  return maximum(groupsOf(digits, groupSize).map(product));
}

console.log(euler8());


Batch file for looking through text files

With the help of a Windows user in chat (Thank's Simon!), we've got a much better solution figured out:

@echo off
set /p Food="What would you like to eat? "
set "Food=%Food% |"
findstr /C:"%Food%" Menu.txt
pause

This will concatenate the pipe character to the end of the user-entered string and find the line that begins with that literal string.

Ordinarily, findstr expects a space delimited list of words to search for.  Using the /C: flag will look for the literal string rather than breaking the string up into separate strings and finding each individual word.

As long as your Menu.txt file maintains the format "MenuItem | Description", this .bat file will work and you won't have to edit it each time you edit your menu.

You just have to keep the formatting and don't put the pipe character anywhere else in the file.