It just feels like additional work using so many methods as opposed to directly accessing the field.

Is it really? You have this:

g.drawImage(player.getImage(), player.getX(), player.getY());

With direct access, it would be:

g.drawImage(player.image, player.location.getX(), player.location.getY());

Which actually seems more complicated to me. It's longer, and you have to know of what type location is. Additionally, any decent IDE can generate fields plus getters and setters for you.

But the actual point of using getters and setters is that it encapsulates your code. For example, if you want to switch from using Point to using some other class. With getters/setters, you only have to change your Entity class, instead of that class plus your main plus maybe others.

Misc

correct indentation makes your code easier to read
your fields actually should not be protected, but private
I would not just print the stack trace inside the entity class, but thrown an exception and handle it elsewhere (just swallowing the exception will cause problems further on, because now the image is null). You could also try to recover by using a generic generated error image instead, so your application still works if one image file is damaged/lost


Open/Closed Principle with calculating the total cost of items in a shopping cart

Basics

String comparison shouldn't be done with ==, unless you can carefully ensure you're using String.intern() everywhere so that the reference comparison will always match appropriately (not to forget the documentation too).
Keep your fields private!
Should PaymentCalculator.calculatePrice(OrderItem) really return 0 if there are no matching rules? That's like saying I can get oranges for free for a payment calculator that only (accidentally?) handle apples...

Rule-based vs if statements

// Add new rules here to support new SKUs. But why is this better
// than adding if/else in the old design? Because even this class
// changes as we add more requirements right?

You can think of it that the calculation logic is not baked into the payment calculator, and that the logic can be maintained separately. For example, a more complex IPriceRule implementation might be retrieving prices from a database, and the calculator does not need to deal with any database connections know-how.


strlen and strcmp implementation in x86 FASM assembly

strlen

Correctness (Return Value): You are violating the convention for the strlen function, which is documented as returning the number of characters between the beginning of the string and the terminating null character without including the terminating NUL character. Your code includes the terminating NUL, given the position of the inc ebx instruction.

This may be fine if you control both the function's implementation and its usage, but it is confusing because it defies programmers' expectations and will be a recurring source of bugs. If you're going to return a length that includes the terminating NUL, you should consider calling your function something different than strlen.
Interface (ABI): All x86 calling conventions return a function's result in the eax register. Although you have documented your function as returning the result in ebx, this is utterly bizarre and is guaranteed to trip up every programmer who ever uses your code. When writing everything in assembly, you are of course free to define your own custom calling conventions, but you should only do so when there is a good reason (like an optimization possibility). I can't see a good reason here. It would be just as easy for you to arrange for your code to produce the result in eax, right where programmers will expect it to be.

It is also somewhat unusual to pass an argument in the eax register, but calling conventions vary in which registers they use to pass arguments, so this isn't flying in the face of every convention ever and is therefore more excusable. However, when you're writing in assembly and you have the opportunity to make these types of decisions, you should consider your choices carefully: what makes the most sense? what will be the easiest to use? what will be the most flexible? what will be the most efficient? Have a good reason for your choice! In this case, passing a pointer in eax makes little sense, since eax is almost universally used for return values, and pointers are almost never going to be the return value of a function. By choosing eax as the input register, you've virtually guaranteed that every caller will need an extra mov instruction to shuffle the input parameter into the appropriate register. Why create this situation when you don't have to?
Style (Indentation): The way you've indented the code, with the labels at the same level as the instructions, makes it difficult to read because all of the instructions aren't lined up. Instead, consider outdenting the internal labels (branch targets) so that they match the function name (external symbols). That will allow all instructions in the function to be lined up at the same vertical column, and thus allow anyone reading the code to skim it easily.

(The only drawback of this is that it makes it a bit harder to determine what is a function label and what is an internal label. Judicious use of whitespace is the most effective way to combat this. I also use a naming convention that allows me to recognize the difference at a glance.)

Also, use variable numbers of spaces between the opcode and the operands to ensure that all operands line up in vertical columns.
Style (Documentation): Maybe you have extensive external documentation that accompanies these functions, but probably not. Even if you do, documentation right in the code is extremely useful, easier to maintain, and should not be forsaken without a very good reason.

When writing functions in assembly, I use kind of a standard header containing a description, the inputs, the outputs, and the clobbers. If there are any assumptions made by the function, I will also call those out explicitly. So, in this case, following what you had documented in the question (even though I just called it into question), I'd write something like this:

; Determines the length of a C-style NUL-terminated string.
;
; Inputs:   EAX = address of beginning of string buffer
; Outputs:  EBX = length of the string, including the NUL terminator
; Clobbers: <none>

You should feel free to develop your own style. The important thing is having this information at the ready. Especially when programming in assembly where you can (and should) invent your own per-function custom calling conventions.
Optimization (Register Clearing): There is only one circumstance in which you should use mov reg, 0, and that's when you're trying to avoid clobbering the flags (e.g., in a sequence that contains a CMOVxx or a SETxx). In all other cases, you should clear a register by XORing it with itself: xor reg, reg. Peter Cordes has written a comprehensive explanation of the reasons why here, but it's enough to just remember the rule. Basically, it's shorter (and thus faster) and it breaks dependencies (which is sometimes important, and never hurts).
Optimization (Reduce Branching): When you want performance, avoid branching. That means that you should minimize branching as much as possible inside tight inner loops. strlen is the canonical example of a tight loop. You've got two branches inside of the loop, a conditional je and an unconditional jmp. Consider rearranging the code so that you only have one. This is almost always possible. Ideally, you want the common case to fall through and the unusual case to branch, but even if that's not possible, it's still better to have a single branch than several of 'em.
Optimization (Elide Repeated Instructions): You've repeated the inc ebx instruction. Consider how the code can be rearranged to avoid the need to do this. This isn't just the standard DRY advice, but a potential optimization opportunity. However, sometimes this trades off with the previous advice about reducing branching. Repeating a simple instruction in order to avoid a branch is virtually always worth it. As is arranging code so that you, say, speculatively increment inside of the loop, only to undo it by decrementing outside of the loop.
Optimization (Memory Access): In C terms, your code is maintaining an "index" into the string. That means you have to do a complex load-and-compare (cmp byte [eax+ebx], 0). You could instead maintain a "pointer" into the string, which would allow you to just do cmp byte [eax], 0. This is not only 1 byte shorter, but may execute more quickly.

Consider:

; Determines the length of a C-style NUL-terminated string.
;
; Inputs:   EBX = address of beginning of string buffer
; Outputs:  EAX = length of the string, including the NUL terminator
; Clobbers: CL, flags
strlen:
    lea    eax, [ebx + 1]

strlen_loop:
    mov    cl, byte [eax]
    inc    eax
    test   cl, cl
    jnz    strlen_loop

    sub    eax, ebx
    ret

This is about the most efficient way of implementing a standard strlen function:

The lea is used as a super-mov, allowing the value in ebx to be copied into eax, while simultaneously incrementing it by 1. (Although mov+inc would have been the same length in terms of bytes, lea might be slightly more efficient on certain processors.) ebx will remain a pointer to the beginning of the string, while eax will be a pointer to the current location in the string.
Inside of the loop, the CISC-style cmp instruction that took a memory operand has been split up into separate RISC-style mov+test instructions for improved scheduling. In particular, this means we can do an inc of the pointer after loading the value that it pointed to. We couldn't do the inc after the cmp, because the inc would clobber the flags (in particular, the zero flag) that we were going to try and read. In this arrangement, the test can also macro-fuse with the jnz instruction.
I've written jnz instead of jne even though they result in identical opcodes because I think it's a better mnemonic in this case. We are testing the value, and then jumping if it is not zero (i.e., if the current character is not the NUL character).
Outside of the loop, we do a final subtraction of the current pointer from the starting pointer, which gives us the length of the string, not including the terminating null.

The biggest drawback is that we've introduced the use of an additional register (the 8-bit cl), which expands our "Clobbers" list in the documentation. See why documenting this is important? The only reason why this would be a drawback, of course, is if the caller/consumer of this function needed to preserve the value in cl, as that would require an extra instruction or two. However, those instructions would be outside of the loop, and thus off the critical path, so it's almost certainly worth it for the optimizations gained.

Interestingly, this is basically the same code that Microsoft's C compiler will emit for a strlen operation when you have intrinsics enabled (otherwise, it'll generate a call to the strlen standard library function, which has essentially this same code inside of it).

This is better than Sep Roland's optimized implementation because it avoids the AGI stall introduced by this sequence of instructions in Sep's code:

inc     ebx
cmp     byte [eax+ebx-1], 0

Sep is being similarly clever here, doing the inc first and then undoing it inside of the cmp to avoid clobbering flags, but modifying ebx immediately before you use it in the addressing operands list for cmp results in a potential stall. Reordering the instructions avoids the stall; even though we had to add one extra instruction, the performance improvement more than makes up for it (unless you're optimizing for size, which you aren't, unless you're code-golfing—it's only a 1-byte difference).

So, this looks pretty good, right? Indeed, it is. As I said, it's about the best you're going to do for a straightforward, literal translation of strlen into assembly. But if you stretch your mind a bit, you can do better.

The slowest part of this code is the mov  cl, byte [eax] instruction that accesses memory at the beginning of every iteration of the loop. There's nothing we can do about the fact that we have to access memory, but notice that we're only reading 1 byte at a time here. Under the hood, the processor only does DWORD-sized reads, so it's actually reading 4 bytes and then throwing away all but the lowest-order byte. Why don't we just read 4 bytes at a time? Then, we can parallelize the code to actually deal with 4 bytes at a time, effectively unrolling the loop by a factor of 4.

The trick to parallelizing the code is figuring out an efficient way of checking all 4 of the bytes that we load in each iteration of the loop for NUL characters.

One possible attempt is the following (MASM syntax, sorry):

; Determines the length of a C-style NUL-terminated string.
;
; Inputs:   EBX = address of beginning of string buffer
; Outputs:  EAX = length of the string, including the NUL terminator
; Clobbers: ECX, flags
strlen:
  mov   ecx, ebx

ALIGN 16
CountChars:
  mov   eax, DWORD PTR [ecx]

  test  al,  al
  jz    SHORT ReturnLength
  inc   ecx

  test  ah,  ah
  jz    SHORT ReturnLength
  inc   ecx

  test  eax, 0x00FF0000
  jz    SHORT ReturnLength
  inc   ecx

  test  eax, 0xFF000000
  jnz   SHORT CountChars

