Precise timing event dispatching in Java

First of all, let me clarify that you can't do precise timing on a "normal" desktop or server operating system. You can be close, but the schedulers are not designed for that, you're not guaranteed to get a time slice for execution at all. The smaller your time-slices get, the bigger the error margins will be. The higher the load on the machine will be, the more slices you will miss.

 * Like my girlfriend, Java has some problems to be on time. He is always a bite late.

I'm most likely old and grumpy, but "funny" comments and variable names are a waste of everyones time at the end of the day. That and, if you ever want to use your code as portfolio for a job, or in your job, might cost you. Because when I see that comment, I can deduct a few things:

The programmer considers it okay to make fun of others in the public.
The programmer does not know anything about how the JVM works.
The programmer does not know anything about how the OS scheduler works.
The programmer does most likely not know anything about the Java ecosystem (Java is used for high-speed trading with stock exchanges, doing trades in the microsecond range).

Of course, what you do in your private projects is none of my business, but be aware that this comes at a cost in one way or another...and maybe not for you, as others might have to maintain your code at some point.
And to ask a different question...does your girlfriend know she's a cheap joke on the internet for you?

long n;
int i=0;

These names could be better, a lot better actually.

long nanosBetweenTicks = (long) (60_000_000_000d / bpm);

This would, do well as a constant.

__JAVA_CORRECTION_NANOS

Normally, you don't have leading underscores under the Java convention.

i++; // erf... let's hope we miss only one tick

That is what I was talking about earlier and is a very good example for a completely unhelpful comment. It tells me that the programmer either had no idea what they were doing, or did not care enough to check it.

while(System.nanoTime()<n + nanosBetweenTicks) /* no body here! */;

I believe that this will not be optimized away because of the System.nanoTime() function call, but I would not bet on it.

The code is otherwise well formatted, and most of the names are good. I'm not sure about the rest of the logic, it seems oddly complicated for what you describe.


It's pretty good, clean and simple code. Not a lot to critique really. A few minor things:

Some people (myself included) prefer to prefix private fields with _. This way it's easy to see that it's a field rather than a local variable (and gets rid of the this. in most cases).
You shouldn't have a public property and a public method which do the same thing. How is a programer supposed to know whether to use Value or GetValue? It's not obvious what the difference is or if there is one at all.
Not 100% sure about the null check in GetValue(). There is no code path where reference should ever be null. So it would actually indicate a bug if it were the case which you are hiding with this check. Consider removing the check or actually throwing an InvalidOperationException or similar instead. Detecting bugs early is important. Another option would be to look at Code Contracts to state the invariants of that method.
I have started to try and avoid null checks where possible by making sure that there is always an object. In your case this could be something like this:

public class Temporary<T> where T : class
{
    private static Func<T> NullGenerator = () => null;

    Func<T> generator = NullGenerator;
    WeakReference reference = null;

    public T Value
    {
        get
        {
            return GetValue();
        }
    }

    public Temporary(T value)
        : this(value, NullGenerator)
    { }

    public Temporary(Func<T> generator)
        : this(null, generator)
    { }

    public Temporary(T value, Func<T> generator)
    {
        if (generator == null)
            throw new ArgumentNullException("generator");
        reference = new WeakReference(value);
        this.generator = generator;
    }

    private T GetValue()
    {
        T res;
        if (!reference.TryGetTarget(out res))
        {
            res = generator();
            reference.SetTarget(res);
        }
        return res;
    }
}


Finding next perfect number - brute force

You get:

  Hint: you’ll need a sum-of-factors subprocedure.

So I would make sum-of-factors a separate procedure. It's a little confusing as is, since sumOfFactors takes a single argument - and that argument isn't the number whose factors you're summing. That is:

(define (sum-of-factors n)
    ...)

(define (next-perf n)
    (if (= (sum-of-factors n) n)
        n
        (next-perf (+ n 1)))

Note that hyphenated-name is the preferred syntax for function names, as opposed to camelCase.

Once we're there, you can write sum-of-factors to do the looping:

(define (sum-of-factors n)
    (define (add-factor fac) (if (= (remainder n fac) 0) fac 0))
    (define (accum fac) (if (= fac n) 0 (+ (add-factor fac) (accum (+ 1 fac)))
    (accum 1))

I split it up into a few more bite-size functions. I find that helps readability.

In Racket (which I guess isn't up for discussion), you can do the latter way better since there's an in-range procedure that gives you want you need:

(define (sum-of-factors n)
    (for/sum ([fac (in-range 1 (- n 1))])
        (if (= (remainder n fac) 0) fac 0))))

Don't think there's a Scheme equivalent unfortunately, so maybe this is more of a tease than an answer.


I assume by artist you mean graphic or sound effect designers. The logic should independent from its visualisation. How data like altitude is stored or processed is no concern for the artist. To stay in Unity3D, you should create components (or complete prefabs) that render graphics or play sound effects. Having a enum for the dropdown is the preferred way as you mentioned. You map it to the corresponding names in the component for the artits. The component is easy to reuse. In your case extracting UILabel and 'TextBlock' is key. Consider those to styled by artists. You then create copies of the component for speed and coins or make it more generic for those cases.

tl;dr
Create components in Unity to separate logic and represantation (think or MVC controller and view) in components. Design view components artist friendly and controller components coder friendly.


Using Ramda in point-free way to transform data into new format

I like your pipeline approach in general!

  1) Omitting R.flatten and R.splitEvery(2) get pretty close to what Is being output directly from R.map(R.toPairs) so maybe there is a way to deal with that data more directly and those methods can be omitted.

Yup, you want something like R.chain here.

R.chain(R.toPairs)

is equivalent here to

R.pipe(
  R.map(R.toPairs),
  R.flatten,
  R.splitEvery(2)
)

effectively performing a non-recursive flatten on the output of the chained function. Clojure calls this mapcat.

  2) datesValuesReducer is pretty complex, maybe it could be simplified. I'm not sure if having the accum and curr means this solution isn't entirely "point free". Thoughts?

Yeah, named arguments are essentially the "points" you're trying to avoid in the pointfree style.

I see two directions here. One is to shorten the function but add more points via destructuring:

R.reduce((acc, [k, v]) => R.assoc(k, (acc[k] || [k]).concat(v), acc),
         {})

The other is to fall further into the Ramda world and do something like this:

const f = R.pipe(
  R.pluck('timeline_map'),
  R.chain(R.toPairs),
  R.reduceBy(R.flip(R.useWith(R.append, [R.nth(1)])), [], R.head),
  R.toPairs,
  R.map(R.unnest)
)

(The last two functions could probably be turned into a reduce as well if you're determined.)

This is fully pointfree, but seems kinda deliberately obtuse, even if the reduceBy reducer were to be pulled out into a named function. If you want an opinion I'd say stick the entire thing in a function that takes in the base keyword (eg. 'timeline_map'), and then use whatever you find most readable inside that function, without striving for total pointfree purity.

If you want more opinions, arguably there's a sweet spot of, say, 60-70% pointfree where you gain the most from the style. Beyond that, things can become increasingly contorted, and you end up with, well, R.reduceBy(...R.useWith...


Use of p5.js and JavaScript

Math is part of the standard JavaScript library.  You shouldn't pollute its namespace with your own code, because it could interfere with other JavaScript code on the page.  In this case, Math.degrees() is never used, and you could just use p5.js's radians() function instead of writing Math.radians().

The constructor for Orbiter is very unwieldy, with up to 10 parameters.  You can just eliminate most of them.  Furthermore, you should specify colors as a single p5.Color object rather than as four separate parameters.

There should be a windowResized() handler, so that the window (or the Stack Snippet) can be resized gracefully.

Physics and animation

The object around which a satellite orbits is called its primary.  I suggest that you name the parameter to the orbit() method accordingly.

Your planets' angular velocity is given by planets[i].orbitAngleMod= 1.4 - i/7, which is not consistent with the laws of physics.  According to Kepler's Third Law, \$T^2 \propto r^3\$ (where \$T\$ and \$r\$ are the orbital period and radius), so \$\omega \propto r^{-\frac{3}{2}}\$.  So, your inner planets are not as fast as they should be, and your outer planets are not as slow as they should be.

Handling the revolution completion with if(this.orbitAngle >= 360){ this.orbitAngle = 0; } can lead to round-off glitches.  A modulo operation would be more appropriate.

I don't see the point of initializing the initial angles of the planets to i * 5 — an offset of up to 4° relative to the x axis is hardly visible.

class Orbiter {
    constructor(sizeRadius, orbitRadius, orbitAngle=0) {
        this.sizeRadius = sizeRadius;
        this.orbitRadius = orbitRadius;
        this.orbitAngle = 0; // degrees relative to x axis

        // 2000 is an arbitrary animation speed (which also depends on the frame rate)
        // The -1.5 exponent is due to Kepler's 3rd Law
        this.orbitAngleDelta = 2000 * Math.pow(orbitRadius, -1.5);
        this.x = this.y = 0;
        this.color = 'white';
    }

    orbit(primary) {
        this.x = primary.x + this.orbitRadius * cos(radians(this.orbitAngle));
        this.y = primary.y + this.orbitRadius * sin(radians(this.orbitAngle));
        this.orbitAngle = (this.orbitAngle + this.orbitAngleDelta) % 360;
    }

    display() {
        noStroke();
        fill(this.color);
        return ellipse(this.x, this.y, this.sizeRadius, this.sizeRadius);
    }
}

let planets = [];
let sun = new Orbiter(100, 0);

function setup() {
    createCanvas(windowWidth - 3, windowHeight - 3);
    frameRate(144);

    sun.x = windowWidth / 2;
    sun.y = windowHeight / 2;
    sun.color = color(255, 200, 0);

    // Instantiate 5 planets
    for (i = 0; i < 5; i++) {
        planets[i] = new Orbiter(5 + 15 * i, 110 + 70 * i);
        let red = i * 50 + 5;
        planets[i].color = color(red, 255 - red, 255 - red);
    }
}

function windowResized() {
    resizeCanvas(windowWidth - 3, windowHeight - 3);
    sun.x = windowWidth / 2;
    sun.y = windowHeight / 2;
}

function draw() {
    background(0, 10, 40);
    sun.display()
    for (planet of planets) {
        planet.orbit(sun);
        planet.display();
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>


Reading properties from file during standalone application startup

What I find bothering is not the ApplicationConfig class and the static initializer, in itself. It's the fact that defaultEventServerPort and defaultClientServerPort are global variables, which should be avoided.

What you should have are two constants defining the default values, 2 variables holding the actual values as instance fields.

private static final int DEFAULT_EVENT_SERVER_PORT = 9090;
private static final int DEFAULT_CLIENT_SERVER_PORT = 9099;

private int eventServerPort;
private int clientServerPort;

and the initialization of those 2 variables done in the constructor. The purpose of doing this in the constructor, instead of a static initializer, is that it lets you have proper instance fields.

The first concern is that there's duplicated code in this: the logic for extracting the port from the Properties object, converting it to an int or using the default value, will be the same for both ports. Therefore, it makes sense to create a method for that:

private static int getAsIntOrDefault(Properties properties, String key, int defaultValue) {
    String val = properties.getProperty(key);
    if (isValidNumeric(val)) {
        return Integer.parseInt(val);
    }
    return defaultValue;
}

Notice that instead of using Integer.valueOf, which returns an Integer object, we can directly use Integer.parseInt, which returns a primitive int. This way, we don't need to have a boxing, and then unboxing conversion.

There is another problem with how the Properties object is loaded: you have a potential memory leak!

APP_PROPERTIES.load(ClassLoader.class.getResourceAsStream("/app.properties"));

This is opening an InputStream, but it is never closed. Instead, use a try-with-resources construct:

try (InputStream is = ClassLoader.class.getResourceAsStream("/app.properties")){
    APP_PROPERTIES.load(is);
} catch (IOException ex) {
    // ...
}

With those changes, you can have the following:

ApplicationConfig() {
    try (InputStream is = ClassLoader.class.getResourceAsStream("/app.properties")){
        APP_PROPERTIES.load(is);
    } catch (IOException ex) {
         // do the logging
    }
    eventServerPort = getAsIntOrDefault(APP_PROPERTIES, "server.event.port", DEFAULT_EVENT_SERVER_PORT);
    clientServerPort = getAsIntOrDefault(APP_PROPERTIES, "server.client.port", DEFAULT_CLIENT_SERVER_PORT);
}

The try-catch block was also reduced so that it spans the minimal amount of code as possible. try-catch should be small and cover only the part of the code that can actually throw the exception you want to catch.

Last point, you can see the advantage of using a constructor here: later, you may want to remove hard-coding "/app.properties". With a constructor, you can easily now pass the path to the properties file, which would be complicated to do with a static initializer.

Nitpick: isValidNumeric won't return true for negative numbers, so you may want to rename it to isValidPositiveInteger. Also, does APP_PROPERTIES really need to be static final as well? I would imagine it is only used to fetch all of the configuration values once, and unused later on.


How to shorten this code or make it more efficient?

In a first step I would extract a method to generate the string.

changed code:

            //CHOOSE LEVEL: FROZEN
case 1213:
    sendOption5(
            levelString( 1, c),
            levelString( 2, c),
            levelString( 3, c),
            levelString( 4, c),
            "More");
    c.dialogueAction = 1213;
    break;
case 1214:
    sendOption5(
            levelString( 5, c),
            levelString( 6, c),
            levelString( 7, c),
            levelString( 8, c),
            "More");
    c.dialogueAction = 1214;
    break;
case 1215:
    sendOption5(
            levelString( 9, c),
            levelString(10, c),
            levelString(11, c),
            "",
            "Choose Floor");
    c.dialogueAction = 1215;
    break;

extracted method:

private static String levelString(int i, TypeOfC c){
   return "Level " + i + (c.achievedFloor <= i ? " @gre@(Achieved)" : " @red@(Not achieved)");
}

You should also think about changing the parameters of your sendOption5 to get only c and two integers from to which define the inteval of values.

And you can move the c.dialogueAction = xxxx; line behind the switch and assign the value you use for the switch.


I wouldn't recommend passing and returning the vector by value. Pass by reference, and do not return at all - typically sorting is done in place anyway.

Another generic advice: no raw loops. The internal loop does some important job, which has to be realized and given a proper name, insert perhaps.

typedef std::vector<int>::size vsize_t;
void ins_sort(std::vector<int> & series)
{
    for(vsize_t i=1; i < series.size(); i++)
    {
        insert(series, i, series[i]);
    }
}

void insert(std::vector<int> & series, vsize_t last, int key)
{
    for (vsize_t j = last - 1; j > -1; --j)
    {
        if (key < series[j]) {
            series[j + 1] = series[j];
            series[j] = key;
        }
        else
            break;
    }
}

Now it is possible to simplify the logic by eliminating j, and combining the two condition checks together:

void insert(std::vector<int> & series, vsize_t last, int key)
{
    while ((--last > -1) && (key < series[last]))
    {
        series[last + 1] = series[last];
        series[last] = key;
    }
}

You can see how the series[last] = key; assignment is rather redundant - it will necessarily be overwritten at the next iteration, so it only makes sense only at the last one:

void insert(std::vector<int> & series, vsize_t last, int key)
{
    while ((--last > -1) && (key < series[last]))
    {
        series[last + 1] = series[last];
    }
    series[last] = key;
}

Testing two conditions at every iteration is expensive. You may notice that the first condition only strikes if key is less than all the elements, in other words, it is less than series[0] (it is sorted up to the point already):

void insert(std::vector<int> & series, vsize_t last, int key)
{
    if (key < series[0]) {
        while (last-- > 0) {
            series[last+1] = series[last];
        }
    } else {
        while (key < series[last])
        {
            series[last+1] = series[last];
        }
    }
    series[last] = key;
}

and applying the rule one more time, we see that the first loop does shift right by 1, and the second does unguarded shift right by one.

Combining everything, we are getting:

typedef std::vector<int>::size vsize_t;
vsize_t unguarded_shift(std::vector<int> & series, vsize_t last, int key)
{
    while (key < series[last--])
    {
        series[last + 1] = series[last];
    }
    return last;
}

vsize_t shift(std::vector<int> & series, vsize_t last)
{
    while (last-- > 0) {
        series[last+1] = series[last];
    }
    return last;
}

void insert(std::vector<int> & series, vsize_t last, int key)
{
    if (key < series[0]) {
        last = shift(series, last);
    } else {
        last = unguarded_shift(series, last, key);
    }
    series[last] = key;
}

void ins_sort(std::vector<int> & series)
{
    for(vsize_t i=1; i < series.size(); i++)
    {
        insert(series, i, series[i])
    }
}


Though you are getting desired output, here in your code you are not exactly generating characters at all indices/positions of the char pass[12]; array. let me explain

consider the following for loop in your code:

for (i = 0; i < 4; i++) {
    pass[i] = rand() % 10; //10 instead of 9 to produce digits from 0 to 9
    char capLetter = 'A' + (rand() % 26);
    pass[i + 2] = capLetter;
    char letter = 'a' + (rand() % 26);
    pass[i + 3] = letter;
    printf("%d%c%c", pass[i], pass[i + 2], pass[i + 3]);
}

consider the maximum cases i.e, when i = 3 and pass[i + 3], then pass[i + 3] is equivalent to pass[6] so the maximum index value that you can access is 6. So you are not generating random value at all indices of the pass[] array but only within 0 to 6 positions and printing the generated characters in each iteration.

Instead try using for loop this way to generate random character at all the indices:

for (i = 0; i < 4; i++)
{
    pass[ 3 * i ] = rand() % 10;
    char capLetter = 'A' + (rand() % 26);
    pass[(3 * i) + 1] = capLetter;
    char letter = 'a' + (rand() % 26);
    pass[(3 * i) + 2] = letter;
    printf("%d%c%c", pass[3 * i], pass[(3 * i) + 1], pass[(3 * i) + 2]);
}

here you can access all the 12 indices i.e, 0 to 11

further, instead of using pass[i] = rand() % 9; to generate a random character and using %d, you can do pass[i] = '0' + (rand() % 10); (use 10 instead of 9 if not 9 will never be printed) to generate a numeric character and use %c. Since you have a character array, you can append the array with a null terminating character ('\0') and make it a string and print the generated password this way:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>   //not required
#include <time.h>

int main(void) //int main() is not a valid signature in C
{
    srand((unsigned int)(time(NULL)));
    int i;
    char pass[13]; //extra byte for null terminating character

    printf("Press enter to get a twelve-character password\n");
    getchar();

    for (i = 0; i < 4; i++)
    {
        //revised logic to generate random characters at all positions (0 - 11)
        pass[ 3 * i ] = '0' + (rand() % 10); //generating numeric character
        char capLetter = 'A' + (rand() % 26); //generating upper case alpha character
        pass[(3 * i) + 1] = capLetter;
        char letter = 'a' + (rand() % 26); //generating lower case alpha character
        pass[(3 * i) + 2] = letter;
    }
    pass[3 * i] = '\0'; //placing null terminating character at the end
    printf("generated password : %s\n\n",pass); //printing the string

    printf("\n\n");
}

  I want to make it more efficient if I can, and perhaps add some
  punctuation, which does not seem that easy, since the ASCII codes are
  quite spread out.

Here is a way to generate passwords which includes punctuation without caring about ASCII code at all! Right now, you are following a fixed pattern of printing uppercase letter followed by number and then a lowercase letter, and you repeat it for three more times to generate a 12 character password. Instead you could randomly generate the password without any such pattern and not using ASCII codes at all!

create a string of all permissible characters
use the string to print 12 character from any 12 random positions

here's the program which follows the above two steps to generate a password and you can add all the permissible characters in the string which I have not mentioned

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
     srand((unsigned int)(time(NULL)));

    int index = 0;

    //step 1
    char characters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/,.-+=~`<>:";
    //I just added a few punctuations characters for explanatory purpose
    //you can add all the additional punctuations which are required

    //step 2
    for(index = 0; index < 12; index++)
    {
        printf("%c", characters[rand() % (sizeof characters - 1)]);
    }

}

I'd say generating the password is much more advantageous as you can only randomly select from the characters that provide in the string. All you need to do is just put in all the permissible characters in the string and you are bound to get a randomly generated password :)


Implementation of Point, Velocity and Acceleration in Haskell

Use GeneralizedNewtypeDeriving if you use the same instance as the wrapped type anyway. Together with DeriveFunctor, we can get rid of much boilerplate (comments omitted, changes noted with -- <--):

{-# LANGUAGE KindSignatures, DataKinds, TypeOperators #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveFunctor #-}                -- <--

import Control.Comonad

import GHC.TypeLits
import Linear
import Linear.V2

type R = Double
type Vector = V2

newtype Time a = Time { fromTime :: a } deriving (Functor, Num)           -- <--

instance Comonad Time where
    extract = fromTime
    duplicate = Time

newtype D (r :: Nat) (v :: * -> *) (u :: * -> *) a = D { fromD :: (u a) }
    deriving (Functor, Applicative, Additive)                             -- <--

type Pnt = D 0 Time Vector R
type Vel = D 1 Time Vector R
type Acc = D 2 Time Vector R

derive ::
    (Comonad v, Functor u, Num a) =>
        v a -> D (r + 1) v u a -> D r v u a

derive dv du = D $ (extract dv) *^ (fromD du)

This immediately gets rid of your Additive problem. Also, now that Time is a Num instance, you can use derive like this:

derive 3 (pure 3 :: Vel)

Unfortunately, Num also contains (*), so you'll be able to multiply time values, which doesn't really make sense in this case. Alas, there is no other way to get fromInteger otherwise.

However, let's have a look at the wrapper, D and derive. The type of derive is a little bit too general. It allows you to do stuff like this:

ghci> import Data.Tree
ghci> derive (Node 10 []) (pure 2 :: D 2 Tree Vector Double)
D {fromD = V2 20.0 20.0} -- if we add Show to D's instances

Could this be a valid use case? Who knows. Is it likely to be a valid use case? Rather not. Get back to the original inspiration for derive:

derive :: Time -> Velocity     -> Point
derive :: Time -> Acceleration -> Velocity

We expect the first argument always to be some kind of time measurement. We also expect the vector to be conform to the time's unit(*). From this point of view, it makes sense to encode the Time in D. However, this yields the question why the other side of the spacetime, space, isn't encoded in D too.

(*) strictly speaking, we're not encoding time's unit but only type.

Either way, you probably want to allow only Time values. Furthermore, you want to make clear what unit Time uses. We could use a phantom type, e.g.

{-# LANGUAGE DataKinds, KindSignatures, GeneralizedNumtypeDeriving #-}
data TimeUnit = Milliseconds | Seconds | Minutes | Hours

newtype Time (* :: TimeUnit) a = Time {fromTime :: a} deriving (Show, Num)

which makes sure that we don't mix different times:

> (Time 3 :: Time 'Seconds Double) + (Time 10 :: Time 'Minutes Double)
Couldn't match type ‘'Minutes’ with ‘'Seconds’
Expected type: Time 'Seconds Double
  Actual type: Time 'Minutes Double
In the second argument of ‘(+)’, namely
  ‘(Time 10 :: Time Minutes Double)’
In the expression:
  (Time 3 :: Time Seconds Double) + (Time 10 :: Time Minutes Double)

But that's out of scope for this review. Instead, we can simply say that Time's unit is seconds, disallow creating Time values with its data constructor, and provide some helper functions:

module Movement
 ( Time, getSeconds
 , seconds, minutes
 , ...
 )
where

newtype Time a = Time { getSeconds :: a }

seconds :: Num a => a -> Time a
seconds = Time

minutes :: Num a => a -> Time a
minutes = seconds . (60 *)

derive :: (Functor u, Num a) => Time a -> D (r + 1) u a -> D r u a
derive (Time s) du = D $ s *^ (fromD du)

Alright. Let's reflect all changes:

used GeneralizedNewtypeDeriving to get rid of boilerplate (major change)
instead of allowing general Comonads, only allow Time (*)
removed Time from D, since derive fixes it  (*)
make the unit of time explicit with "smart" constructors and remove the Time data constructor from the exports.

(*) You can still use those techniques internally, but a public interface should be hard to use wrong if possible. After all, that's the reason you're using r :: Nat and derive :: ... -> D (r + 1) ... -> D r, right?

We end up with the following code:

{-# LANGUAGE KindSignatures, DataKinds, TypeOperators #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveFunctor #-}
module Movement
 ( Time, getSeconds
 , R, Vector,
 , D(..), Pnt, Vel, Acc
 , seconds, minutes
 , derive
 )
where

import GHC.TypeLits
import Linear
import Linear.V2

type R = Double
type Vector = V2

newtype Time a = Time { getSeconds :: a } deriving (Functor)

newtype D (r :: Nat) (u :: * -> *) a = D { fromD :: (u a) }
    deriving (Functor, Applicative, Additive, Show)

type Pnt = D 0 Vector R
type Vel = D 1 Vector R
type Acc = D 2 Vector R

seconds :: Num a => a -> Time a
seconds = Time

minutes :: Num a => a -> Time a
minutes = seconds . (60 *)

derive :: (Functor u, Num a) => Time a -> D (r + 1) u a -> D r u a
derive (Time s) du = D $ s *^ (fromD du)

  Am I wrong about naturality which I meantioned above; is it ok to use wrappers like Time like I did in derive function?

Using wrappers is fine. For example, the UniversalTime in the time package is just a wrapper around Rational. And although it doesn't export its constructor, DiffTime is also just a newtype of Pico.

Maybe it feels more natural with the helper functions:

someCalculation :: Vec
someCalculation =
  let time = seconds 120
      acc  = D (V2 10 10) -- (*)
  in derive time acc

(*) This example will probably inspire you to provide Num a => a -> a -> D r V2 a functions.


Converting a string to a corresponding type in JavaScript

On thing to keep in mind is that certain inputs that you might not consider to be numbers will be considered numbers by the isNaN and Number functions.

Potentially Unexpected Numbers:

Infinity ("Infinity")
hexidecimal notation ("0x1a3")
scientific notation ("0e9" and "0e+9" and "0e-9")

function convert(value) {
    var result = value;
    if (typeof value === 'string') {
        // check if it is a empty character
        value.trim();
        if (value.length > 0) {
            if (/\S/.test(value)) {
                if (value === 'true') {
                    result = true;
                } else if (value === 'false') {
                    result = false
                } else if (!isNaN(value)) {
                    result = new Number(value);
                }
            }
        }
    }
    return result;
}

var rows = document.querySelectorAll(".row");
for(var i = 0; i < rows.length; i++){
  var input = rows[i].querySelector(".in");
  var output = rows[i].querySelector(".out");
  var type = rows[i].querySelector(".type")

  var value = input.getAttribute("value");
  if(value){input.innerHTML = "\""+value+"\""}

  var result = convert(input.getAttribute("value"));
  output.innerHTML = result

  var typeValue = typeof result === "object" ? isNaN(result) ? typeof result : result === null ? "null" : "number" : typeof result;
  type.innerHTML = typeValue;
  if(typeValue === "number"){if(type.classList){type.classList.add("highlight");}else{type.className = type.className + " " + "highlight";}}
}
.table{display:table;border-left:1px solid black;table-layout:fixed; min-width:300px;}
.headerRow{display:table-row;background-color:#dfdfdf;font-weight:bold;}
.headerCell{display:table-cell; border-right:1px solid black; border-bottom:1px solid black; border-top:1px solid black;}
.row{display:table-row;}
.cell{display:table-cell; border-right:1px solid black;border-bottom:1px solid #dfdfdf;}
.highlight{background-color:lightgreen;}

Input String

Output Value

Output Type

""

Boolean values are also considered numbers, but your function has that covered.


Extra typenames

Every place you use typename, it's unnecessary. std::enable_if_t will take care of that for you.

thread_local

First of all, thread_local implies static, so writing both is redundant. Secondly, if you're making it thread_local, that's effectively like making a thread-specific singlelton - so you should return a reference to it, not a copy:

template<class T = std::mt19937, std::size_t N = T::state_size>
auto randomEngine() -> std::enable_if_t<!!N, T&>

And take it by reference:

static auto& RandomEngine = randomEngine();

random()

I'm not sure it's a good idea to create the distribution every time. The distribution object itself can keep state, so I think it'd be a better idea to take it in instead:

template <class Dist>
typename Dist::result_type random(Dist& dist)
{
    static auto& RandomEngine = randomEngine();
    return dist(RandomEngine);
}

And alter dist<T> to take arguments so that you could do:

auto d = dist<unsigned>(0, 15);
for (auto i = 0u; i < 16; ++i)
    std::cout << random(d) << ' ';


Wow! If this is you after one day, we hope for great things.

However, you can make your program simpler. Let's start with factorize. It has a couple of defects:

It uses proper recursion where tail recursion with recur would
suffice. So it would overflow the stack for a number having too many
factors. However, since it uses long arithmetic, no number is big
enough to do this.
Each recursive call retries all the primes that have failed to be
factors.

You can do it with a single loop if you exhaust each prime factor as you go:

(defn factorize [num]
  (loop [num num, acc [1], primes (lazy-primes)]
    (if (= num 1)
      acc
      (let [factor (first primes)]
        (if (= 0 (mod num factor))
          (recur (quot num factor) (conj acc factor) primes)
          (recur num acc (rest primes)))))))

Now let's look at lazy-primes. While sticking to your algorithm ...

We can simplify the base case - the one with no arguments.
You produce a lazy sequence level for every number tested. We can
use recur to short-circuit tail recursion for all the numbers that
fail to be prime.
We can use take-while, map, and not-any? to express the prime
testing more clearly (though it will run slower). Because these
are lazy, we don't do any redundant testing.

The result is

(defn lazy-primes
  ([] (lazy-primes 2 []))
  ([current known-primes]
    (let [factors (take-while #(<= (* % %) current) known-primes)
          remainders (map #(mod current %) factors)]
      (if (not-any? zero? remainders)
        (lazy-seq (cons
                    current
                    (lazy-primes (inc current) (conj known-primes current))))
        (recur (inc current) known-primes)))))

A couple of arbitrary changes:

I've used the abbreviated #(...) function syntax.
I renamed calculated-primes to known-primes.

Edited to correct an erroneous comment.


Using UnitOfWork/Repository pattern in static class/methods

It entirely depends on your implementation of the unit of works members. If the IDataRepository is using something like NHibernate and keeping open persistent connections (which, being part of a unit of work, I presume it might) you will absolutely run into weird database connectivity issues when using a private static member.

The reason for this, is that the static property is shared between all instances of the CustomerService, in your example, so you'll have one of those, and it'll be constructed with "whatever it gets at the time" - for example, the first database connection or session your application opens.  If you have some sort of session per request handling that subsequently disposes of that session, the static class will still hold a reference to it, and you'll have a bad time.

To deal with this problem in some things that "must be" static, there's a cheap little trick you can use - add a static func to some form of resolver or container that you wire up at bootstrapping time:

public class ContainerRegistrationCode
{
    public void RegisterTypesInContainer()
    {
        Kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
        CustomerService.GetCurrentUnitOfWork = () => Kernel.GetService<IUnitOfWork>();
    }
}

public class CustomerService
{
    public static Func<IUnitOfWork> GetCurrentUnitOfWork { get; set; }

    public static List<Customer> GetCustomers()
    {
        var currentUnitOfWork = GetCurrentUnitOfWork ();
        currentUnitOfWork.CustomerRepository.Find(t => t.ID == 123).ToList();
    }
}

This way, you delegate out to a container or something that can manage the lifecycle of the unit of work, and every time you use it in a static context, you call the func which gets whatever the current one is.

It's a bit of a hack, don't use statics, use a good container instead that supports scoping (like Ninject) and you just shouldn't have this problem.


JavaScript implementation of insertion sort

I just started reading Introduction to Algorithms

Do you mean the popular textbook from MIT Press? In a course taught using this book, it would likely not be acceptable to use other library functions like Array.prototype.splice. Here it glosses over a significant part of insertion sort, which is making space for the next value in the already sorted half of the array. It hides what might be an essential factor in runtime analysis.

In the book pseudocode, it shifts the numbers in the while loop using the assignment A[i + 1] = A[i]. That is more standard array usage and should work just fine in JS.

Pragmatically, using JS arrays for analysis of algorithms is problematic because they can quietly increase in size more like an ArrayList in Java than a regular array. The usage of splice in this code causes the array to change size from n to n+1, then back to n, which is not necessarily trivial at runtime.

  I thought I'd ask for feedback right at the start since this is a really new topic to me.

The courses based on this book are often not very heavy on coding, focusing more on reasoning and proofs. As I recall, the book exercises do not feature programming. For hands-on experience implementing algorithms, there may be better books.

In the CS program that I attended, there was an earlier class that used a book like Data Structures and Algorithms in Java by Goodrich and Tamassia which focused heavily on implementation.


Using Statement for OleDB - Is this overkill?

The Using is good practice and not overkill. Trying to dispose the resources in the Finally part has the disadvantage, that you don't know when the exception happened and which resources have been assigned by that time. The Using statement does this automatically for you internally: If resouce <> Nothing Then resource.Dispose() End If
You need different connection strings for the different Excel types. You can use this function:

Private Function GetConnectionString(ByVal filename As String) As String
    Const xlsConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;"
    Const xlsxConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;"

    If Path.GetExtension(filename).Length = 5 Then ' .xlsx, .xltx
        Return String.Format(xlsxConnString, filename)
    Else ' .xls, .xlt
        Return String.Format(xlsConnString, filename)
    End If
End Function

You can either propagate the exception or return Nothing. In my opinion, your version does it very well.


Get the length of data within a buffer (by getting the position of the last byte with data)

If your array is completely "empty" your current method will throw an exeption because it will try to get array[-1].

Just use a for loop starting at 0 and if you find the first 0 return index-1. For the case that the whole buffer is filled return array.Length - 1.

Update:

As it seems it is possible that there are 0 values in between valid data like [+][+][+][+][ ][ ][ ][+][+][+][ ]...[ ]. Hence going from start to end of the array doesn't seem a reliable action.

Using a for loop instead of using the while loop enables your code to do the empty check as well like so

public const int NotFound = -1;
public static int GetPositionOfLastByteWithData(this byte[] array)
{
    for (int i = array.Length - 1; i > -1; i--)
    {
        if (array[i] > 0) { return i; }
    }
    return NotFound;
}

As you are talking about streams in your question, wouldn't it be better to store the index of the last written byte ? This would be the easiest and the most safe variant because, assuming you are reading exactly 10 bytes from the stream and later on you need exactly these 10 bytes to restore the read data. If the last byte of that stream would be a 0 like
[+][+][+][+][+][+][+][+][+][ ][ ][ ][ ][ ]...[ ]

both methods, yours and mine, would return 8 but the really read byte count would be 9.


Document your instruction format! Looks to be opcode,
destination, 8 bytes of input. You need to describe the endianness
of the data though.  Comments are an OK first step, but data
structures with self-describing names are probably even better.
You could avoid entire classes of errors by splitting the
program and data memory. This is "Harvard" vs "von Neumann"
architecture.
Remove unneeded type specification, such as when defining
registers in main.
Can use Default::default to get a reasonable initial state,
such as a vector of zeroes. Prevents having to re-type the length
again.
Don't use explicit return statements at the end of functions.
What is the expected behavior if you concat a slice with more
than 8 bytes? I made this limit to the first 8 bytes.
Become intimately familiar with the methods on Iterator and try to leverage the functional tools it provides, like fold.
Avoid slice indexing whenever possible. It's slightly slower as
it performs bounds checks.
concat is a bit odd of a name. I feel that pack is more
typical for this operation.
Your opcode is crying out to be an enum. This also happens to be
a great place to hang behavior, such as converting it to/from an
integer.
It's a little strange that eval accepts the program and
registers by value. Maybe you want to create a Machine that owns
them, or accept them by mutable reference?
It's strange that Program contains a pointer to where the data
is. Typically, the program should be immutable and you'd have a
Program Counter (PC) that tracks where you are in the program.
Printing the registers each iteration is a form of logging. If
you need such a thing, inject it using a generic. In this case, I
just accepted a generic function type, but you could also create
your own trait if you wanted more granular places to log.
You should basically never use a &Vec<T>; use &[T] instead.
You should basically never use process:exit inside of any
function but main; use proper error handling like Option or
Result. I usually start with expect on these types which will
panic the program, then thread the errors through once the
general structure is in place.
Use slice::get instead of checking the length manually.
Creating a fetch_many method allows better naming,
flexibility, and a more efficient implementation.
Create more types! For example, create a RegisterFile and
Arguments to offload some of the decision making and
implementation details. These types provide naming (which is
self-documentation), extra seams for types and assertions, as well
as places to put "helper" methods (e.g. pack_bytes). They might
show places where you might be misusing sizes (e.g. indexing the
register file beyond 8-bit makes no sense).

use std::ops::{Index, IndexMut};
use std::cmp;
use std::error::Error;

enum Opcode {
    Exit = 0x00,
    Load = 0x01,
    Add  = 0x02,
}

impl Opcode {
    fn from_u8(byte: u8) -> Result<Opcode, Box<Error + Send + Sync>> {
        use Opcode::*;

        let opc = match byte {
            x if x == Exit as u8 => Exit,
            x if x == Load as u8 => Load,
            x if x == Add as u8 => Add,
            _ => return Err(From::from("invalid instruction code")),
        };

        Ok(opc)
    }
}

#[derive(Debug)]
struct RegisterFile {
    registers: [u64; 8],
}

// TODO: Consider catching and reporting access to registers outside
// of the register file. The indexing implementation panics the
// program.

impl Index<u8> for RegisterFile {
    type Output = u64;

    fn index(&self, idx: u8) -> &u64 {
        &self.registers[idx as usize]
    }
}

impl IndexMut<u8> for RegisterFile {
    fn index_mut(&mut self, idx: u8) -> &mut u64 {
        &mut self.registers[idx as usize]
    }
}

impl Default for RegisterFile {
    fn default() -> RegisterFile {
        RegisterFile { registers: Default::default() }
    }
}

#[derive(Copy, Clone)]
struct Program<'a> {
    code: &'a [u8],
    pos: usize
}

impl<'a> Program<'a> {
    pub fn new(code: &'a [u8]) -> Program<'a> {
        Program { code: code, pos: 0 }
    }

    fn fetch(&mut self) -> Result<u8, Box<Error + Send + Sync>> {
        let v = try!(self.code.get(self.pos).ok_or("No more code to read"));
        self.pos += 1;
        Ok(*v)
    }

    fn fetch_many(&mut self, n: usize) -> Result<Vec<u8>, Box<Error + Send + Sync>> {
        if self.code.len() < self.pos + n {
            return Err(From::from("No more code to read"));
        }
        let v = &self.code[self.pos..(self.pos + n)];
        self.pos += n;
        Ok(v.to_owned())
    }
}

struct Arguments {
    values: Vec<u8>,
}

impl Arguments {
    // TODO: Did I pick `high` and `low` right?
    pub fn high_u32_8(&self) -> u8 {
        self.values[3]
    }

    pub fn low_u32_8(&self) -> u8 {
        self.values[7]
    }

    pub fn u64(&self) -> u64 {
        Arguments::pack_bytes(&self.values)
    }

    fn pack_bytes(bytes: &[u8]) -> u64 {
        let len = cmp::min(bytes.len(), 8);
        bytes[..len].iter().fold(0, |acc, &byte| acc << 8 | (byte as u64))
    }
}

fn eval<F>(mut program: Program, mut registers: RegisterFile, each_iteration: F) -> Result<(), Box<Error + Send + Sync>>
    where F: Fn(&RegisterFile),
{
    loop {
        let operator = try!(program.fetch());
        let operator = try!(Opcode::from_u8(operator));
        let destination = try!(program.fetch());
        let arguments = try!(program.fetch_many(8));
        let arguments = Arguments { values: arguments };

        match operator {
            Opcode::Exit => return Ok(()),
            Opcode::Load => {
                registers[destination] = arguments.u64();
            }
            Opcode::Add => {
                registers[destination] = registers[arguments.high_u32_8()]
                    + registers[arguments.low_u32_8()];
            }
        }

        each_iteration(&registers);
    }
}

fn main() {
    let registers = Default::default();
    let code = vec![
        Opcode::Load as u8,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64,
        Opcode::Load as u8,
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8,
        Opcode::Add as u8,
            0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
        Opcode::Exit as u8,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    ];
    let program = Program::new(&code);

    if let Err(e) = eval(program, registers, |registers| println!("{:?}", registers)) {
        println!("Evaluation failed: {}", e);
        // TODO: Could add process::exit with an error code here
    }
}


I have a Java Class that I suspect can use a ReflectionUtil here because there are too many switch/cases, any advice?

The only problem I see with this code is, that for extending the enum, you need to change two methods in the code, which spreads out changes instead of keeping them local to a single place.
You could however harness the power of the java enum (which can have fields and methods) to make the changes locally.
Something along the lines of:
enum ParserClassType {
    SPECIFIC_XML(SpecificXMLParser.FILE_TYPE_OUTPUT) {
        public ParserClass createParser(InputStream is, etc, ...) {
            return new SpecificXMLParser(...);
        }
    },
    XML(GenericXMLParser.FILE_TYPE_OUTPUT) {
        public ParserClass createParser(InputStream is, etc, ...) {
            return new GenericXMLParser(...);
        }
    },
    ...

    private final String fileExtension;

    private ParserClassType(String fileExtension) {
        this.fileExtension = fileExtension;
    }

    public String getFileExtension() {
        return fileExtension;
    }

    public abstract ParserClass createParser(InputStream is, etc, ...);
}

public static String getFileExtension(...) {
    ParserClassType parserClassType = ...
    return parserClassType.getFileExtension();
}

public ParserClass getParserClass(...) {
    ParserClassType parserClassType =  ...
    return parserClassType.createParser(...);
}

As you see, when you add a new type, you simply have to extend the enum. All the client code stays unmodified.
Apart from that, please look up the java naming conventions. Variables should start with lower case letters and definitely not shadow their class names.
Furthermore, getParserClass() / ParserClass is badly named, as it clearly involves around a concrete parser / parserInstance, not around a class.


Usability

The Binary class has two kinds of usages:

Create an instance from a binary string, to get the decimal value later
A utility class with a utility method to convert a binary string to decimal value

Having two usages is confusing.
In general, an API that lets you accomplish the same thing in multiple ways raises questions like "which way is better",
which is not a very productive discussion.
Just provide one way, and there will be less questions asked, less confusion.

In this particular example,
it might make sense to move the converter logic to a BinaryUtils utility class.
If you still want a class that contains a binary string and decimal value,
then you can keep the Binary class for that purpose.

Pre-calculate when it makes sense

Getters should not calculation. When I see a method named "getSomething",
I assume it simply returns the value of a field (or sometimes a defensive copy).
But in this class, it calculates the decimal value.
Every time it's called, again and again.
Since the method always returns the same value,
it would be better to calculate that value once,
at construction time.
And that way, the getter will naturally really return just a simple field value.

Avoid negation in names

Negation as the "Not" in charIsNotBinary may lead to double-negation in code like if (!charIsNotBinary(...)) { ... }, which can be confusing.
It's better to rewrite as isBinary, and use ! where you need to negate it.

Using < and > operators is also slightly odd, feels kind of overkill for a range of size 2.
This way seems simpler and more natural:

  private static boolean isBinary(char ch) {
    return ch == '0' || ch == '1';
  }


Store the first k elements in a temporary array temp[0..k-1]

You are not doing that

  Find the smallest element in temp[], let the smallest element be min

You are not doing that

  For each element x in arr[k] to arr[n-1]...

You are starting on 0 because you skipped step 1

Nothing in there about a binary search
Not less operations the with the shifts

This

if (testArray[i] <= result[0])
{
    continue;
}
else
{

Can be

if (testArray[i] > result[0])
{

Other than that looks good

Just following what I think are the instructions
It is \$\mathcal{O}(n \times k)\$ as the first k elements are not free

private int[] FindKBiggestNumbersM(int[] testArray, int k)
{
    int[] result = new int[k];
    int indexMin = 0;
    result[indexMin] = testArray[0];
    int min = result[indexMin];

    for (int i = 1; i < testArray.Length; i++)
    {
        if(i < k)
        {
            result[i] = testArray[i];
            if (result[i] < min)
            {
                min = result[i];
                indexMin = i;
            }
        }
        else if (testArray[i] > min)
        {
            min = testArray[i];
            result[indexMin] = min;
            for (int r = 0; r < k; r++)
            {
                if (result[r] < min)
                {
                    min = result[r];
                    indexMin = r;
                }
            }
        }
    }
    return result;
}


A heart.lisp I wrote with my 6 year old daughter

That's a great start! Looks like a lot fun.

I would do only a few things slightly different. Some of them a real improvements and some are style preferences of an old Lisper... ;-)

First function: PRINT-LINE

(defun print-line (&rest args)
  (loop
     :for type :in args :by #'cddr
     :for num :in (cdr args) :by #'cddr
     :do (loop :repeat num
            :do (princ (ecase type
                         (:s " ")
                         (:h "❤")))))
  (format t "~%"))

There are two real improvements:

don't use a &rest arg, pass the list directly
the outer LOOP can be written slightly simpler with destructuring

New version:

(defun print-line (line)
  (loop for (type num) on line by #'cddr
        do (loop repeat num
                 do (write-char (ecase type
                                  (:s #\space)
                                  (:h #\❤)))))
  (terpri))

The second function: PRINT-LINES

(defun print-lines (data)
  ;; ensure there is a new line
  (format t "~&")

  (dolist (line data)
    (apply #'print-line line)))

There is one real improvement:

don't use apply, just pass the list directly

New version:

(defun print-lines (data)
  (terpri)
  (dolist (line data)
    (print-line line)))

The data variable

(defvar *data*
  '((:s 8 :h 8 :s 8 :h 8)
    ...
    (:s 19 :h 2)))

It helps to add a documentation string, or to give it a useful name.

(defvar *heart*
  '((:s 8 :h 8 :s 8 :h 8)
    ...
    (:s 19 :h 2)))

or

(defvar *data*
  '((:s 8 :h 8 :s 8 :h 8)
    ...
    (:s 19 :h 2))
  "The description of a heart.")


The main M4 file

  Should I pull the setup script into this macros or leave it separate?

I think it's good you separated.
For the same reason that it's good to decompose a large function doing many things to smaller functions.

If it doesn't make sense to ever run the setup script independently,
then an alternative is to put it in a function,
if that's possible in M4.

This may be a matter of taste,
I avoid pushd and popd in shell scripts for fear that I might forget to do popd, or that later I delete one of them by mistake.
An alternative is a (...) subshell, for example:

    (
        cd build/third
        ./setup "$CXX" || AC_MSG_ERROR([Failed to set up the test utilities], [1])
    )

The subshell has its own environment, its own $PWD,
so directory changes will not affect the encapsulating shell process.
Forgetting one of the parens in (...) is impossible as that would be a blatant syntax error.

The setup script

It would be better to give the setup script a .sh extension to indicate it's a shell script.

Some variables containing filenames are not carefully quoted, for example:

THORSANVIL_ROOT=$(dirname ${ROOT})

This will break down if the path contains spaces.

Maybe on your computer you have the good sense to avoid spaces in paths of your dev stuff,
but others cloning your project might not,
and annoy you with dumb questions when something doesn't work.
It's better to quote such variables.
Paste your script on shellcheck.net and review all similar cases.

if [[ -e ${THORSANVIL_ROOT}/lib/libgtest.a ]]; then
    exit 0
fi

Instead of -e, which gives true for directories too,
I'd use -f that more explicitly requires regular files.
(It will match symlinks pointing to regular files too.)
Sure, it's unlikely that a .a file would be a directory,
but if that ever happens, it will really suck.

GTEST_ARCHIEVE=`ls gtest-*.zip 2>/dev/null | tail -n 1`
if [[ ${GTEST_ARCHIEVE} == "" ]]; then
    echo "Retrieving: gtest-1.7.0"
    wget http://googletest.googlecode.com/files/gtest-1.7.0.zip
    GTEST_ARCHIEVE=`ls gtest-*.zip 2>/dev/null | tail -n 1`
fi

Always prefer the modern $(...) subshells instead of the old and troublesome ``...`` style.

Also, since you're duplicating that ls ... command,
it would be better to put that in a helper function.
Even though it's just one line,
it's not exactly trivial,
and copy-pasted code very often comes back to haunt you.

Btw I guess you meant to name that variable GTEST_ARCHIVE instead of GTEST_ARCHIEVE.

As in the other script, I would wrap the pushd/popd in (...) instead.


Your code looks good and was easy to understand, at least for me :)

A few things you can do to improve it:

Python String Format and Upper

Consider using python format() method, instead of:

print("You have " + str(p_health) + ' hit points.')

try:

print('You have {} hit points.'.format(p_health))

And when checking if a char equals to a given char, you don't have to check both cases you can just use Python upper/lower function so instead of:

if again == 'y' or again == 'Y':

try:

if again.lower() == 'y':
    do stuff

Better Practice

The status() function could be improved by assigning a value to result and returning it, this is just better practice:

def status():
    res = ''
    if g_health == 5:
        res = "\nA menacing goblin stands before you..."
    elif g_health >= 3:
        res = "\nThe goblin is looking a little tired, and is bleeding..."
    elif g_health >= 1:
        res = "\nThe goblin is bleeding horribly and looks enraged..."
    return res

Python Class

Perhaps this code will be better in a GoblinGame class, this class will have properties such as goblin_health, player_health and goblin_alive that can be assigned when initializing the class instance, and a run() method to play a round of the game, I've wrote a quick sample class you can follow along from there:

class GoblinGame:
    def __init__(self):
        self.player_health = 5
        self.goblin_health = 5

    def goblin_alive(self):
        return self.goblin_health > 0

    @property
    def status(self):
        res = ''
        if self.goblin_health == 5:
            res = "\nA menacing goblin stands before you..."
        elif self.goblin_health >= 3:
            res = "\nThe goblin is looking a little tired, and is bleeding..."
        elif self.goblin_health >= 1:
            res = "\nThe goblin is bleeding horribly and looks enraged..."
        return res

    def run(self):
        while self.goblin_alive:
         # write the game logic...

Good Luck!


Looping through rows of data sets in files

In your code, std_d is not defined.  Presumably it is some threshold value, since it is used in a comparison of absolute differences.

First, reformat your code so that I can better determine what it is supposed to do:

for(i in seq_along(z[,1])) {
    if(is.na(coredata(z[i,1]))) next
    ctr <- i
    while(ctr < length(z[,1])) {
        if((abs(coredata(z[i,1])-coredata(z[ctr+1,1]))) > std_d) {
            z[ctr+1,1] <- NA
            ctr <- ctr + 1
        } else {
            break
        }
    }
}

Then determine what the algorithm is that you are trying to do:

Looping over each element of the first column of z, skipping any missing values, compare that value to every other value to the end of column. If the current value and some subsequent value differ by more than some threshold (in absolute difference), set that subsequent value to NA.

R is a vectorized language, so explicit for loops are often not the most efficient way to perform an operation.

Let's vectorize that inner while loop.

for(i in seq_along(z[,1])) {
    if(is.na(coredata(z[i,1]))) next
    ctr <- (i+1):length(z[,1])
    z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d),1] <- NA
}

I make ctr a vector of all the indexes higher than i, and use that most functions are vectorized.  For example, with i equal to 1, (and picking std_d equal to 2) working the statements from inside out:

> ctr <- (i+1):length(z[,1])
> ctr
[1] 6 5
> i
[1] 5
> i <- 1
> ctr <- (i+1):length(z[,1])
> ctr
[1] 2 3 4 5
> coredata(z[i,1]) - coredata(z[ctr,1])
 4  3  2  1
-3  3 -1  0
> abs(coredata(z[i,1]) - coredata(z[ctr,1]))
4 3 2 1
3 3 1 0
> abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d
    4     3     2     1
 TRUE  TRUE FALSE FALSE
> which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d)
4 3
1 2
> i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d)
4 3
2 3
> z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d),1]
2012-06-03 11:45:11 2012-06-03 12:00:08
               3191                3185
> z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) > std_d),1] <- NA
> z
                    mesured_distance IFC_Code from_sensor_to_river_bottom
2012-06-03 11:30:15             3188     1005                        3500
2012-06-03 11:45:11               NA     1005                        3500
2012-06-03 12:00:08               NA     1005                        3500
2012-06-03 12:15:16             3189     1005                        3500
2012-06-03 12:30:07             3188     1005                        3500

This change alone would probably speed up your code a lot. You could aslo pull the computation of length(z[,1]) outside the loop, but that will be a much smaller improvement.

The sample of data you gave is too small to do any reasonable benchmarking on.


First of all, your code doesn't work properly: there are 143 happy numbers between 1 and 1000 but your code (after fixing a NullPointerException) will count 614. The logic is indeed too complicated and you can simplify this a lot.

First of all, let's consider the method that calculates the sum of squares of each digits. Instead of digitSquareSumCalculator, a more descriptive name would simply be sumOfSquaredDigits.

public static int getLastDigit(final long number) {
    return Math.toIntExact(number % 10);
}

Why use Math.toIntExact? No overflow can happen here since we're taking the modulo 10 so the result is between 0 and 9. If you're using just to cast the result to an int, it would be clearer to just cast.

public static long digitSquareSumCalculator(final long number) {
    int remainder = getLastDigit(number);
    long quotient = number / 10;
    long digitSum = remainder * remainder;
    while (quotient > 0) {
        remainder = getLastDigit(quotient);
        quotient = quotient / 10;
        digitSum = remainder * remainder;
   }
   return digitSum;
}

This contains duplicated logic: you can see that the first part of the method is the same as what goes in the while loop. You can fix that by not using a temporary variable quotient but reusing the variable number (and thereby dropping the final). The number given to the method won't be changed.

public static long sumOfSquaredDigits(long number) {
    long digitSum = 0;
    while (number > 0) {
        int remainder = (int) (number % 10);
        number /= 10;
        digitSum += remainder * remainder;
    }
    return digitSum;
}

This code shows that actually, you don't need the getLastDigit method.

The main part of the code is indeed clunky. You're missing an obvious method here: you want to determine if a number is happy or not, therefore it would make sense to have a method isHappy(number) that determines if the given number is happy or not.

The code of this method must do the following:

Calculates the sum of squared digits of the number
If the number obtained has already been obtained, return false; else continue. If we hit 1, return true.

We can store the visited numbers in a Set (to have constant-time look-up):

public static boolean isHappy(long number) {
    Set<Long> numbers = new HashSet<>();
    while (number > 1 && !numbers.contains(number)) {
        numbers.add(number);
        number = sumOfSquaredDigits(number);
    }
    return number == 1;
}

With such a method, you can then have a very simple for loop:

public static long countHappyNumbersInRange(final long startInclusive, final long endInclusive) {
    long count = 0;
    for (long index = startInclusive; index <= endInclusive; index++) {
        if (isHappy(index)) {
            count++;
        }
    }
    return count;
}

Now, we can make a simple but big improvement in terms of performance (just like you were trying to in your code). When we are determining if a given number is happy or not, we're also determining whether all the visited numbers are happy or not. So we don't need to check every number between the bounds and we can store a cache of happy or not happy numbers. So let's introduce a cache

private static final Map<Long, Boolean> CACHE = new HashMap<>();

that, for a given number, will hold whether it is a happy number of not. Then, when the method isHappy is running, we can stop early if we encounter a number we've already seen before. If that's the case, then we put in the map all the numbers encountered with the happyness of the starting number.

public static boolean isHappy(long number) {
    if (CACHE.containsKey(number)) {
        return CACHE.get(number);
    }
    Set<Long> numbers = new HashSet<>();
    while (number > 1 && !numbers.contains(number)) {
        numbers.add(number);
        number = sumOfSquaredDigits(number);
        if (CACHE.containsKey(number)) {
            boolean result = CACHE.get(number);
            for (long n : numbers) {
                CACHE.put(n, result);
            }
            return result;
        }
    }
    boolean result = number == 1;
    for (long n : numbers) {
        CACHE.put(n, result);
    }
    return result;
}

I ran this code to determine all the happy numbers between 1 and 1 million and it gave the result instantly.


Logging the name of recipes using ingredients

I would suggest two improvements:

Use a Map to have a faster lookup in your ingredients. find needs to iterate through an array every time, while if you create a Map for it, you can get each result in constant time
Use the map array method (unrelated to the above mentioned Map object) in combination with join instead of reduce.

Here is how that would look:

const INGREDIENTS = [{id: 'chocolate',name: 'Chocolate Ice Cream',type: 'ice_cream',contains: ['cream', 'milk_chocolate']},{id: 'm_and_ms',name: 'M&Ms',type: 'topping',contains: ['milk_chocolate']},{id: 'lemon',name: 'Lemon Ice Cream',type: 'ice_cream',contains: ['cream', 'lemon']},{id: 'peanuts',name: 'Peanuts',type: 'topping',contains: ['peanuts']},{id: 'vanilla',name: 'Vanilla Ice Cream',type: 'ice_cream',contains: ['cream', 'vanilla_extract']},{id: 'strawberry',name: 'Strawberry Ice Cream',type: 'ice_cream',contains: ['cream', 'strawberries']},{id: 'caramel',name: 'Caramel Sauce',type: 'topping',contains: ['caramel']},{id: 'raspberry',name: 'Raspberry Sauce',type: 'topping',contains: ['raspberries']}];
const RECIPES = [{id: 'the_basic',name: 'The Basic',rules: ['chocolate', 'vanilla']},{id: 'chocolate_lovers',name: 'Chocolate Lovers',rules: ['chocolate', 'm_and_ms', 'caramel']},{id: 'tooty_fruity',name: 'Tooty Fruity',rules: ['strawberry', 'raspberry', 'm_and_ms']}];

const keyedIngredients = new Map(INGREDIENTS.map(o => [o.id, o.name]));
const printRecipe = () => {
  RECIPES.forEach(recipe => {
    let listOfItems = recipe.rules.map(
        ingredient => keyedIngredients.get(ingredient)
    ).join(" and ");
    console.log(`${recipe.name} - ${listOfItems}`);
  });
};

printRecipe();


About thread safety: it is not thread safe. There is nothing that prevents member-functions such as  TFixedAllocator::allocate,  TFixedAllocator::new_pool and others to be executed by multiple threads at the same time.  Inside these functions several variables are modified. Modifying them from multiple threads without synchronization is an undefined behavior according to the C++ standard.

How to fix it? The easiest way to do it is to use one std::mutex for the allocate and deallocate member-functions of the TFixedAllocator class(acquiring it in the very beginning of the function and releasing it in the very end). It is convenient to use an std::lock_guard for this purpose. Something like this:

template <size_t ChunkSize>
class TFixedAllocator {
    ...

    std::mutex allocator_mutex;

public:
    ...

    void* allocate() {
        std::lock_guard<std::mutex> allocator_lock_guard(allocator_mutex);
        if (!free) {
            new_pool();
        }
        TNode* result = free; // allocate the topmost element (saved in free)
        free = free->next; // and pop it from the stack of free chunks
        return static_cast<void*>(result);
    }

    void deallocate(void* elem) {
        std::lock_guard<std::mutex> allocator_lock_guard(allocator_mutex);
        TNode* node = static_cast<TNode*>(elem);

        // add to the stack of chunks
        node->next = free;
        free = node;
    }
};

Functions and variables naming: it is conventional to name functions with a verb(to describe an action). I would use get_instance instead of instance and create_new_pool instead of new_pool, for example.
You TFixedAllocator class violates the single responsibility principle. Despite managing memory allocation(which is its main responsibility) it also implicitly implements some data structure(a stack?(I mean things related to the union TNode, the free pointer and so on)). It makes the code rather hard to follow: those operations with free and next pointers are not easy to understand(it is not clear why they are performed in the first place). There are two ways to fix it:

Create a separate class that implements this data structure.
Use a standard container. If what you need is a stack, std::stack is a good option(again, I'm not completely sure if it is feasible because I do not fully understand how this data structure is used in your code).

Writing useless comments is definitely a bad practice. For instance, union TNode { // union doesn't make much sense: it is absolutely clear that it is a union without any comments. I'd recommend simply deleting comments like this one. Comments inside a function that tell what a block of code does, like here:

void deallocate(void* elem) {
    TNode* node = static_cast<TNode*>(elem);

    // add to the stack of chunks
    node->next = free;
    free = node;
}

usually indicate that this block of code should have been a separate function(in this case, as I have mentioned before, there should probably be another class that implements this data structure). In general, you should try to write self-documenting code.
Spacing and indentation: separating different functions with an empty line makes the code more readable.


Determining if the kangaroos will land in the same position

Closed form solution

A better approach is to calculate the intercept point directly and then check whether or not it is an integer. The time of intercept is:

$$t = \frac{x_2 - x_1}{v_1 - v_2}$$

where both numerator and denominator are integers, but their ratio may not. We can also handle all special cases from the ratio.

bool kangaroos_meet(int x1, int v1, int x2, int v2) {
    int numerator = x2 - x1;
    int denominator = v1 - v2;
    if (denominator == 0)                // same velocity
    {
        return numerator == 0;           // they meet always or never
    }
    if (numerator % denominator != 0)    // intercept point not an integer
    {
        return false;
    }
    int t = numerator / denominator;     // calculate intercept point
    return t >= 0;                       // intercept point lies in the past
}


Plague Inc. in Python - Extremely Early Stage

Some thoughts:

As the game goes on, you’ll need to record more information about the countries. Whether they’re doing medical research, border closures, infection/mortality rates, etc. Rather than storing all this information in a list of dictionaries, I’d suggest creating objects for each country. Here’s a simple example:

class Country(object):
    def __init__(self, name, population):
        self.name = name
        self.population = population

china = Country("China", 1363560000)

Also follow martijnn2008’s advice, and load the countries from an external file (probably a CSV). Keeping the data separate from the code is generally good practice. You’d probably be better off having a small dataset in the program to start with, as you build the basic logic, then start using the full data set later.

As unholysampler suggests, use an int for the population; this will make your life much easier later when chunks of the population start dying. You can always define a function that does nice comma-printing on your population data later.
Have different functions for parts of the game. For example, a start_game() function which just includes the code for setting up a new game, then another function news_bulletin() which prints a random news bulletin.

This will make it easier to reuse this code later – for example, if the user gets to the end of the game and you want to ask "Play again?", you can just redirect them to start_game() rather than jumping through hoops.
Rather than expecting the user to enter a name that’s formatted exactly as it’s stored in your data, you could:

Do something to clean up messy input. For example, right now, "china" is an invalid input, but any reasonable person can see what they meant. Perhaps do something like

if start_country.lower() in list_of_countries:
     # more code here

And weirdness happens if I choose a country name which isn't on your list. You could perhaps just ask again and again until you get an answer, or just pick one at random for me. I just want to get on with the game!
Just offer them a choice from a numbered list. Here’s a very crude mockup of how that might work:

Which country would you like to choose?
1 China
2 India
3 United States
Type the corresponding number: # wait for input
3
You have chosen "United States"

Magic numbers as arguments to ljust() throughout your code. Icky and fragile. Pull them out and make them variables, or better try to compute the necessary values on the fly.

ETA: The problem arises because you’re assuming that the window is 55 characters wide (for example, the print '-' * 55 line). You should pull this out into a window_width variable, so you don't have problems later on (and if necessary, can adapt it for wider or narrower windows).

What if, later, you want to add the Independent Former Republic of New South Nebelsbad? Stuff like that might cause you problems if you’re rigid about the width.
In your import statements, I would write

from datetime import datetime

Cuts out datetime.datetime statements, which just look weird. Also note that your MM-DD-YY may confuse players for whom that isn’t their default date system. How about

>>> current_date = datetime.datetime.strftime(datetime.date.today(), "%d %B, %Y")
>>> print current_date
29 April, 2014

That looks much more natural, and is unambiguous.


Method to act on parameter or from iterable if not parameters are passed

Not going into the question as to whether or not this is a good idea, I can see very little wrong with the solution.

One thing I would very much like to suggest is the following.

Instead of

map(func, search(query))

please write

for result in search(query):
    func(result)

There are actually some differences:

In Python 3, map builds a iterable, and func(result) will only be called if the iterable is looped over. In this case, this is most definitely not what you want!
In Python 2, map builds a list, and thus evaluates everything. Better, but an intermediate list is now going to be build and thrown away.

In general I would recommend only using map for functions that are side-effect free.

Another thing I'd like to remark is where you build the namedtuple. You do it inside the function, building a new Task class for every task you add. Please move that code outside of the function task.


Sort 3 numbers in Common Lisp with the minimum number of operations

It does seem to be correct. As for elegance, I believe it can be expressed without nested conditionals and I would consider that more elegant, even if it takes the average number of comparisons from 2.5 to 3. This code does 3 comparisons (always) and up to six writes. Your code does 2 or 3 comparisons and up to seven writes (ignoring temps, that would take the code below to "up to nine" and your code to "up to ten").

On the balance, your code probably has a slight edge in performance, so if this would be a frequently-called function, I would consider using order over order3.

That is:

(defun order3 (min mid max)
  (when (< max min)
     (rotatef max min))
  (when (< mid min)
     (rotatef mid min))
  (when (< max mid)
     (rotatef max mid))
  (list min mid max))


Class for formatting topics using BBCodes

First of all you make 1 big fault by saying that your classes inside MarkUp are private.
They aren't, they are package private, more info on site of oracle.

Then, let's start with the enum.
Your final String code is also package private. => change them to private.
Your getter for the code is also a little off the normalisation, let's try to call it getCode.

Final result could be :

private enum BBcode {

    BOLD("B"),
    ITALIC("I"),
    IMAGE("IMG"),
    UNDERLINE("U"),
    VIDEO("VIDEO");
    /* many others... */

    private final String code;

    private BBcode(String code) {
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }
}

The class Syntax you could add constants in stead of repeating your chars.
Then also, you have repeating stuff what you can put together.
The naming in, out are for me to broad.

Example of how I should make the class :

private class Syntax {

    private static final char START_OPENING_TAG = '[';
    private static final String START_CLOSING_TAG = "[/";
    private static final char CLOSING_TAG = ']';
    private static final char EQUAL_SIGN = '=';

    public String getOpeningTag(BBcode bbcode) {
        return addStartOpeningTag( bbcode.code()); // will return "[BOLD]" for example.
    }

    public String getOpeningTag(BBcode bbcode, String value) {
        return addStartOpeningTag(bbcode.code() + EQUAL_SIGN + value); // will return "[COLOR=#333]" for example.
    }

    public String getClosingTag(BBcode bbcode) {
        return addStartClosingTag( bbcode.code()); // will return "[/BOLD]" for example.
    }

    private String addStartClosingTag(String value) {
        return START_CLOSING_TAG + value + CLOSING_TAG;
    }

    private String addStartOpeningTag(String value) {
        return START_OPENING_TAG + value + CLOSING_TAG;
    }
}

As you can see now, I can easily refactor the code.
Let's say you class grows and we need to change the ] to >
For me it's one little change and it's completly done.
Your old class, you have already to change it 3 places, possible fault's .(forgetting one to change) waiting to happen when your class grows.


Should I use unnamed or named functions?

So this is redundant.

var openIPP = function openIPP() {
    $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
}

Because both of these functions are the same.

var openIPP = function() {
    $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
}
function openIPP() {
    $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
}

This is the easiest for me to read.

$IPPWrapper.hover(
    function() {
        $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
    },
    function() {
        $IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
    }
);

But if you want more information in case a bug is thrown then use named functions like so.

$IPPWrapper.hover(
    function openIPP() {
        $IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
    },
    function closeIPP() {
        $IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
    }
);


Regex to parse URLs for their correctness according to RFC 3986

Holy regex Batman!

Without testing, you should be able to replace all occurrences of:

[0-9] with \d
[A-Za-z0-9] with [\w^_]
[A-Fa-f0-9] with \p{XDigit}
[A-Za-z0-9-._~] with [\w.~-]

and so forth. See documentation for Pattern.

As for your capturing groups I'm quite sure you can do some clever back referencing there but I will save my sanity and not try to parse the regexp. :)


Two methods to prompt the user to enter the width and length of a rectangle

Breaking methods down into less than five lines is generally a sign that you have gone a bit too far (But not always!). This Software Engineering post is a good overview.

Instead of breaking your methods into userInputWidth and userInputHeight, I would recommend creating a helper method named getPositiveInput that accepts a prompt string and using that instead.

For example:

private double getPositiveInput(String prompt) {
    Scanner reader = new Scanner(System.in);
    double result;
    do {
        System.out.println(prompt);
        result = reader.nextDouble();
        if (result <= 0) {
            System.out.println("Enter a number greater than zero.");
        }
    } while (result <= 0)
    return result;
}

This makes it possible to reduce the duplication of your code without breaking your methods down so far that you have to have one for every property on your class.

The trick is what the definition of "one task" is. Deciding what each method should do to keep the code modular is made much easier by experience. I've found the following guidelines help.

Describe the method out loud, if you say "and" or "then" more than once, the method is probably doing too much and should be split up.
If you say the same thing for more than one method, extract the code that does that thing into it's own method.
If you catch yourself copy/pasting code stop and put it in a method.

Here's an example:

Given the following code (combined your methods to get what I presume was the original method), here's how I would describe the method.

private void userInputDimensions() {
    Scanner reader = new Scanner(System.in);
    double loopCondition = 0;
    while (loopCondition <= 0) {
        System.out.println("Please enter the width of the rectangle ");
        double nextDouble = reader.nextDouble();
        loopCondition = nextDouble;
        if (nextDouble <= 0) {
            System.out.println("Enter a number greater than zero.");
        } else {
            this.rectangleWidth = nextDouble;
            break;
        }
    }

    loopCondition = 0;
    while (loopCondition <= 0) {
        System.out.println("Please enter the length of the rectangle");
        double nextDouble = reader.nextDouble();
        loopCondition = nextDouble;
        if (nextDouble <= 0) {
            System.out.println("Enter a number greater than zero.");
        } else {
            this.rectangleLength = nextDouble;
            break;
        }
    }
}

Prompt the user for the width of the rectangle until they enter a number greater than zero
Set the rectangleWidth to the number
Prompt the user for the length of the rectangle until they enter a number greater than zero
Set the rectangleLength to the number

Notice that the duplicate "code" here is the prompt and validation input. By contrast, consider the following code using the getPositiveInput method.

private void userInputDimensions() {
    this.rectangleWidth = this.getPositiveInput("Please enter the width of the rectangle");
    this.rectangleLength = this.getPositiveInput("Please enter the length of the rectangle");
}

This method can be described by "set the width and length of the rectangle to the user input" and does not need to be broken down further.


It can be done in many ways based on your use case & code structure, but i feel this can be optimal way of structuring.

api/services/index.js

import axios from 'axios';
export {default as MATCHES_API} from "./services/matches.js";

export const CONFIG_API = axios.create({
  baseURL: 'https://1eb19101-0790-406f-90e0-ee35a2ff2d1f.mock.pstmn.io',
  timeout: 2000
});

api/services/matches.js

import CONFIG_API from "api/services";

const ERROR_MSG = "<generic message>";

export const matches = () => {
  return CONFIG_API.get("/matches").then(res => {
  // do some operations on data - if required
    return {success: true, data: res.payload};
  }).catch(err => {
    return {success: false, message: ERROR_MSG || err.message};
  });
};

actions/matchesAction.js

import {FETCH_MATCHES} from './actionTypes';
import {MATCHES_API} from "/api/services";

export const fetchMatches = () => dispatch => {
  matches.then((response) =>
    const {success} = response;
    if (success) {
      dispatch({ type: FETCH_MATCHES, payload});
    } else {
     dispatch({ type: FETCH_MATCHES_FAILED}); /* or show notification */ .
    }
  );
};

Let me know if this works out.


Add the refresh-rates map to #refresh-buttons element ( use .data() function ), optimize amount of $() calls:

$(document).ready(function() {
    var refresh_btns$;

    // you can store id map where ever you prefer to
    // I've figured it would be good to keep them with
    // the element they are related to
    ( refresh_btns$ = $("#refresh-buttons") )
    .data(
        "refreshRates",
        {
            "refresh-off"    :50000000,
            "refresh-5-sec"  :5000,
            "refresh-30-sec" :30000,
            "refresh-60-sec" :60000
        }
    )
    .on("click", "button", function () {
        var
        interval = refresh_btns$.data("refreshRates")[ this.id ] || 0;
        if (
            interval !== 0
        ) {
            // yeah m_x is right about .toggleClass()
            // it producess weird behaviour
            // this shold to the job
            $( this )
            .addClass("pressed-button")
            .siblings()
            .removeClass("pressed-button");

            clearInterval(intervalId);
            intervalId =
            setInterval(
                function () {
                    $('#status-tables')
                    .load(
                        '/dashboard/index #status-tables',
                        function () {
                            $("#workstation-table").tablesorter();
                            $("#report-table1, #report-table2")
                            .tablesorter( { sortList : [ [ 1, 0 ] ] } );
                        }
                    );
                },
                interval
            );
        }
    });
});


Python script to touch files of a particular pattern in all folders of a given name

For combining (1) and (2) you can reverse the sort by only trying if your are under a test directory

Also this is a great use for a generator / map combo to avoid extra loops

import os
import re

is_xml = re.compile('xml', re.I)
is_test = re.compile('testResults', re.I)

def find_xml_tests(root):
    for current, dirnames, filenames in os.walk(root):
        if is_test.search(current):
            for filename in filter(lambda p: is_xml.search(p),  filenames):
                yield  os.path.normpath(os.path.join(current, filename))

def touch(filename ):
    os.utime(test,(time.time(),time.time()))

map(touch, find_xml_tests('path/to/files'))


Here are the few things I've noticed after a first glance on the program:

import os is not used, you can remove it
() after the class Application can be omitted
keep two blank lines between the imports and the class definition, after the class code and the if __name__ == '__main__' line
variable naming - there are some poor variable names like x or k - consider renaming them to something more descriptive
the following code block can be removed (unless you have it there as a stub for future development):

else:
    return

the class itself feels overloaded - this may be because it does two different not-directly related things at the same time - prompting the user and making budget calculations - since you are going to continue to develop the class - make sure Application is not becoming a God Object
the class and its methods would benefit from having detailed documentation strings

As a side note, take a look at the The Architecture of Open Source Applications project - it is really pure informational gold in terms of designing, thinking and development of your software project.


def ordinal(self, num):
    """
      Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.
    """

Its suspicious that this seems to be a method rather than a free standing function.

    self.num = num

Why are you storing the input here? Given the purpose of this function that seems odd.

    n = int(self.num)

Its doubtful that this is a good idea. What are you converting from? Converting to int should be really be done closer to whether this number came from.

    if 4 <= n <= 20:

You've made this case larger than necessary, many of those would be correct even with out this test, and its not clear what so special about the range 4-20.

      suffix = 'th'
    elif n == 1 or (n % 10) == 1:

You don't need the or. If n == 1, then that the second condition will be true anyways.

      suffix = 'st'
    elif n == 2 or (n % 10) == 2:
      suffix = 'nd'
    elif n == 3 or (n % 10) == 3:
      suffix = 'rd'
    elif n < 100:
      suffix = 'th'

What happens if suffix is >= 100? You'll get an error.

    ord_num = str(n) + suffix
    return ord_num

You don't need to split this across two lines.

Here is my version:

# much code can be improved by using a datastructe.
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
def ordinal(num):
    # I'm checking for 10-20 because those are the digits that
    # don't follow the normal counting scheme.
    if 10 <= num % 100 <= 20:
        suffix = 'th'
    else:
        # the second parameter is a default.
        suffix = SUFFIXES.get(num % 10, 'th')
    return str(num) + suffix


Just some quick tips, I might append some later. You might disagree with me, it's just my vision.

1) AFAIK, Pomodoro has some "classic" times for work and break sessions. It might be good to create them as default ones so the user wouldn't have to enter them manually via command line each time. I suggest using argparse module for that. A really quick and dirty rewriting of your main function:

def main():
    try:
        argparser = argparse.ArgumentParser()

        argparser.add_argument("--workLen", help="the length of a work session", type=int, default=25)
        argparser.add_argument("--sbLen", help="the length of a short break", type=int, default=5)
        argparser.add_argument("--lbLen", help="the length of a long break", type=int, default=30)

        # parse the arguments. They can be accessed in form args.argument
        args = argparser.parse_args()

        clock = Clock(args.workLen, args.sbLen, args.lbLen)
        clock.tickTock()
    except Exception as e:
        print("One or more arguments were invalid.", str(e))
        exit(1)

2) No need to put your work, sBreak and lBreak (and, probably, others too) variables right after class Clock: because that way you're declaring them as static. When you're declaring them in __init__, you basically declare other variables - the variables for this particular instance. And the static ones just remain None and are useless. So you may safely remove them. More info

3) Not sure if it is a common practice, but I would do if workTime == None or sBreakTime == None or lBreakTime == None: as if None in (workTime,sBreakTime,lBreakTime,):. You're testing for the same value anyway (None). I'm not sure if you want this behaviour, but if you want your program to exit if any of these values is 0 as well, you may use if not all((workTime,sBreakTime,lBreakTime,)):, because 0 is treated as false by Python.

I agree with Matthias on exit. As for naming conventions, I prefer being more liberal: do as you find comfortable, especially if it is your personal project. I would also use the PEP8 convention for variables (small_letters_with_underscore), but when it comes to function names, I'm more used to camelCaseStartingWithSmallLetter ;)

UPD1:
4) Add a sleep(0.1) at the end of your while loop in tickTock, because otherwise it uses up too much CPU.


Shoping cart code using a loop to print multiple times

Security

It's unclear where $cat comes from, but if it can possibly be user supplied (eg when it comes from a GET/POST request, or when it comes from the database where it might have been placed by a user), you should use prepared statements to prevent SQL injection.

You should also not be using mysql_* as it's deprecated.

Also, you should always prevent XSS when echoing data that might be user supplied.

Queries in array

Your approach of using an array to handle the 9 queries whose results should be handled the same is ok, but it would be better if you extracted your foreach loop into a separate function and then called that function with the queries (or better yet their result). Doing it that way would increase readability and reusability of your code.

Reduce amount of queries

You could remove the amount of queries you use by using or, which should increase the performance of your code. So instead of asking

SELECT * FROM products WHERE rowno=1 and colno=1 and pageno=1 and productLine like '$cat'";
SELECT * FROM products WHERE rowno=1 and colno=2 and pageno=1 and productLine like '$cat'";

You could just ask

SELECT * FROM products WHERE ((rowno=1 and colno=2 and pageno=1) or (rowno=1 and colno=2 and pageno=1)) and productLine like '$cat'";

This could be further simplified, and the other queries could be added as well, but honestly, I'm not quite sure if it wouldn't be easier to change your database schema. I'm not quite sure how it currently works though.

Misc

all your SQL keywords should be all uppercase to increase readability, not just some.
your comments all just reflect what the code just told me, so you can just remove them.
use proper indentation to increase readability.
select the concrete fields that you want, don't just select *.
move style information in it's own css file.
you forgot the opening and closing table tags.
why use like? it seem you want equality?

With some of these changes applied, your code might loop something like this:

$dbh = new PDO([...]);
printShoppingCart(getByCat($pdo, $cat, "SELECT var1, var2, var3, var4, var5 FROM products WHERE rowno=1 AND colno=1 AND pageno=1 AND productLine=:line"));
[...]

function getByCat($pdo, $ca, $query) {
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(':line', $cat);
    return $stmt->fetch();
}

function printShoppingCart($vars) {
    echo "

        " . htmlspecialchars($vars[0], ENT_QUOTES, 'UTF-8') . "

            RS " . htmlspecialchars($vars[2], ENT_QUOTES, 'UTF-8') . "&nbsp;

        " . htmlspecialchars($vars[3], ENT_QUOTES, 'UTF-8') . "

            " . htmlspecialchars($vars[4], ENT_QUOTES, 'UTF-8') . "

        Details

";
}

There are more improvements that can be made, but I think this would be a good start.


It might have been an ok-ish way of doing things... 15 years ago. This code is astonishingly similar to what one would be writing in vba - minus the Try..End Try block.

If you want to learn the .NET way of doing things, I strongly recommend you remove this from every VB.NET module you're writing:

Imports Microsoft.VisualBasic

Things in that namespace exist to make an easier transition between vb6/vba and vb.net - pretty much everything in it has an actual .net-idiomatic equivalent elsewhere in the framework.

ADODB / ActiveX Data Objects is replaced with ado.net, itself rendered obsolete with linq-to-sql, itself a predecessor of entity-framework. But one step at a time - start with ado.net.
MsgBox is replaced with System.Windows.Forms.MessageBox
vbCrLf should have been vbNewLine, and both are replaced with Environment.NewLine

You're not including the module-scope fields, and yet the code you posted seems to use plenty... but I don't understand why. You're opening a module-scoped connection, fetching data, and then closing it. Why would that object ever need to exist beyond that? You don't need that Boolean bConnection.

ADODB being COM / unmanaged, it doens't implement the IDisposable interface. See this Stack Overflow answer for information about proper cleanup of COM objects... which should motivate you to use managed code ;-)

In short:

  Use Marshal.ReleaseComObject to tidy up COM objects. ADODB is a COM library being used through COM Interop.

Now, what you have here is essentially a Smart UI pattern: the UI runs the show, and controls everything. That's good for learning how things work, fiddling around and prototyping things, but it's also one of the best ways to create a spaghetti mess out of production code.

Your form should only be responsible for one thing: being a user interface. Accessing a database is not the job of a UI, it's that of some data service.

You should create a class to act as your Model, that would expose a property for each value you're fetching from a database record.

Then the View (/form) wouldn't need to know about a database or connections or anything - it would simply display what the Model has in store for it. And then when the user makes changes, you can take the modified Model and pass it to the same data service that provided you with it, to write the modified values into the database.

Read up on the Model-View-Presenter pattern for more details.