ReturnLength:
  sub   ecx, ebx
  mov   eax, ecx
  ret

I've introduced an alignment of the branch target (CountChars) because aligned branch targets are more efficient, and it makes a measurable difference here because we're branching to that location a lot (each time we loop). When optimizing for code speed over size, this is a no-brainer.

There are obvious variations on this theme, especially with regard to register assignment. You might ask, why not use eax for the pointer to the current location in the string buffer, as that would eliminate the need for the penultimate mov instruction. There is a good reason I didn't, though: using eax to hold the character being tested inside of the loop makes the latter two test instructions (the ones that use immediate operands) 1 byte shorter than if any other register had been used. (Certain x86 instructions have optimized encodings when eax is the destination register for legacy reasons.) This doesn't normally matter too much, but it can help to ensure that a loop fits entirely within the cache. A 2-byte mov outside of the loop is a small price to pay for a 2-byte size reduction of the code inside the loop.

Details aside, this does get the job done with respect to testing 4 bytes at a time. But is it efficient? It feels like it might not be, because there's so much branching. Indeed, our "avoid branches in inner loops" intuition is right on, as this version is not significantly faster than the original. On modern architectures like Haswell, it's slightly faster; on older architectures, like Pentium 4 (where branch mispredictions are extremely expensive due to extremely long pipelines), it is slightly slower. In either case, the time delta is not even enough to matter. So this appears to be a dead-end. We bought ourselves a little bit of performance by reading a DWORD at a time, instead of a single byte, but any advantage gained is lost to all of the conditional branches that need to be executed each iteration of the loop.

In order to gain a real performance improvement, we need to take a different tack. And it needs to be one that reduces the number of branches. If we can find a branchless way to test all 4 bytes of the DWORD at once to see if any of them are 0 (a NUL byte), then we can reduce the number of branches in all but one iteration of the loop by a factor of 4. As it turns out, there is a solution for this, as described on the Bit Twiddling Hacks page.

Consider the following implementation (again in MASM syntax). It retrieves a DWORD and performs a series of bit manipulations on that value to determine if any of its byte are zero (i.e., contain NUL characters). If not, it branches back to the top and starts over with another DWORD-sized chunk of the string. If so, then it falls through and tests each of the four individual bytes (or, more accurately, three of the individual bytes, since if the low-order three bytes are non-zero, then we know the highest-order byte must be zero).

; Determines the length of a C-style NUL-terminated string.
;
; Inputs:   EBX = address of beginning of string buffer
; Outputs:  EAX = length of the string, including the NUL terminator
; Clobbers: ECX, flags
strlen:
  mov  ecx, ebx               ; save pointer to beginning of string for later

ALIGN 16
CountChars:
  mov  eax, DWORD PTR [ebx]   ; load DWORD value from current offset
  add  ebx, 4                 ; increment offset by number of bytes processed
  and  eax, 0x7F7F7F7F        ; mask out highest bit of each byte
  sub  eax, 0x01010101
  test eax, 0x80808080        ; TEST to ensure macro-op fusion with JZ
  jz   SHORT CountChars       ; if none of these 4 bytes were 0, start again with 4 more

  mov  eax, DWORD PTR [ebx-4] ; load previous 4 bytes (the ones we were just testing),
                              ;   using an immediate offset to compensate for eager
                              ;   increment in the loop while avoiding an AGI stall

  test al, al                 ; test low byte for NUL
  jz   SHORT ReturnLength
  inc  ebx                    ; wasn't the first byte, so increment byte count

  test ah, ah                 ; test the second byte for NUL
  jz   SHORT ReturnLength
  inc  ebx                    ; wasn't the second byte, so increment byte count

  test eax, 0x00FF0000        ; test the third byte for NUL
  jz   SHORT ReturnLength
  inc  ebx                    ; wasn't the third byte, so has to be the fourth (high) byte

ReturnLength:
  lea  eax, [ebx - 4]         ; undo the eager 4-byte increment; put result in EAX
  sub  eax, ecx               ; subtract starting pointer from current pointer
  ret

As it turns out, this is precisely the parallelization strategy taken by GLIBC (the C standard library implementation used by the GNU project, including the GCC compiler). The relevant code, including extensive descriptive comments, is available here; see also http://stackoverflow.com/q/20021066 and http://stackoverflow.com/q/11787810. This parallelized implementation is significantly faster on all x86 architectures than our previous "best" code—you're looking at around a 2× speedup.

I was pretty proud of this, until I thought some more and realized that there's no need to retest each of the 4 bytes. They were already tested in the initial bit-twiddling, and our answer about which of those 4 bytes contains the 0 is already available in the result of that bit-twiddling—we just need to extract it! This is great, because it eliminates three more branches, the three least likely to be correctly predicted (which of the 4 bytes actually contains the NUL is essentially random), and also the three most likely to enact a performance cost (since they are all back-to-back). It also saves us from having to reload the same 4 bytes again from memory.

; Determines the length of a C-style NUL-terminated string.
;
; Inputs:   EBX = address of beginning of string buffer
; Outputs:  EAX = length of the string, including the NUL terminator
; Clobbers: ECX, flags
strlen:
  mov  ebx, DWORD PTR [psz]
  xor  ecx, ecx

ALIGN 16
CountChars:
  mov  eax, DWORD PTR [ebx+ecx]
  add  ecx, 4
  and  eax, 0x7F7F7F7F
  sub  eax, 0x01010101
  and  eax, 0x80808080 ; must be AND here b/c we need result (but may not fuse)
  jz   SHORT CountChars

  ; At this point, EAX will contain one of the following values:
  ;  - 0x80808080 (if the low byte---byte 0---contained the 0)
  ;  - 0x80808000 (if byte 1 contained the 0)
  ;  - 0x80800000 (if byte 2 contained the 0)
  ;  - 0x80000000 (if the high byte, byte 3, contained the 0)
  bsf  eax, eax        ; find the first set bit, which gives either 7, 15, 23, or 31
  sub  ecx, 4          ; undo the eager increment by 4 from the loop
  shr  eax, 3          ; shift right by 3 (7 => 0, 15 => 1, 23 => 2, 31 => 3),
                       ;   thus giving the index of the NUL byte
  add  eax, ecx        ; add that byte index to the length, thus giving total length
  ret

This doesn't actually save a whole lot of time compared to the branching version, since the compare-and-branch sequence only gets executed once for each string. But, it does generally provide a minor performance boost, and it is never slower. This is true for all string lengths; there's no hidden overhead. Most of the cost comes from the relatively-expensive BSF operation. And, note that BSF is slower on AMD processors than Intel, so this code may be slightly less optimal on AMD, especially since AMD tends to use shorter pipelines and thus have less expensive branch mispredictions.

Now, I won't say that this is the fastest possible implementation, because there ain't no such thing as the fastest code, but it's pretty respectable. I'd even say it's about as good as you're going to get with bog-standard x86 instructions.

There is another frontier, and that is to use SIMD instructions (whether MMX, SSE 2, or SSE 4.2). This makes possible further substantial speed improvements, but my answer is much too long already, so I'll have to leave this stone unturned, since it is even more complicated to explain.

[NOTE: There's a fair amount of hand-waving in this answer with regards to which optimizations are sensible and what the performance differences are. I've actually done extensive benchmarking of this exact code before, on a variety of different x86 family architectures (mostly Intel), but I've left those details out of this answer for brevity (hah!). You'll just have to take my word for it. Or ask a question about it on Stack Overflow.]

strcmp

Aren't you tired of reading yet?


Using Linq to select the first and last values

What you could do is to remove the ToList() from your query. This would change your code from making a single query that returns many values to two queries, each returning a single value.


Server which writes to mongo and makes http request

Some comments:

Code is not formatted properly. There is a bunch of unnecessary whitespace, and there is some inconsistent use of var/let.
Most of the comments just add noise, and can be removed.
You're not taking advantage of promises or async/await (both for your expressjs route, the mongodb client, and for the outgoing http requests).
There is no general error handling middleware, or any other error handling in the express route.
The server accepts requests before the database is connected.
A side-effect of this is that the db global needs to be null-checked in every function that uses it.
It's hard to test
The naming is a bit lacking. From DB_NAME and other clues I gather this is about some sort of config, but other than that it's hard to tell

I did some quick refactoring (not tested):

const MongoClient = require('mongodb').MongoClient
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const rp = require('request-promise')
const URL = 'mongodb://localhost:27017'
const DB_NAME = 'config-insert'

let db = null
async function connectDb(){
    let client = await MongoClient.connect(URL)
    db = client.db(DB_NAME)
}

async function insertOne(db, data){
    data = JSON.parse(JSON.stringify(data)) // use this otherwise mongo was modifying data variable

    return db.collection('config-history').insertOne(data, {
        w: 'majority',
        wtimeout: 10000,
        serializeFunctions: true
    })
}

async function putCategory(data){
    let response = await rp({
        uri: `http://10.1.1.41/category/${data.id}`,
        method: 'PUT',
        port: 9202,
        body: data,
        json: true
    })

    if(response._shards.successful !== 1){
        throw new Error(`Could not put ${data.id}`)
    }
}

const promiseRoute = route => async (req, res, next) => {
    try{
        await route(req, res)
    }catch(err){
        next(err)
    }
}

app.use(bodyParser.json())

app.post('/', promiseRoute(async (req, res) => {
    let data = req.body

    await insertOne(db, data)
    await putCategory(data)

    res.status(200).json({status: 'ok'})
}))

app.use((err, req, res, next) => {
    console.error(err)
    res.status(500).json({status: 'not nok'})
})

connectDb()
    .then(() => {
        app.listen(4000, () => console.log('Example app listening on port 4000!'))
    })
    .catch(err => {
        console.log(err)
    })

What I have done is:

Format the code
Remove almost all the comments
Used async await instead of callbacks. Notice I have wrapped the expressjs route in a helper middleware that just passes any uncaught errors on to the general error handler. For mongodb, the driver already supports promises, and for outgoing http requests we have the request-promise library.
Added error handling middleware that ensures you get a proper response even if a request fails
Not starting the http server before the db is connected. Notice how the db null check is gone.
Injecting db into insertOne to allow for easier testing in the future.
Turned the _shards.successful response into a more general error case since it was not handled anyway.
Moved the json-parse trick closer to where it is needed (you could probably use an Object.assign here as well if you wanted)


I'd rewrite toToken a slight bit:

toToken :: String -> Token
toToken [t]
   | isAsciiUpper t = Variable t
   | t == '$' = Dollar
   | t == '@' = At
   | t == '&' = Ampersand
toToken str = Value $ read str

Notice how I'm handling the single character string cases first and that this is much less indented. I've also omitted the explicit error message you have and eliminated the explicit type-signature.

This saves on vertical indentation and just reads a bit cleaner to me.

let's have a look at executeLine

executeLine :: Program -> (Token, Token, Token) -> Program
executeLine p (a,(Variable b), c)
    | pushToStack = jump (currentLine p + 1) $ push diff $ updateVariable p b diff
    | (diff <= 0) = jump address $ updateVariable p b diff
    | otherwise = jump (currentLine p + 1) $ updateVariable p b diff
    where
        diff = value - differential
        differential = tokenToInt p a
        value = getVariable p b
        pushToStack = address == -1
        address = tokenToInt p c
executeLine _ _ = error "Could not execute line."

This again removes indentation reads a bit cleaner to me.

Let's also add some intermediate variables to main, just to clarify what happens:

main = do
    code <- readFile "countdown.txt"
    let program = (generateProgram . map removeHash . stripLines . lines) code
    let result = (reverse . map chr . stack . until executionFinished executeProgram) program
    putStrLn result

While we're at adding variables, let's also look at names. The functions are generally named really well, that's a little less the case for their arguments. Especially for executeLine we can improve the names from a, b, and c. Let's instead use the terminology from the language itself:

executeLine program (differential, (Variable storage), adress)

Names can really help with understanding a program and choosing good names is really hard. On that note pc feels somewhat misleading. I think something like executedInstructions could be more helpful :)


Fastest computation of N likelihoods on normal distributions

You should use a line profiler tool to examine what the slowest parts of the code are.  It sounds like you did that for your own code, but you could keep going and profile the source code that NumPy and SciPy use when calculating your quantity of interest.  The [Line profiler](https://pypi.python.org/pypi/line_profiler/) module is my favorite.

import numpy as np
from scipy.stats import multivariate_normal
from scipy.stats import norm
%lprun -f norm.logpdf norm.logpdf(x=np.random.random(1000000), \
                                  loc=np.random.random(1000000), \
                                  scale = np.random.random())

Timer unit: 1e-06 s

Total time: 0.14831 s
File: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/stats/_distn_infrastructure.py
Function: logpdf at line 1578

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
  1578                                               def logpdf(self, x, *args, **kwds):
  1579                                                   """
  1580                                                   Log of the probability density function at x of the given RV.
  1581
  1582                                                   This uses a more numerically accurate calculation if available.
  1583
  1584                                                   Parameters
  1585                                                   ----------
  1586                                                   x : array_like
  1587                                                       quantiles
  1588                                                   arg1, arg2, arg3,... : array_like
  1589                                                       The shape parameter(s) for the distribution (see docstring of the
  1590                                                       instance object for more information)
  1591                                                   loc : array_like, optional
  1592                                                       location parameter (default=0)
  1593                                                   scale : array_like, optional
  1594                                                       scale parameter (default=1)
  1595
  1596                                                   Returns
  1597                                                   -------
  1598                                                   logpdf : array_like
  1599                                                       Log of the probability density function evaluated at x
  1600
  1601                                                   """
  1602         1           14     14.0      0.0          args, loc, scale = self._parse_args(*args, **kwds)
  1603         1           23     23.0      0.0          x, loc, scale = map(asarray, (x, loc, scale))
  1604         1            2      2.0      0.0          args = tuple(map(asarray, args))
  1605         1        13706  13706.0      9.2          x = asarray((x-loc)*1.0/scale)
  1606         1           33     33.0      0.0          cond0 = self._argcheck(*args) & (scale > 0)
  1607         1         5331   5331.0      3.6          cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
  1608         1         5625   5625.0      3.8          cond = cond0 & cond1
  1609         1           84     84.0      0.1          output = empty(shape(cond), 'd')
  1610         1         6029   6029.0      4.1          output.fill(NINF)
  1611         1        11459  11459.0      7.7          putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
  1612         1         1093   1093.0      0.7          if any(cond):
  1613         1        58499  58499.0     39.4              goodargs = argsreduce(cond, *((x,)+args+(scale,)))
  1614         1            6      6.0      0.0              scale, goodargs = goodargs[-1], goodargs[:-1]
  1615         1        46401  46401.0     31.3              place(output, cond, self._logpdf(*goodargs) - log(scale))
  1616         1            4      4.0      0.0          if output.ndim == 0:
  1617                                                       return output[()]
  1618         1            1      1.0      0.0          return output

It looks like a not-insignificant amount of time is being spent checking and removing invalid arguments from the function input.  If you can be sure you will never need to use that feature, just write your own function to calculate the logpdf.

Plus, if you are going to be multiplying probabilities (i.e. adding log probabilities), you could use algebra to simplify and factor out common terms from the summand for the normal distribution's pdf.  That will lower the number of function calls to np.log etc.  I did this in a hurry, so I probably made a math mistake, but:

def my_logpdf_sum(x, loc, scale):
    root2 = np.sqrt(2)
    root2pi = np.sqrt(2*np.pi)
    prefactor = - x.size * np.log(scale * root2pi)
    summand = -np.square((x - loc)/(root2 * scale))
    return  prefactor + summand.sum()

# toy data
y = np.random.uniform(low=-1, high=1, size=1000) # data points
loc = np.zeros(y.shape)

# timing
%timeit multivariate_normal.logpdf(y, mean=loc, cov=1)
%timeit np.sum(norm.logpdf(y, loc=loc, scale=1))
%timeit my_logpdf_sum(y, loc, 1)
1 loops, best of 3: 156 ms per loop
10000 loops, best of 3: 125 µs per loop
The slowest run took 4.55 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 16.3 µs per loop


Euler Project 12# - highly divisible triangular number

Before we get to the slowness aspect of this code, there are a few other things we should straighten out first:

Variable names

In order to better understand your code, it is helpful to have better variable names.

Whenever you see yourself adding a comment after each variable name to describe it, you are doing something wrong:

int f = 0; //divisors
int m = 500; //max divisors
int j = 1; //current number
int z = 0; //sum (last run achieved: 135878572)
int a = 1; //current denominator
String t = ""; //total divisors

Not to mention that this is just confusing:

System.out.println("t: " + z);
...
System.out.println("f: " + t);
...
System.out.println("d: " + f);
...
System.out.print("Answer: " + z);

I would have expected something like:

System.out.println("t: " + t);
...
System.out.println("f: " + f);
...
System.out.println("d: " + d);

But your output is not very informative at all about what it actually means.

Now, how about we do this?

int divisors = 0;
int maxDivisors = 500;
int currentNumber = 1;
int sum = 0;
int currentDenominator = 1;
String totalDivisors = "";

Now there's no longer a need for the comments describing each variable, and now it will be easier to understand your code.

String concatenation and System.out

A major bottleneck in your code is all the System.out.println messages. You can take the fastest code in the world, and add a bunch of calls to System.out.println to it and it will become a lot slower.

Additionally, actually storing and outputting all the divisors is a major bottleneck. You are storing the divisors by using String concatenation. String concatenation by using the += operator is slow, as a new String object is created every time. It is slightly faster to use the StringBuilder class to perform string concatenation. However, in this case I would recommend getting rid of this output entirely. Once you have checked that the calculation of the number of divisors is correct, you don't need to know what the exact divisors are anymore.

Algorithm

Now to the fun part. Your way of calculating the number of divisors is the good old brute-force-ish way. Loop from 1 to x and see if it is divisible. Makes sense.

But there is a much much much faster way.

Let's take a look at some numbers, shall we?

Number    Divisors
6         4
28        6
36        9
66        8
120       16

Let's take a look at the prime factorization for those numbers

Number    Divisors  Prime Factorization
6         4         2*3
28        6         2*2*7
36        9         2*2*3*3
66        8         2*3*11
120       16        2*2*2*3*5

In how many different ways can we pick the prime factorizations for each of these numbers?

Let's take a look at 36. There are 2x 2's in the prime factorization and 2x 3's. So we can pick 0-2 2's (three combinations) and 0-2 3's (three combinations). 3 combinations * 3 combinations = 9 !!

Coincidence? Let's take a look at 120. There are three 2's, one 3, and one 5. So there's four combinations to pick 2's, two combinations to pick 3's and two combinations to pick 5's. 4*2*2 = 16.

Coincidence? Absolutely not.

Note that we don't actually need to do the actual prime factorization, we just need to know in how many different ways we can pick the prime factors.

Assume that the prime factorization is x*x*x*y*y*z, then there will be 4*3*2 = 24 divisors for that number. No matter what the values of x, y and z are.

This is just a push in the right direction, now I will leave the fun part of implementing the code up to you (or, if you really really just want the codes, which I don't recommend, you can take a look at one of my previous questions in which I have implemented this fast approach)


You should check if formattedDate is actually a Date object before using it (and change the variable name, since it sounds like it contains a formatted string).
It's strange, if not wrong, to consider months to be exactly 30 days.
You unnecessarily calculate Math.round(difference_ms/ONE_DAY) twice.
yearAge is a bad name for the variable at the beginning, since it doesn't contain anything concerning the year. And you reuse the variable later (then the name fits).
var today = new Date(yearNow,monthNow,dayNow); is wrong (and unnecessary), considering you just got monthNow from the current date and added 1.  Fortunately you don't actually use it.
Testing for the full year to be below 100 is unnecessary. Only getYear returns such values.
It probably would be better just to compare the day, month and year of the birthday and the current day, and do those calculation of the age in days and months only if needed.


Last things first

Before I forget about it (because it's peripheral in your code), I'll point out the new StateManager(new MenuState());, which is among the don't of C++. Raw pointers are dangerous! if you don't delete the allocated memory afterwards, you'll leave a leak (and you didn't). So use smart pointers (std::unique_ptr or std::shared_ptr) instead. That's quite an interesting topic, but you'll have to study it for yourself. Or better still, allocate your objects on the stack (State_manager manager;)

The design

  manager->update_state(manager);

is a bit weird, don't you think? What would it mean to write manager->update_state(other_manager)? Probably not much. So you could rewrite the update_state method like this:

void update_state() {
    m_current_state->on_update(this); // instead of current->on_update(removed_argument)
}

It's cleaner and completely equivalent. But then you have to write such things as:

while (exit != 1) {
    manager->update_state();
}

It isn't obvious. Where are the external input taken from? Following the thread, I see that the the state itself is responsible for managing the transition: it will ask user input and control if changing from the current state (i.e itself) to the next state (that it will have to determine too) is feasible. Without saying if it is a good design or not, I wonder whether it is useful in anyway to have a state manager at all. Its only role seems to call on_enter and on_exit, but baking that into the State class isn't difficult since on_enter and on_exit are part of its interface (or you could even dispense with it; just add instructions at the beginning and the end of the update function). It also keeps track of the current state, but a simple current_state variable would do the trick:

std::unique_ptr<State> current_state = std::make_unique<Intro_state>();
while (exit != 1) current_state->update();

But then you might also wonder why this exit is outside of the state machine. If there is an intro-state, a game-state

  At that point I want to take a break and tell you that naming your file with a synonym or a paraphrases for the class it contains is a really bad idea. The Game_state class should be in Game_state.h, not in gaming_state.h, that doesn't make any sense.

then why isn't there an exit-state? It could do some clean-up, display credits, I don't know. So now we have:

std::unique_ptr<State> current_state = std::make_unique<Intro_state>();
current_state->update();

But then the current_state variable itself, and the allocation that goes along with it, are also superfluous. Intro_state().update(); would look weird, but what about intro();? So we have a function void intro() that asks if it needs to call void game() or void exit(), and a void game() that asks if it needs to call void intro() again or void exit(). The design pattern has disappeared, and yet we haven't removed any functionality or usability feature, only simplified. From that observation I feel I can conclude safely that there is a problem in your design.

My 3 cents

Many C++ manuals insist on the object-oriented part of the language and the so-called design patterns. It isn't, IMHO (which, that said, isn't really my own but one taken by most of the prominent figures of the C++ scene), a good way to learn C++. Try rather to explore the robustness of the language or its versatility.


After discussion in comments your code became much better.

Also if directoryPath and fileName will not be changed after initialization in constructor you can define these fields as readonly:

private readonly string directoryPath = string.Empty;
private readonly string fileName = string.Empty;

This code

using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write))
{
    using (var logFileWriter = new StreamWriter(logFile))
    {
        logFileWriter.Write(message);
    }
}

can be replaced with

File.AppendAllText(Path.Combine(directoryPath, fileName), message);

Also ArgumentException's constructor takes message as first argument and paramName as second, so you need to call it like this:

throw new ArgumentException("Write some error message...", nameof(logDirectoryPath));


Changing these two functions into one function

You need to think about the underlying model. Have a think about isA/hasA. Depending on what you conclude...

Are the types defining similar interfaces? You may find that the date info is like a label that both object types have attached to them. (It looks that way.) Define an interface that contains the common names. Have each of the two types implement it. Now you can use just one loop.
Is one of them actually a member of the other? Then define it that way. Your loop will get smaller.

Bottom line is that highly repetitive code should make you think about whether your model is correct.


Average of three biggest parameters out of five without using sorting algorithm or vector/array

I would think, that you should try to divide and conquer rather than writing one long function. That means you should split your code into separable and reusable functions that do one thing. For example the individual minima you get by the following functions

float min2(const float& a, const float& b) {
    return a < b ? a : b;
}

float min3(const float& a, const float& b, const float& c) {
    const float temp = min2(a, b);
    return temp < c ? temp : c;
}

float min4(const float& a, const float& b, const float& c, const float& d) {
    const float temp = min3(a, b, c);
    return temp < d ? temp : d;
}

float min5(const float& a, const float& b, const float& c, const float& d, const float& e) {
    const float temp = min4(a, b, c, d);
    return temp < e ? temp : e;
}

You might even put this into variadic templates and overload min.
Now you can get the minimum value and define a switch statement

float average3of3(const float& a, const float& b, const float& c) {
    return (a + b + c)/3;
}

float average3of4(const float& a, const float& b, const float& c, const float& d) {
    const float min = min4(a, b, c, d);
    switch(min) {
        case a:
            return average(b, c, d);
        case b:
            return average(a, c, d);
        case c:
            return average(a, b, d);
        case d:
            return average(a, b, c);
    }
}

float average3of5(const float& a, const float& b, const float& c, const float& d, , const float& e) {
    const float min = min5(a, b, c, d, e);
    switch(min) {
        case a:
            return average3of4(b, c, d, e);
        case b:
            return average3of4(a, c, d, e);
        case c:
            return average3of4(a, b, d, e);
        case d:
            return average3of4(a, b, c, e);
        case e:
            return average3of4(a, b, c, d);
    }
}


First thing I'd suggest is make the 2 lists the same type(string).  Now the file list can be an exclusion list that contains only the filenames that aren't in the database.  Something like this should work:

    var clientDocList = documentRepository
        .Documents
        .Where(c => c.ClientID == clientID)
        .Select(d => d.DocFileName
        .Trim()
        .ToUpper()).ToList();

    var fileExclusionList = Directory
        .GetFiles(directoryPath)
        .Select(x => Path.GetFileName(x)
        .Trim()
        .ToUpper())
        .Except(clientDocList).ToArray();


Program that teaches kids Chinese characters

First of all, this is a great idea!

Naming

all and set are not good names, because they shadow Python built-in names. set is especially bad, because it actually contains a list, which is misleading.
Also, variable names in Python should use snake_case instead of CamelCase. For example "NotLearned" should be changed to not_learned.

The PEP8 command line tool can tell you these things, I suggest to give it a try!

Also, k is a very poor name for a random list of characters.

Compatibility

It's ok if you have a reason to stay on Python 2.x, but it's still a good idea to make your scripts Python 3.x compatible when it's easy to do.
For example, you could replace print something with print(something),
because the latter works in both versions, the former doesn't.

Bugs

The program has several bugs.

outof is not reset at the beginning of each cycle.
For example from the word set of People with 4 elements,
I "guessed" 3 correctly, got 75% score,
then in the next round I guessed 2 correctly so my score became 125% instead of 50%.
The fix is simple, move outof = 0 inside the loop.

Another bug is in the logic to level up.
In my previous example of getting 75% score,
this happened:

if set in NotLearned:
    # => true => moving set from NotLearned to Learned
if set in Learned:
    # => true, because the set was just moved to Learned
    if score >= .5:
        # => true, I scored 75%
        # => moving set from Learned to Practiced
if set in Practiced:
    # => true, because the set was just moved to Practiced
    if score >= .6:
        # => true, I scored 75%
        # => moving set from Practiced to LevelOne
if set in LevelOne:
    # => true, because the set was just moved to LevelOne
    if score >= .75:
        # => true, I scored 75%
        # => moving set from Practiced to LevelOne

There's a problem with logic here.
Possibly you meant to use elif instead of some (or all?) of those ifs.

Reducing the number of lists

  I want to know if there is a better way to have fewer lists

The way you use the lists, is a bit strange...
From NotLearned, you randomly pick one of the lists (numbers, people or family), and that list will be used for the rest of the game:
words are sampled from this list,
and the list itself is moved through other lists: NotLearned -> Learned -> Practiced -> LevelOne -> ... and so on.

Instead of moving through NotLearned -> Learned -> ..., you could use a simple number to indicate the level, and increment as the user progresses.

Usability

Typing Chinese is problematic if you don't have a Chinese keyboard. I played the game by copy-pasting answers. It could be more interesting and more accessible to present multiple choices that can be selected by entering their numbers.

In each cycle of the main while loop, the words come in the same order. It would be more interesting if the order was randomized.
See the random.shuffle function.

Unused variables

Eliminate all unused variables, they are just noise.


Use of concurrency to generate combinations

Go routines are cheap to make and run. So your solution would work perfectly fine.

To your question whether it's actually a useful application of concurrency I would say no.
You're creating channels and go routines to then instantly wait for it's next result anyway.

Right below your linked python answer to that other question there's a nice java answer with a slightly different approach. I suggest combining the 2 approaches.

I'm not used to writing go code so the following will probably need a couple of fixes but should give you an idea how to do it correctly yourself:

func CombIter(input []byte, acc []byte, length int, outC chan []byte) {
    for i := 0; i < len(elements)-length+1; i++ {
        if length == 1 {
            outC <- append([]byte{acc, input[i]})
        } else {
            for j:= i+1; j < len(elements); j++ {
                combIter(input[j:], append([]byte{acc, input[j]}), length-1, inC)
            }
        }
    }
}

You might also have to check the stopping condition for the outer while loop. You want this one to stop when there aren't enough elements left to get a result of the correct length. I didn't run this code so it could be off by 1.

If you need that outC <- []byte{} line to have a stopping condition it may make most sense to provide a helper method:

func CombIter(input []byte, length int, outC chan []byte) {
    combIter(input, []byte{}, length, outC);
    outC <- []byte{};
}


Simple grid system made out of CSS columns

There are a few good reasons why no one uses the multi-column module for "grids".

They are rigid

There are only 2 options for the column-span property: none or all.  Want to have elements spanning 2 columns?  Too bad.  Also, last time I checked, Mozilla does not support the column-span property.

They are unpredictable

Each browser has its own algorithm for determining how to generate the columns.  If you read the specification, column-count is not a guarantee that you will get the specified number of columns:

  describes the optimal number of columns into which the content of the element will be flowed. Values must be greater than 0. If both ‘column-width’ and ‘column-count’ have non-auto values, the integer value describes the maximum number of columns.

From: http://www.w3.org/TR/css3-multicol/#column-count

The emphasis is mine: in an ideal situation, you'll get the exact number of columns you've specified.  If the browser's algorithm decides that there's not enough room for that many, it will give you less.

Controlling where breaking occurs is a nuisance

Since you're using images for testing, you're not seeing the problem.  Using columns on a parent container doesn't just control how the children flow, but all descendant elements.  What this means is that your gridElement will frequently span multiple columns in an effort to equalize the height of the columns.  You can specify where breakage occurs (or shouldn't occur) on the descendant elements like so:

.foo {
  -webkit-column-break-inside: avoid; /* Deprecated property name for Webkit (Blink too?) */
  page-break-inside: avoid; /* Non-standard property name for Mozilla */
  break-inside: avoid;
}

http://codepen.io/cimmanon/pen/CcGlE

TL;DR

This system is designed with text in mind, not grids.  I predict that if you were to pursue this further, you'll end up being dissatisfied due to the limitations of the module as it is currently specified.  If you're just planning to use this with images, my last point above does not apply.


Celsius and Fahrenheit Converter in JavaScript

Use proper spelling - it'll looks more professional and can prevent bugs stemming from the typo. Farhenhite should be Fahrenheit, and Celcius should be Celsius.
Use proper indentation - every new block should open a new indentation level. You're doing this well with the if/elses, but you should also do it for the whole click listener as well:
converterButton.addEventListener('click', function(event){
    event.preventDefault();

    const celsiusToFahrenheitValue = (celsiusToFahrenheit.value * 9/5 + 32);
    const fahrenheitToCelsiusValue = (fahrenheitToCelsius.value - 32) * 5/9;
    // etc

preventDefault? Is the button inside a <form>? If so, the preventDefault is fine. Otherwise, it won't do anything and can be removed.
Avoid document.write - it can be insecure and somewhat confusing. Here, since it's called after the page loads, it will replace the whole document with the new HTML, which is probably not what you want - you'd probably rather preserve the converter and let people continue to convert after pressing the button once. Instead, populate, say, a results element with the results.
Confusing variable names Without reading the variable definition, it isn't entirely clear what the difference between celsiusToFahrenheitValue and celsiusToFahrenheit.value is. Consider only calculating the new value when it's needed, inside the if statements, and calling it something like convertedToFah. Also consider renaming celsiusToFahrenheit to just plain celsius, since the value it will hold is the plain celcius value.

if (celsius.value) {
    const convertedToFah = (celsius.value * 9/5 + 32);
    document.querySelector('.conversion-type').textContent = 'Celsius To Fahrenheit Result:';
    document.querySelector('.result').textContent = `${convertedToFah} ℉`;
}

When one input is changed, consider clearing the other input to make it clear what will be converted when the button is pressed - use an input listener.


I assume one of the complaints was with the constant.  There are various ways to calculate pi, using an exact calculation rather than using some number of digits.

Here's one example (in C++14):

constexpr auto pi()
{
    return std::acos(-1);
}

(For C++11, use a non-auto type, such as double or float.)

The constexpr keyword will allow this to be calculated at compile time.  You could still assign the return value to a constant or call the function inline where needed.  If you don't have C++11, then you can use const in place of constexpr, and just assign it to a constant.


More efficient loops to generate unpronounceable words

Copy Pasting

If you are copy-pasting code, it is a sign that you should write it differently (your two for loops are quite obviously copy pasted).

Bug

I'm pretty sure that here:

        for (var k = 0; k < twoLetters.length; k += 1) {
            if (threeLetters[k] === test) {

you meant to change it to k < threeLetters.length;.

Solution

Instead of copy-pasting the for loop code, extract it to a function:

function generateHelper(string, array, charCount) {
    for (var j = 0; j < string.length; j += 1) {
        var test = string.slice(j,j+charCount);
        for (var k = 0; k < array.length; k += 1) {
            if (array[k] === test) {
                console.log('Has ' + charCount + ' letter syllable');
                return unpronouncable(length);
            }
        }
    }
}

Coding Style

i++

It is customary to write j++ instead of j += 1 in loops.

loop variable

It is also customary to use i as primary loop variable and j as secondary variable in case the loop is nested inside another loop. As your j-loops in generate are not nested, I would use i for them, and then j instead of k for the nested loop.

Call of return generate();

return should generally be at the end of a function, but in this case, I would pull it up in front of the generate function definition. It is easier to overlook at the bottom.

But the whole generate method seems unnecessary. Couldn't you just remove these lines:

function generate() {
}
return generate();

I don't mean the code inside the function, just the function definition and the function call.

General Approach

You already mentioned that this is probably not the best approach, so I'm not going to say too much about it. Generally, I would probably go with an iterative solution as most of the time they are easier to understand and faster as well.

An example of an iterative approach might look like this:

function unpronouncable(length) {
    // filter these out
    var twoLetters = ['aa', 'ae', 'ag', 'ai', 'ar', 'ao', 'as', 'aw', 'ay', 'ba', 'da', 'de', 'ed', 'ef', 'eh', 'ei', 'em', 'en', 'er', 'et', 'ex', 'fa', 'fe', 'fu', 'gi', 'go', 'hm', 'ho', 'so', 'id', 'ie', 'jo', 'ka', 'ki', 'ku', 'lo', 'mi', 'mm', 'mu', 'na', 'ne', 'nu', 'od', 'oe', 'oi', 'om', 'op', 'os', 'os', 'oy', 'pe', 'pi', 'qi', 're', 'se', 'ta', 'ti', 'ut', 'wo', 'xi', 'xi', 'ya', 'yu', 'za', 'zo', 'co', 'my', 'qu', 'ge', 'ro', 'ra', 'xa', 'wa'];
    var threeLetters = ['thm', 'css', 'dvd', 'buh', 'bad', 'rue', 'cun', 'pub', 'puk', 'pul'];

    // generate a new string until one is found that does not contain the filters
    var generatedString = "";
    var done = false;
    while (!done) {
        generatedString = generate(length);
        done = !contains(generatedString, twoLetters, 2) && !contains(generatedString, threeLetters, 3);
    }
    return generatedString;

    // generates a random string with given length
    function generate(length) {
        var letters = "abcdefghijklmnopqrstuvwxyz";
        var string = "";
        for (var i = 0; i < length; i++) {
            string += letters[Math.floor(Math.random() * letters.length)];
        }
        return string;
    }

    // returns true if string contains any characters in the stringArray.
    function contains(string, stringArray, charCount) {
        for (var k = 0; k < stringArray.length; k++) {
            if (string.indexOf(stringArray[k]) > -1) {
                console.log('Has ' + charCount + ' letter syllable');
                return true;
            }
        }
        return false;
    }
}
console.log(unpronouncable(8));

You could also replace the done = [...] assignment with two if statements, which might be easier to read.

Also: your approach with iterating over the string and using splice is quite complicated. Just use string.indexOf(stringArray[k]) > -1; to check if a string contains another string.

And just out of curiosity: how would you pronounce css or dvd?


Is it safe?  Maybe.  Is it the right way to do it?  No.

Even if it were safe, there’s a big problem with the SQL, and that’s that you’re inserting the dots after escaping, rather than before.  I notice that for the input ', it will be escaped to \', and then your dot-insertion turns it into \.'..  Before, the \ was escaping the ', but now it isn’t.  Now it’s escaping the ..  I don’t know if a malicious entity could do anything bad with that, but I wouldn’t take any chances.

And here are some problems with the HTML:

Copy-and-pasting will catch those dots.
Search engines will catch those dots.
You break any Unicode characters, e.g. you turn 日本語 into ?.?.?.?.?.?.?.?.?.. (But I only have an old version of PHP installed; maybe newer versions are more intelligent, but in that case, you might have other problems like putting a combining character onto your >)

And that’s not to mention the gigantic size increase, and potentially having invalid HTML… all around, it’s just not a very good way to do it.

So what’s the right way to do it?  Well, for inserting data into the database, you should be using PDO with prepared statements.  Then you don’t have to deal with SQL escaping at all: you prepare a query with placeholders, and send in the placeholder data, and since the data doesn’t have to touch the query, you don’t have to worry about that at all.

Sidebar: using PDO

You said that it’d be a lot of work to use PDO.  Well, I’ve never found it particularly difficult.  Your code perhaps looks like this:

mysql_connect('localhost', 'myapp', 'letmein');
mysql_select_db('myapp');
// ...
mysql_query("insert into users (firstname, lastname, email) values ('$firstname', '$lastname', '$email')");

But it’s not actually that hard to use PDO.  That code could be translated to use prepared statements and PDO like so:

$db = new PDO('mysql:host=localhost;dbname=myapp', 'myapp', 'letmein');
// ...
$stmt = $db->prepare('insert into users (firstname, lastname, email) values (:firstname, :lastname, :email)');
$stmt->bindValue('firstname', $_POST['firstname']);  // look ma, no escaping!
$stmt->bindValue('lastname', $_POST['lastname']);
$stmt->bindValue('email', $_POST['email']);
$stmt->execute();

And besides being more secure, you’re also moving onto something that the PHP developers have committed to keep in place: the mysql_* functions will be removed, as the PHP documentation says:

  Warning: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

End of sidebar

On the HTML side, using htmlentities or htmlspecialchars is the standard way to do it.

Then, finally, I’d like to point out one thing about how you’re accessing POST data: you’re currently using $_POST[firstname].  It’s supposed to be an expression that’s between the brackets, but you have the name of the field literally in there.  It turns out that that’s okay currently, as undefined constants evaluate to their name.  But that does generate a notice, and depending on your error reporting level, you will probably see lots of notices in your error log saying that this is bad and/or deprecated.  You should explicitly quote it: $_POST['firstname'].


Disclaimer: I'm here at behest of the OP. I'm not all that proficient at JS, just enough to do some basic things, but I am fairly well versed in PHP. That being said, the knowledge should be fairly universal and I said I'd lend my point of view on the subject. Please feel free to point out my mistakes. I'd love to know more myself.

Edit: You can't have structure without syntax, so I ignored that bit. But I did edit my answer per your request for no comments on your naming scheme. I do still think its relevant so I left it, however I hid it so you may skip over it if you wish.

Descriptive Code (Naming Scheme)

  I'll be honest, I'm not sure what exactly is going on here. Mostly because your function names are not very descriptive. More descriptive function names would be nice, or at the very least, more documentation. Especially documentation about where some of these other functions are coming from. Because JS is so loose with its scope control these could be coming from anywhere and it would be nice to know where they SHOULD be coming from and what they SHOULD be doing/returning.

Nesting Functions

There are a couple of problems with nesting functions. The first is that those "inner" functions are only available within the scope of the "outer" function and are recreated every time that outter function is called. Second is that it is generally considered bad practice. Not all nested functions, just most. But that is because most are not created properly. I've already said I'm not an expert on this, that's why I gave you the link so you can make your own opinions. I will mention that I don't think what you have here is a good example of nested functions. Mostly because I can't figure out how cIO() is supposed to work if it never calls in().

Switch Statements

You are defining your switch statements wrong. The colon ":" should come after the case argument, not before.

case 'user_try':

This is one of those rare instances where I would say you should look at case dropping. Not sure if that's the right term, but it sounds cool. What I mean by that is instead of retyping the same statements for similar cases, you can write it once, and prepend all the cases that use it above that statement, excluding any breaks so that they "drop" down to the next.

case 'user_new':
case 'user_exist':
//etc...
case 'tweet_add':
    out( cPreHold( 'model=' + type, cPost( type, text ) ) );
    break;

Magic Numbers

You have some magic numbers going on here. Not really sure how you should fix them, but I think there has to be some way. If someone could recommend an example as an edit, I will accept it.

array_pair[0].appendChild( array_pair[1] )

Miscellaneous

I'm confused as to what cPreHold() is supposed to be doing. You have it set up a response variable, check if it has a "true" value, which if it does, you do nothing with it, but then if it doesn't it returns the response variable, which is false... Why not just return false? Why use response variable at all?

if( mPre( type ) ) {}

I do not think that switch statements are necessary in cPre() and cPost() unless you are planning on extending their functionality. It would be better written as an if/else statement.

UPDATE

I can't really say much about your structure. As I mentioned, I only use JS for very basic applications. More or less, your structure looks the same as how I'd write mine, except for all those lamda functions and nested functions. I can catch some syntax errors, and provide some logic suggestions, but I'm not the best one to turn to for advanced topics such as structure.

BTW: Here's a function I find I use a lot. Seems like you could use it too.

function eID( id ) { return document.getElementById( id ); }

Hope this helps!


address

I'd enclose the ul.primaryContacts in one address element (not every item separately):

<address>

Phone: 1.800.corp

Email: office@corpora.com

Follow Us:

</address>

links without content

Your follow links don't contain any content:

Screenreader users wouldn't be able to make sense of these links.

Either add the text to it (and visually hide it, and display the icons via CSS), or use img here (together with the alt attribute, of course).

Same problem with the two slideButtons ().

em

I don't think the em element is correct in these cases:

1.800.corp
office@corpora.com

http://www.w3.org/TR/html5/text-level-semantics.html#the-em-element:

  The em element represents stress emphasis of its contents.

And, important:

  The placement of stress emphasis changes the meaning of the sentence.

In your cases the em doesn't change any meaning. You wouldn't stress the phone number or the email address while reading.

contact URIs

You could link your contact details:

1.800.corp (with the tel URI scheme)
office@corpora.com (with the mailto URI scheme)

br

You use br in the navigation (Home
go to start), but this is not a correct use:

  br elements must be used only for line breaks that are actually part of the content, as in poems or addresses.

site heading

Your page should probably have a site heading. Currently your outline would be:

Untitled Section
    Untitled Section
    Awesome business card design
    Awesome business card design
    Awesome business card design

In your case, the logo (resp. the alt value) is the site/page heading, so you'd have:

slider

It depends on content and context of your page if the slider should be part of header or not. Is the slider present on all pages? Then it's probably correct to place it in the header. But if it would be part of the main content of a page, it shouldn't be in the header.

I think you should enclose the whole slider in a section (resp. aside); if possible, find a heading for it. As soon as you use such a sectioning element for the slide, you can enclose the two slide buttons in a nav element (as they are the main navigation for that sectioning element). Also, each slide could be an article (instead of a section).

Then you'd get the following outline (together with the site heading mentionend before):

Corpora - A Business Theme
  Untitled Section (this is your site nav)
  Untitled Section (this is the slider heading)
    Untitled Section (this is your slider nav)
    Awesome business card design
    Awesome business card design
    Awesome business card design


Console-based game in Java to demonstrate Solid principles and abstractions

thanks for sharing your code

I know that this isn't a huge amount of code, but I'm going to look at it assuming that we will want to be able to add additional features and expand upon the code that's already here.

Redundant Comments

comments should say why you're doing something, not what you're doing.
This line

private String[] inventory; //Player will have an inventory.

is an example of a particularly bad offender. If I have a Player class, and it has an inventory member variable. We know that a Player will have an inventory, you don't need to write a comment saying what the code is already telling us.

Let's take a look at your Entity class. If we look in the constructor, we can see that the constructor is causing some side effects. In this case, it's printing to the console. In general, when I construct an object, I assume there will be no side effects or other unexpected behaviour. It's perfectly reasonable to provide a method to do this (in your case displayEntityName) but I would not include this in the constructor.

Consider making your classes immutable where possible

Unless you need to provide getter and setter methods for an instance variable, you should just leave them out entirely and make the variable final. I think here name is a good candidate, a getter seems reasonable, but I don't think you'd ever really need a setter. In a standard RPG or game, the player or enemy names don't change. They can be marked final.

private final String name;

see this question https://stackoverflow.com/questions/565095/are-getters-and-setters-poor-design-contradictory-advice-seen

have a look at the arguments for and against using getters and setters. I won't also recommend reading up on the benefits (and drawbacks) of writing immutable classes.

Avoid using Strings to represent more complex Objects

You're currently representing your inventory as an array of Strings. I would argue that an Item is far more than just a String. I would rather see an Item class. This could be a super class or interface that all items in your game could derive from / implement.

Some class that come to mind could be, Weapon, Armour, Accessory etc. If all of these things are represented as a single String, you're restricting what you can do. Additionally, I would not use an array for this situation. How about an Inventory class.

public class Inventory {
    private final List<Item> items = new ArrayList<>();

    public void addItem(Item item){ // can be weapon, armour etc.
        items.add(item);
    }

    public int numItems(){
        return items.size();
    }
    ...
}

Now, this Inventory class has the single responsibility of representing and maintaining this list of items.

and your Player class can just have an Inventory

private final Inventory inventory;

Or even just put it in the Entity class. This way an Enemy can have an inventory too.

Notice how I used a List instead of an array. This can be resized and already has a list.size() method to tell you how many elements are in it. No need to keep track of that stuff yourself!

This Inventory can now become a lot more useful than just an array of Strings.

Your current Player class has two responsibilities that jump out. One is providing Player behaviour, but it's also maintaining the inventory by keeping track of it's size. Now the Inventory class is in charge of this.

This method signature

public void searchChest()

At the moment this method simply prints that the Player is searching a chest, why not provide the option to search any Chest object.

public void searchChest(Chest chest)

and a Chest could look like

public class Chest {
    private final List<Item> contents;

    ...

    public List<Item> open(){
        return new ArrayList<>(contents);
    }
}

Then in the searchChest method, the Items from the Chest can be added to the Inventory.

Similarly to the Chest method, this method

public void equiptWeapon()

firstly, there's a typo here. It should be

public void equipWeapon()

Secondly, why not be able to provide a weapon

public void equipWeapon(Weapon weapon)

At the moment in your Enemy interface you have this method.

void attack(Player player);

What if you want to have Enemies fight each other, different factions etc.
There's no need to limit the potential targets, how about

void attack(Entity entity);

Some final points to consider.

When you attack another entity, you could get the currently equipped Weapon and the other entity's currently equipped Armour and do some simple math based on their Stats

instead of a displayEntityName method, you could just override toString and then print the Entity directly in the calling code.

Before you start coding anything, think about what Objects could be involved in your System/Game in real world terms, then start thinking about how these could be implemented as Objects in your code.

Instead of WeaponConstants, why not just make a Collection of Weapon objects.

Hopefully this review was useful for you.

Keep it up!


Instead of putting multiple if else blocks I thought it can be implemented as following.

Looks like the Strategy Pattern with polymorphic dispatch.
A sound plan!

Make fields final when possible

The private fields of Context can all be final.
It's good to make them final so you won't change them by accident.
final fields are easier to read, as you know they will only ever have the same value.

Avoid throwing Exception

IValidator.handleFailure is defined with throws Exception.
It's recommended to avoid using the generic Exception class,
it's better to use specific exceptions.
Code using this interface is forced to catch Exception,
which creates the risk that other exception types may be caught by mistake.

Implement just what you need

Do you need all the constructors in ValidatorException?
In the posted code, there isn't a single use case using of any of those.
I suggest to implement only the functionality you actually need,
and avoid to implement in advance something "you might need someday".

Conventions

In Java it's not a convention to prefix interface names with a capital I.
I suggest to rename IValidator to Validator.

The constant interface antipattern

You haven't shared the code of CWSConstants,
but it sounds like it might simply contain constants,
and your classes implement this interface only to have easy access to those constants.

This is considered a bad practice. Interfaces are intended for contracts of behaviors, using them for easy access of constants is an abuse of the language. The alternative is to put the constants in a class instead of an interface. You may use static imports to avoid polluting the code with the name of the class everywhere.


How can i make my Get_Numb_of_Digits_in_a_number() function more accurate?

To get the number of whole numbers, you can just use log10.

int wholeNumbers = ( number == 0 ) ? 1 : (int)log10( abs( number ) ) + 1;

I implemented your function in C#. By using the decimal type for the calculation of the numbers after the decimal sign, precision issues are automatically solved. Most likely a simple for loop is more performant than using pow as in your solution. The result of numbers after the decimal sign for infinite precise numbers (like PI) is dependent on the precision of the type. With this code, I get 14 digits after comma for PI.

public static int AmountOfDigits( double number, DecimalPart decimalPart = DecimalPart.WholeNumbers )
{
    double absNumber = Math.Abs( number );
    int amountOfDigits = 0;

    // Amount of digits before decimal sign.
    if ( decimalPart == DecimalPart.WholeNumbers || decimalPart == DecimalPart.EntireDecimal )
    {
        amountOfDigits += (absNumber == 0) ? 1 : (int)Math.Log10( absNumber ) + 1;
    }

    // Amount of digits after decimal sign.
    if ( decimalPart == DecimalPart.AfterDecimalSign || decimalPart == DecimalPart.EntireDecimal )
    {
        // Use decimal for more precision!
        decimal afterDecimalSign = (decimal)absNumber;
        while ( afterDecimalSign - Math.Truncate( afterDecimalSign ) != 0 )
        {
            amountOfDigits++;
            afterDecimalSign *= 10;
        }
    }

    return amountOfDigits;
}

You do have to ask yourself where you will use this code however. When you are going to use it to calculate correct padding for string output, it's probably better to just convert the numbers to strings and count the amount of characters. It would be an interesting benchmarking test to compare that solution to this one.


Faster way to check if number has factor of different primes than given list of primes

A note on terminology,

14 has factors [1, 2, 7, 14]

Usually these are called divisors, while the factors of 14 are taken to be only 2 and 7.
The Algorithm
While it is not entirely clear to me what you need the result to be, there is an alternative approach to finding the answer to the following question:

Does the number have any factors that are not in the list?

Which I hope is a fair re-wording of

[the number] should not have any other factor as primes other than in the list

To answer that question, a possible algorithm is:
For each p in primes, as long as n is divisible by p, divide n by p. The "leftover" n at the end is the product of all the factors of the original n that are not in primes.
For example in Python,
def solve(n):
    primes = [2, 3, 5]
    for p in primes:
      while n % p == 0:
        n = n // p
    return n

Now the result will be 1 if the number n only had the primes as factors, or otherwise it will be whatever is left. In the original function, the leftover would also be essentially be factored (but slowly, and only the first factor is returned). An integer factorization algorithm (there are faster options for that than trial division) could be applied as an extra step to recreate that result, but that is not required to answer the question of whether the number has any other factors that were not in the list primes.
This algorithm would not deal very well with a much longer list of primes (say, millions of primes), but it does deal well with cases such as 1926576016 where the lowest prime factor which isn't in primes is high.


#!/usr/bin/python

import sys
import math

def prime_factorize(n):
    factors = []
    number = math.fabs(n)

Prime factorization really only makes sense for integers. So you really use abs not fabs.

    while number > 1:
        factor = get_next_prime_factor(number)
        factors.append(factor)
        number /= factor

    if n < -1: # If we'd check for < 0, -1 would give us trouble
        factors[0] = -factors[0]

    return tuple(factors)

Tuples are for heterogeneous data. Keep this a list. It is conceptually a list of numbers, and it so it should be stored in a python list not a tuple.

def get_next_prime_factor(n):
    if n % 2 == 0:
        return 2

    # Not 'good' [also] checking non-prime numbers I guess?
    # But the alternative, creating a list of prime numbers,
    # wouldn't it be more demanding? Process of creating it.
    for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2):

Your expression, int(math.ceil(math.sqrt(n)) + 1) seems to be more complicated that it needs to be. Couldn't you get by with int(math.sqrt(n) + 1).

        if n % x == 0:
            return x

    return int(n)

Again, why are you trying to support something that isn't an int?

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: %s <integer>" % sys.argv[0])
        exit()

I'd pass an exit code to indicate failure

    try:
        number = int(sys.argv[1])
    except ValueError:
        print("'%s' is not an integer!" % sys.argv[1])
    else:
        print("%d -> %s" % (number, prime_factorize(number)))

Algorithmwise, it will be more efficient to keep a list. They key is to keep information about the primes used between calls. In particular, you want a list that indicates the smallest prime factor for example

factors[9] = 3, factors[15] = 3, factors[42] = 21

A simple modification of the Sieve of Eratosthenes should suffice to fill that in. Then easy lookups into the list should tell you exactly which prime is next.


Good job - it's nice to see improvements from the reviews you've received.
I would recommend using logical && rather than bitwise & in the computation r &node->value == parent->value.  Results should be the same, but programmers expect to see logical operators with boolean values.
The computation of r cannot use && as is, because the right-hand side does need to be evaluated for its side-effects, even when the left-hand side is false.  I'd consider rewriting as separate expressions, so a future maintainer doesn't "correct" the & to &&:
bool l_un = isUnivSubTimpl(node->left, node, count);  /* updates *count */
bool r_un = isUnivSubTimpl(node->right, node, count); /* updates *count */
bool r = l_un && r_un;

Identifiers beginning with is are reserved for Standard Library extension, so I'd advise changing the name isUnivSubTimpl, particularly as it has external linkage.
It isn't clear to me why freeTree() returns a bool, as it only ever returns true.
Building the tree could be simplified a little with
stTree *createLeafNode(int value)
{
    return createNode(value, NULL, NULL);
}


Bug

The main loop starts at i = 2. That is, s.charAt(1) - s.charAt(0) is never attended to. Suspicious, isn't it?
Naming

A name comp (and comp2) presumes that it carries some information about comparison. It obviously doesn't. diff and rdiff sound better.
Algorithm

Reversal of the string just wastes time. You may work the same string from both directions simultaneously:

for (int i = 1; i < s.length(); ++i) {
    diff = s.charAt(i) - s.charAt(i - 1);
    rdiff = s.charAt(s.length() - 1 - i) - s.charAt(s.length() - 1 - (i-1));
    ...

Returning the comparison result is an anti-pattern.

return stillEq;

achieves the same result as

if (stillEq)
    return true;
else
    return false;

in a much cleaner way.
If you insist on reversing a string, better come up with an iterative method. Java cannot eliminate tail recursion.


Here's your problem:

return sum(letters_map[char]*(names.index(name)+1) for name in names for char in name)
                              ^^^^^^^^^^^^^^^^^^^

So as we walk down names, we calculate the value of the current name... and then start over and search for it from scratch to determine the index. That extra lookup turns our algorithm from \$O(n)\$ to \$O(n^2)\$!! And string search is expensive - for the 1000th name, we have to first check 999 other strings that are definitely going to be wrong. We don't need to search for name in names to find the index. Not only that, but then we re-search the index for every char in name! (Maybe Python is smart enough to cache this, maybe not). So really this is more like \$O(n^3)\$...

We can just keep track of the index as we go. That's what enumerate() is for:

return sum(letters_map[char] * idx
           for idx, name in enumerate(names, start=1)
           for char in name)

That one change takes your runtime over 10 iterations from 13.31s to 0.07s. Behold the power of not redoing a bunch of work.

Everything else is basically fine. Creating letters_map could be abridged to just:

letters_map = {letter: idx
               for idx, letter in enumerate(string.ascii_uppercase, start=1)}

That doesn't affect performance, just makes it a little easier to see what letters_map actually is. It turns out that dictionary lookup is fater than doing the name lookup on ord() within the loop is, so this is pretty speedy.

It's also typical to do file operations with a context manager. That is:

with open(file_name) as f:
    return sorted(re.findall(r'"(.*?)"', f.read()))

That is marginally slower, but more Pythonic in my opinion.


Overall looks good. I think following improvements can be suggested.

1.Instead of this

typeof ids[statementId] === "undefined"
  ? (ids[statementId] = 1)
  : ids[statementId]++;

How about this for more readability

ids[statementId] = (ids[statementId] || 0) + 1;

2.Instead of doing sort and immediately reverse. You can change sort function (with descending order) so that you can avoid reverse call.


Number of possible numbers in roman number string

Use pattern matching to check for single-element lists

Let's start with romamCombination's second pattern:

romanCombinations str = if length str == 1 then 1

Compared to Java, length isn't a constant time operation in Haskell. It will traverse the whole list. If we only want to know if a list consists of a single element, we should pattern match to get a constant time behaviour:

romanCombinations [_] = 1

Use named variants of folds where applicable

Next, we will sum all elements in some list:

  -- we have to change the else due to the new pattern, but more on that later
  else foldr (+) 0 [ romanCombinations xs | (x, xs) <- sep , elem x possibles ]

However, foldr (+) 0 is a common operation and therefore has a name in the Prelude: sum. We should use the named variant to convey our intend:

  else sum [ romanCombinations xs | (x, xs) <- sep , elem x possibles ]

Similarly, divide is already in the Prelude, it's called splitAt, although the arguments are flipped:

  where
    divide str n = splitAt n str

Use Hoogle to find functions

But how would we find those functions? With Hoogle. If we search for Num a => \[a\] -> a, we will come across sum very soon, and if we search for [a] -> Int -> ([a], [a]), Hoogle will also find splitAt, even though the arguments are flipped.

Note that you sometimes need to use more general type signatures to find something with Hoogle.

All together so far

If we apply all those recommendations, we end up with

romanCombinations :: String -> Int
romanCombinations []  = 1
romanCombinations [_] = 1
romanCombinations str = sum [ romanCombinations xs | (x, xs) <- sep , elem x possibles ]
  where
    sep       = map (`splitAt` str) $ take (length str) [1..4]
    possibles = ["X", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

Adjusting the length of a list by another list

We're already at the end. However, there is one last step we should take: get rid of the other length. That can be done with zip and map:

limit :: [a] -> [b] -> [b]
limit xs = map snd . zip  xs

In case you're not familiar with pointfree-code, it's the same as

limit :: [a] -> [b] -> [b]
limit xs ys = map snd (zip xs ys)

As zip will end whenever the shorter list is exhausted, this will limit str to at most 4 elements in [1..4] and of course limit [1..4] to at most length str.

We end up with

romanCombinations :: String -> Int
romanCombinations []  = 1
romanCombinations [_] = 1
romanCombinations str = sum [ romanCombinations xs | (x, xs) <- sep , elem x possibles ]
  where
    sep       = map (`splitAt` str) $ limit str [1..4]
    possibles = ["X", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

limit :: [a] -> [b] -> [b]
limit xs = map snd . zip  xs

Bottom line

All in all, your original code was already easy to read, had type signatures and uses   simple splitting algorithm one can easily infer from your code. That being said, I haven't checked your algorithm or thought about improvements but only checked the code.

I recommend you to check the Prelude, as splitAt and sum are already available for your use without any import. Also, try to avoid length. Either work with the list immediately (e.g. map, fold, sum, ...) or pattern match.


How to remove duplicated code? AOP and Generics are Ok

I assume you really need to distinguish Circle and Triangle.
Any way you can use auto-properties of base class.

public abstract class BaseItem
{
    public int Id { get; set; }
    public string Description { get; set; }
}

public sealed class TriangleItem : BaseItem
{
    // Another TriangleItem class members
}

public sealed class CircleItem : BaseItem
{
    // Another CircleItem class members
}

Boxing mehtods differ in type of object they return, which is subtype of BaseBox though.
That means you can merge them and delegate particular boxes creation to subclasses.

public abstract class BaseBox
{
    public string ItemsXml { get; set; }
    public string Descriptions { get; set; }

    public BaseBox Boxing(BaseItem[] items)
    {
        var ids = items.ToList().Select(i => i.Id.ToString()).ToArray();
        var descriptions = items.ToList().Select(i => i.Description.ToString()).ToArray();
        var box = CreateBox(Util.ToXml(ids), descriptions.Aggregate((d, next) => next + ", " + d));
        return box;
    }

    public BaseItem[] Unboxing()
    {
        return Util.FromXml(ItemsXml).Select(i => CreateItem(int.Parse(i), i)).ToArray();
    }

    protected abstract BaseBox CreateBox(string itemsXml, string descriptions);

    protected abstract BaseItem CreateItem(int id, string description);
}

The same can be done for unboxing and BaseItem.

public sealed class TriangleBox : BaseBox
{
    protected override BaseBox CreateBox(string itemsXml, string descriptions)
    {
        return new TriangleBox { ItemsXml = itemsXml, Descriptions = descriptions };
    }

    protected override BaseItem CreateItem(int id, string description)
    {
        return new TriangleItem { Id = id, Description = description };
    }
}

public sealed class CircleBox : BaseBox
{
    protected override BaseBox CreateBox(string itemsXml, string descriptions)
    {
        return new CircleBox { ItemsXml = itemsXml, Descriptions = descriptions };
    }

    protected override BaseItem CreateItem(int id, string description)
    {
        return new CircleItem { Id = id, Description = description };
    }
}

Update:
Boxing method should be void. And probably renamed to 'DoBoxing'.

public abstract class BaseBox
{
    ...

    public void Boxing(BaseItem[] items)
    {
        var ids = items.ToList().Select(i => i.Id.ToString()).ToArray();
        var descriptions = items.ToList().Select(i => i.Description.ToString()).ToArray();
        this.ItemsXml = Util.ToXml(ids);
        this.Descriptions = descriptions.Aggregate((d, next) => next + ", " + d);
    }

    ...
}

And called as:

    public BaseBox Do(BaseItem[] items)
    {
        ...

        if (result != null)
        {
            result.Boxing(items);
        }

        return result;
    }


The first observation that I would make is that your type signature is too specific:

findSame :: [Int] -> [Int] -> [Int] -> [Int]

The function should work for any Ord a:

findSame :: Ord a => [a] -> [a] -> [a] -> [a]

The second observation is that you don't need to work on three lists at a time.  You could just take two lists at a time:

findSame tris $ findSame pents hexes

But what is the findSame operation then?  It's the intersection of two ordered lists.  A quick search reveals an isect function in Data.Ordered.List.

So, the solution could just be

import Data.List.Ordered (isect)
head $ filter (> 40755) $ isect tris $ isect pents hexes

Or, more elegantly:

head $ filter (> 40755) $ foldr1 isect [hexes, pents, tris]

The implementation of isect is simple enough that you could just "steal" it.

Minor note: Personally, I would define the sequences so that the subscripts match the notation in the problem statement.

tris  = scanl (+) 0 [1..]
pents = scanl (+) 0 [1, 4..]
hexes = scanl (+) 0 [1, 5..]

That also makes it easier to generalize:

polygonalSeq :: Int -> [Int]
polygonalSeq s = scanl (+) 0 [1, (s - 1)..]
head $ filter (> 40755) $ foldr1 isect $ map polygonalSeq [6, 5, 3]


Maxwell's distribution using Box-Muller transform

The implementation of Gaussian(Random random) does not match the description. You should add the comment about the polar form. I know the equivalence. Some reviewers may not.
Polar form comes with the price. The loop

    do
    {
        x = Uniform(random, -1.0, 1.0);
        y = Uniform(random, -1.0, 1.0);
        r = x * x + y * y;
    }
    while (r >= 1 || r == 0);

is potentially infinite. I'd be scared to see it in the production code.
The Wiki article warns against the price of the basic form coming from the computation of \$\sin\$ and \$\cos\$. I don't buy it. sincos is cheap. Thou shalt profile.
The condition r == 0 is pretty much guaranteed to fail, and I wouldn't trust the result of Math.Log(r) / r for really small r. Do not compare floating point values for equality. Chose an \$\epsilon\$, and compare for r < eps.
Maxwell calls MaxwellComponent three times, and each time MaxwellComponent computes the same MaxwellVariance. Seems excessive.


Dictionary load function using hash table

Your constants could be named slightly differently; consider TABLE_SIZE and MAX_WORD_LENGTH.
You could also rename dictionary to better indicate that it's a file path and not a dictionary object.
Consider printing error output to stderr: fputs(stderr, ...) or fprintf(stderr, ...).
You're using a global nwords, but a local hashtable; this looks to me like a scoping error. You could consider just making a new struct.


Just a short review from me:
The artificial delays (time.sleep(0.5)) are superfluous and not safe. They slow you down sometimes, they fail sometimes, because the pages take longer than usual to load.
Instead you can use Selenium selector functions, to wait until an element appears (or disappears). For example, you could have something like this:
element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//button[text()="Dodaj u korpu"]")))
)

Here, we wait for an element to be in clickable state, but set a timeout of 10 seconds for the condition to be realized. You have a solid range of similar options available. Check out the doc: Waits
Likewise, you can get rid of the exception handling block (NoSuchElementException). My advice is to replace the sleeps with adequate wait functions, depending on the conditions you want to test. This should make your code more reliable and probably a bit faster, because it's not going to wait for longer than necessary.
Since your concern is speed: I would say 4.90 seconds is not bad but I don't know your constraints. Have you benchmarked your code to find out what is taking time ? Use the timeit module or - recommended link: Python Timer Functions: Three Ways to Monitor Your Code to set up your own timing class.
From experience, Selenium takes time to load, so perhaps you might as well leave it running in the background and use a loop to refresh the page at regular intervals, while being gentle and taking care not to overload the site.


Searching for a string in a downloaded PDF

First of all standard library imports and third-party library imports should be kept separate:

from subprocess import PIPE, Popen
from urlparse import urljoin

import mechanize

It's better to put your code in a function so that you re-use it with different urls, search keywords etc. Further explanation in comments:

def pdf_contains(url, file_url, search_key, keyword=''):
    br = mechanize.Browser()
    br.open(url)
    print br.title()
    # As you're interested only in the first link text that contains
    # the keyword('Sunday,' in this case) we should better use next()
    # with a generator expression. `next()` will yield the first item from
    # the generator if any otherwise we'll return None
    # Also `urlparse.urljoin` can come handy in joining urls.

    pdf = next((urljoin(file_url, f.url) for f in br.links()
               if keyword in f.text), None)

    # Now instead of downloading the file using .urlretrive we
    # can simply simply get a file-like object using
    # `mechanize.urlopen` which then we can then pass to
    # subprocess's STDIN

    if pdf is not None:
        data = mechanize.urlopen(pdf)

        # Now instead of running `os.system` and storing the output
        # in a file we can use `subprocess.Popen` to store the
        # output of ps2ascii command in PIPE

        proc = Popen(['ps2ascii'], stdin=data, stdout=PIPE)

        # Now simply read the data line by line from PIPE
        # and check for the search_key, if found return instantly
        for line in iter(proc.stdout.readline, ''):
            if search_key in line:
                return True
    return False

url = ("http://sttm.org/Bulletin/Bulletins2015/tabid/483/Link"
       "Click.aspx?fileticket=WkjzL8SuMQQ%3d&tabid=483&portal"
       "id=0&mid=979", "http://sttm.org/Bulletin/Buletins2015/")

scheduled = pdf_contains(url,
                         "http://sttm.org/Bulletin/Buletins2015/",
                         "My Name Here",
                         "Sunday,")

print scheduled


Fibonacci sequence binary tree console logger

One thing I would recommend is using memoization.  Make a dictionary of fibonacci numbers that you've already calculated (do the math once when the user gives you input).  When you go to calculate a node's fibonacci value, just do a check in the dictionary for the appropriate value.  This will avoid calculating the lower levels so much.
Actually, if you only know the level the node is on, you could instead put the fibonacci values in an array (python list) where the index of the array is the number that should be shown on that level of the tree.
Either way, there are ways to use memoization to avoid duplicate effort, and it can make a big difference in your speed for a lot of problems.


Handling exceptions for providing log information while debugging

Exceptions have Message property, which you should use, if you want to tell someone what went wrong in human language. You can then use String.Format("Razor parse failed: {0}", ex.Message) for all your exceptions. This will allow you, for example, to throw multiple InvalidOperationExceptions in the future without worrying about how you are going to log those.

Not to mention, that the guy debugging your code will likely prefer to know what went wrong straight away, without the need to look for log messages in your code or in log files.


Inversion of an array that contains indices

Unfortunately I don't really know visual basic but I think that you will find it easy to grasp the idea (and implement it in any language) of the following java code:

int[] source = new int[]{2,0,1};
int[] dest = new int[source.length];
for (int i = 0; i < source.length; i += 1) {
    dest[source[i]] = i;
}

The code runs at \$O(n)\$ time whereas if you search for every element you get \$O(n^2)\$ time.


Count words in string and tally up the repetitive words

Just finished that exercise too.
I think you can extract some of that logic to anonymous functions.
It isolates a pieces of behaviour that you can work on.

defmodule Words do
  @doc """
  Count the number of words in the sentence.

  Words are compared case-insensitively.
  """
  @spec count(String.t) :: map
  def count(sentence) do
    filter_word = fn(word) ->
      String.match?(word, ~r/[a-zA-z\d]/)
    end

    remove_special_characters = fn(word) ->
      String.replace(word, ~r/[:!&@$%^,]/, "")
    end

    count_words = fn({k, v}, acc) ->
      Map.put(acc, k, Enum.count(v))
    end

    sentence
    |> String.downcase
    |> String.split(~r/[\s_]/)
    |> Enum.filter(filter_word)
    |> Enum.map(remove_special_characters)
    |> Enum.group_by(fn(word) -> word end)
    |> Enum.reduce(%{}, count_words)
  end

end

And actually, I've created a function that returns a list of words to count: http://exercism.io/submissions/e26667aff3734da79ac0b6c6fedfd3da

Hope that helps!