Bug

    public void insertEnd(int data){

        Node newNode = new Node(data);
        newNode.setNext(null);

        if(tail != null){
            tail.setNext(newNode);
            newNode.setPrev(tail);
            tail = newNode;
        }
        if(head == null){
            head = newNode;
        }

        length++;
    }

If tail is null at the beginning, it will stay null.  Like with head in insertFront, you should always set tail in insertEnd.  As is, if you call insertEnd and then insertFront, it will point tail at the one inserted at the front.

    public void insertEnd(int data){
        Node newNode = new Node(data, tail, null);

        if (tail != null) {
            tail.setNext(newNode);
        }
        tail = newNode;
        if (head == null) {
            head = newNode;
        }

        length++;
    }

This way, it always sets tail to newNode.

You also never set the previous node if tail is null.  But you explicitly set the next node to null.  This version always sets both.  It would also work to never set the next node and only set the previous node if there is one.  But please don't mix the two notions.  Either set everything or let everything that can default, default.  Either is readable on its own.  Mixed, it gets a bit confusing.

I tend to favor explicitly setting everything.

I also prefer more whitespace, so that keywords like if are separated from things like parenthetical expressions.  The exception being method calls.  That way if I see foo(, I know immediately that foo is a method and not some language construct.

Don't overcomplicate things

    public void removeFront(){

        if(head != null){

            head.getNext().setPrev(null);
            head = head.getNext();

        }else if(head == null){

            System.out.println("List is empty");
            return ;

        }
        length--;
    }

You check both if head is not null and if it is null.  You can check just one.  Further, since you return if it is null, you can do that first.

    public void removeFront() {
        if (head == null) {
            System.out.println("List is empty");
            return;
        }

        head = head.getNext();
        head.setPrev(null);
        length--;
    }

Now we take care of the exceptional case first, and we don't have to gate the rest of the method.  Note that it would usually make more sense to throw an exception here.  A Deque would throw a NoSuchElementException in that situation.

If we switch the order of the statements, we don't have to write head.getNext() twice.

It's no longer confusing that we decrement length outside the if structure but only actually reach that code in one branch.

Bug 2

    public void removeEnd(){

        if(tail != null){

            System.out.println("Tail not null");
            Node temp = tail.getPrev();
            temp.setNext(null);
            tail = temp;

        }else{
            System.out.println("Tail is null");
        }
        length--;
    }

You decrement length even if there's nothing there.

    public void removeEnd() {
        if (tail == null) {
            System.out.println("Tail is null");
            return;
        }

        System.out.println("Tail not null");

        tail = tail.getPrev();
        tail.setNext(null);
        length--;
    }

This should follow the same pattern as removeFront.

Implement an interface

Note that a Deque has a similar API to this.  Consider implementing that interface for compatibility reasons.  Of course, you may find that that is unnecessary for what you need.


Override values for overlapping objects between two scala lists

No need to run find twice, just run it once and store the result in a value of type Option[MyWidget].

You can then use Option#fold and pass in two functions: one to run when the option contains a matching widget, and another when no match was found.

def setOverrideValues(inv : List[MyWidget], cat: List[MyWidget]) : List[MyWidget] = {
  inv.map (k => {
    val wOpt = cat.find(_.sku == k.sku)

    wOpt.fold(ifEmpty = k.copy(name = "No Catalog Label")) {
      w => k.copy(name = w.name, label = w.label)
    }
  })
}

You could also use pattern matching

def setOverrideValues(inv : List[MyWidget], cat: List[MyWidget]) : List[MyWidget] = {
  for (k <- inv)
    yield cat.find(_.sku == k.sku) match {
      case Some(w) => k.copy(name = w.name, label = w.label)
      case _ => k.copy(name = "No Catalog Label")
    }
}

Both options would save you from repeated calls to find or getOrElse


Simple optimisation

Instead of doing color = pixelate_mode(mode)(l) in the nested loop, you could compute modefunc = pixelate_mode(mode) once at the beginning of the function then call modefunc(l) as you need it.

Other optimisation

Instead of checking if x and y are in the range, you could just generate them so that they always are in the range :

l = []
for x in xrange(pixel_width * W, min(width, pixel_width * (W + 1))):
    for y in xrange(pixel_height * H, min(height, pixel_height * (H + 1))):
        l.append(img.getpixel((x, y)))
color = modefunc(l)
for x in xrange(pixel_width * W, min(width, pixel_width * (W + 1))):
    for y in xrange(pixel_height * H, min(height, pixel_height * (H + 1))):
        img.putpixel((x, y), color)

Also, for a more optimised version, you could compute limits only once :

minx, maxx = pixel_width * W, min(width, pixel_width * (W + 1))
miny, maxy = pixel_height * H, min(height, pixel_height * (H + 1))
l = []
for x in xrange(minx, maxx):
    for y in xrange(miny, maxy):
        l.append(img.getpixel((x, y)))
color = modefunc(l)
for x in xrange(minx, maxx):
    for y in xrange(miny, maxy):
        img.putpixel((x, y), color)

List expressions

You could use a list expression to define l. Even better you do not need l as a list at all and could just use a generator expression (Edit: Apparently this does not work for np.array so you have to build the string anyway, may it be with multiple appends or with list comprehension).

minx, maxx = pixel_width * W, min(width, pixel_width * (W + 1))
miny, maxy = pixel_height * H, min(height, pixel_height * (H + 1))
color = modefunc(img.getpixel(x, y)
                for x in xrange(minx, maxx)
                for y in xrange(miny, maxy))
for x in xrange(minx, maxx):
    for y in xrange(miny, maxy):
        img.putpixel((x, y), color)

More optimisations

You could compute the x limits outside the nested loop.

Your while loops are actually for loop in disguise and you could make things more efficient by using for W in range(width/pixel_width) or you could use the step argument of range to use the values you'll actually need : for w in range(0, width, pixel_width): (in both cases, there might be an off-by-one issue but I'll let you check and fix).

Final (untested) version of the code

def pixelate(img, (pixel_width, pixel_height), mode):
    width, height = img.size
    modefunc = pixelate_mode(mode)
    for w in range(0, width, pixel_width):
        minx, maxx = w, min(width, w + pixel_width)
        for h in range(0, height, pixel_height):
            miny, maxy = h, min(height, h + pixel_height)
            color = modefunc(img.getpixel(x, y)
                    for x in xrange(minx, maxx)
                    for y in xrange(miny, maxy))
            for x in xrange(minx, maxx):
                for y in xrange(miny, maxy):
                img.putpixel((x, y), color)
    return img


Your code is overall clean and well written.

You should use list comprehension:

def find_lower_squares(num):
    """Returns a list of even perfect squares less than a given integer"""
    squares = []
    for i in range(num, 3, -1):
        if is_even_square(i): squares.append(i)
    return squares

Should become:

def find_lower_squares(num):
    """Returns a list of even perfect squares less than a given integer"""
    return [i for i in range(num, 3, -1) if is_even_square(i)]

Scientific/mathematical code like this greatly benefits from automated testing, let me show you an example:

import doctest

def find_lower_squares(num):
    """
    Returns a list of even perfect squares less than a given integer

    >>> find_lower_squares(40)
    [36, 16, 4]
    """
    return [i for i in range(num, 3, -1) if is_even_square(i)]

doctest.testmod()

This gives double benefits:

Changes to the code can be made without being worried: if you break something, the error message will show up immediately
Code readability and documentation increase a lot, the reader can see some examples of the function being used and will understand it faster and better.

Avoid None-important assignment

In mid level languages such as C you must declare array first as empty and then fill them. In high level languages such as Python you should avoid such low level behaviour and insert the values in the arrays directly:

def generate_square_spiral(num):
    """
    Generates a square spiral matrix from a given integer

    >>> generate_square_spiral(5)
    [[5, 4], [2, 3]]
    >>> generate_square_spiral(17)
    [[17, 16, 15, 14], [5, 4, 3, 13], [7, 1, 2, 12], [8, 9, 10, 11]]
    """
    edge = int(sqrt(num))
    square_spiral = [nth_row(num, row) for row in range(edge)]
    return square_spiral

Also we could remove the unnecessary assignment:

edge = int(sqrt(num))
return [nth_row(num, row) for row in range(edge)]


indent your code!
don't do this

printf "%${padding}s\n" "$1"

do this

printf "%*s\n" "$padding" "$1"

in this section:

cat $loginfofile >> ~/.bash_profile
test $? -eq 0 && (echo "[OK] Successfully appended '$loginfofile' to '~/.bash_profile'")
test $? -ne 0 && (echo "[ER] Something went wrong appending '$loginfofile' to '~/.bash_profile'")

the 2 test command is testing the exit status of the previous command, not the cat command. It's either testing the exit status of the previous test command or the first echo command. Either way, you get the result you want, but really by luck. You want

if cat $loginfofile >> ~/.bash_profile; then
    echo "[OK] Successfully appended '$loginfofile' to '~/.bash_profile'"
else
    echo "[ER] Something went wrong appending '$loginfofile' to '~/.bash_profile'"
fi

Be aware that the logic of A && B || C is different from if A; then B; else C; fi in one subtle way: what happens when B exits non-zero?

in if A; then B; else C; fi when A succeeds but B fails, C will NOT be executed.
in A && B || C when A succeeds but B fails, C WILL be executed -- the || operator detects the previous command in the pipeline (B) exits non-zero and will execute its right-hand side command.

I'd recommend using select instead of a while loop to get your answer

PS3="Would you like to install 'loginfo'? "
select ans in Yes No; do
    case $ans in
        Yes) install_loginfo
            break
            ;;
        No) echo "'loginfo' was not installed."
            break
            ;;
    esac
done


Aggregation on list forEach and maps improvals

From java 8 it is available in the String class the method join that achieves the same result of your method stringConcat so instead of:

String k = stringConcat(achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());

You can use String.join with "" delimiter:

String k = String.join("", achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());

It is also possibile to avoid forEach and use Map instead but because you are modifying the achats list elements, you have to map every element of the list to a new instance of your class and after you obtain your new list. To achieve this you can define a new copy constructor for the class:

achats.stream()
    .map(original -> {
        String k = //omitted for brevity : see above the code for k
        AchMatiereCompteCommandeAggFullDto copy = new AchMatiereCompteCommandeAggFullDto(original);
        if (map.containsKey(k)) {
            copy.setMntFactureHTLCY(map.get(k).getMntFactureHTLCY());
        }
        return copy;
    }).collect(Collectors.toList()); //<- return the new list


I'm not sure if there's a faster way of doing it. However, your current code can be improved.
Enhanced for loop
Your loop are written using the traditional index:
String first;
for (int i = 0; i < arr.size(); i++) {
    first = arr.get(i);
    // ...

When you don't need the index, it is better to use the enhanced for loop. This has the advantage that it makes the code more compact and easier to read:
for (String first : arr) {
     // ...

You are also calling multiple times arr.get(j) with the index instead of storing the result in a local variable. Using the enhanced for loop solves that directly.
String comparisons
Right now, you are comparing each String together with
if(first.substring(1,2).equals(arr.get(j).substring(0,1)) &&
    (!first.equals(arr.get(j)))){

There are a couple of comments here:

This is very hard to read: it is unclear what the code is doing ;
This is split in two lines and has a lot of parentheses which doesn't help
Each line is "compact" so it's hard to see what is actually happening.

To rewrite that, we should remember that what we're trying to do here: test whether the 2nd character of the 1st string is the same as the 1st character of the 2nd string. So, instead of using substring, let's use charAt which directly returns the character at the given index. The 2nd character of the first String is first.charAt(1); the 1st charcter of the second String is second.charAt(0). As such, we could have:
if (!first.equals(second) && first.charAt(1) == second.charAt(0)) {
    // ...
}

Note the added spaces before the curly braces, between the operators and after the if statement, it also contributes to clarity.
Bizarre default condition
When the word currently considered is not a property fit, you are dping
else {
    second = "    ";
}

if (!second.trim().isEmpty()) {
    // ...
}

You are explicitely setting the String to whitespaces, only to trim it afterwards. This is a bit awkward.
What you want to do here is to continue when you reach an unwanted word. So you could have instead:
for (String first : arr) {
    for (String second : arr) {
        if (second.equals(first) || second.charAt(0) != first.charAt(1)) {
            continue;
        }
        for (String third : arr) {
            if (third.equals(first) || third.equals(second) ||
                first.charAt(2) != third.charAt(0) || second.charAt(2) != third.charAt(1)) {
                continue;
            }
            for (String fourth : arr) {
                if (fourth.equals(first) || fourth.equals(second) || fourth.equals(third) ||
                    first.charAt(3) != fourth.charAt(0) || second.charAt(3) != fourth.charAt(1) || third.charAt(3) != fourth.charAt(2)) {
                    continue;
                }

but now we're back to a mess: this is hard to read. However, it gives us insight into how can we do it better.
What we want is the following: we have a list of already found words (first and second for example); with that, we want to continue when the third is incorrect. What makes it incorrect is:

either it is equal to one of the previous found word
its characters do not match with the previously found words

So we can make a method of that!
Factoring common logic
private static boolean isIncorrect(String word, String... others) {
    boolean alreadyFound = Arrays.stream(others).anyMatch(word::equals);
    boolean notMatchedChars =
        IntStream.range(0, others.length)
                 .anyMatch(i -> word.charAt(i) != others[i].charAt(others.length));
    return alreadyFound || notMatchedChars;
}

This method is split in two (and uses Java 8 idioms but the logic would be the same without it). It takes as parameter a word to test and a vararg of the currently found words.

The first test checks whether any of the currently found words others are equal to the tested word.
The second test checks whether the characters are correct. If we have 3 currently found words then

the 1st character of the word must be equal to the 3rd character of the first word;
the 2nd character of the word must be equal to the 3rd character of the second word;
the 3rd character of the word must be equal to the 3rd character of the third word;

With that method, we can refactor our code to
void makeWord(List<String> arr) {
    for (String first : arr) {
        for (String second : arr) {
            if (isIncorrect(second, first)) {
                continue;
            }
            for (String third : arr) {
                if (isIncorrect(third, first, second)) {
                    continue;
                }
                for (String fourth : arr) {
                    if (isIncorrect(fourth, first, second, third)) {
                        continue;
                    }
                    System.out.println(first);
                    System.out.println(second);
                    System.out.println(third);
                    System.out.println(fourth);
                    System.out.println(" ");
                }
            }
        }
    }
}

which is very clean, although surely O(n4).


Ensure that ICommand implementation properly uses weak references

The implementation works fine if the passed delegate is an instance method, because that prevents the method from being garbage collected.

But that is not necessarily the case. Lambda expression, for instance, will be garbage collected sometime because they are not referenced somewhere else.
That may result in strange not reproducible bugs that are hard to debug.

The following code (with a simplified version of the WeakRelayCommand class) shows that the weak reference approach does not work for static methods and lambda expressions with closures.

void Main()
{
    var longLiveObject = new DummyObject();
    var commands = GetActions(longLiveObject);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    foreach (var command in commands)
        Console.WriteLine(command.Name + "\t IsAlive:" + command.IsAlive);
}

private static WeakAction[] GetActions(DummyObject longLiveObject)
{
    var localObj = new DummyObject();
    return new []
    {
        new WeakAction("InstanceMethod (short living)", localObj.InstanceMethod),
        new WeakAction("InstanceMethod (long living)", longLiveObject.InstanceMethod),
        new WeakAction("StaticMethod", DummyObject.StaticMethod),
        new WeakAction("LamdaExpression (without closure)", o => { }),
        new WeakAction("LamdaExpression (with closure)", o => localObj.InstanceMethod(o)),
    };
}

// Define other methods and classes here
public class DummyObject
{
    public void InstanceMethod(object obj) { }
    public static void StaticMethod(object obj) {}
}

public class WeakAction
{
    private readonly WeakReference<object> _targetReference;
    private readonly MethodInfo _callbackInfo;

    public WeakAction(string name, Action<object> executeCallback)
    {
        Name = name;
        _targetReference = new WeakReference<object>(executeCallback.Target);
        _callbackInfo = executeCallback.GetMethodInfo();
    }

    public string Name { get; }
    public bool IsAlive
    {
        get
        {
            object obj;
            return _targetReference.TryGetTarget(out obj);
        }
    }
}

Output:

InstanceMethod (short living)        IsAlive:False
InstanceMethod (long living)         IsAlive:True
StaticMethod                        IsAlive:False
LamdaExpression (without closure)   IsAlive:True
LamdaExpression (with closure)      IsAlive:False


Saving a submitted Mongoose model, possibly with an uploaded image

Your modified code is better, but you can simplify this method even more. If you don't return anything from a function in a promise, it will be resolved with no value. There's no need to do return Promise.resolve().

.catch(error => next(error)) is equivalent to .catch(next).

Code Tells You How, Comments Tell You Why. Don't clutter your code with comments that tell you nothing more than the code they are describing. "If the request contains a file, generate a file name for it." tells me nothing more than if (req.file) req.body.logoImage = generateFileName(req.file.mimetype)

Depending on your framework, async functions might be able to simplify this logic. If you are using Express, this won't apply. However, if you are using a framework which lets you return a promise in middleware, async functions are the way to go. If next(error) is equivalent to returning a rejected promise, you can just do this:

// Save a new job to the database.
exports.save = async function(req, res) {
  if (req.file) {
    req.body.logoImage = generateFileName(req.file.mimetype)
  }

  const job = await Job.create(req.body)
  if (job.logoImage) {
    await moveFile(req.file.buffer, job.logoImage)
  }

  res.json({ status: 'Uploaded job successfully.' })
}

If Job.create doesn't use req.body.logoImage and generateFileName never returns a falsy value, you can further simplify this logic by combining the if statements.

// Save a new job to the database.
exports.save = async function(req, res) {
  const job = await Job.create(req.body)
  if (req.file) {
    await moveFile(req.file.buffer, generateFileName(req.file.mimetype))
  }

  res.json({ status: 'Uploaded job successfully.' })
}

If async functions won't work for your use case (I wouldn't want to make the exported function return a promise if it is left dangling), I would go with this logic (assuming generateFileName can return a falsy value):

// Save a new job to the database.
exports.save = function(req, res, next) {
  if (req.file) req.body.logoImage = generateFileName(req.file.mimetype)

  Job.create(req.body)
    .then(job => {
      if (job.logoImage) {
        return moveFile(req.file.buffer, job.logoImage)
      }
    })
    .then(() => {
      res.json({ status: 'Uploaded job successfully.' })
    })
    .catch(next)
}


How to make below code more readable and efficient?

I cannot imagine the code being that reduced; you probably removed extraneous code.
The code shown should be clearer as:

public class ProductInitialization {
    public void setAccess(Product p){
        p.access = p.brand.equals("LOCAL") ? ProductConfiguration.PRODUCT_ACCESS
             : "DEFAULT";
    }
}

public class ProductMarketInitialization {
    public void setMarketAccess(Product p){
        p.access = p.type.equals("MARKET") ? ProductConfiguration.MARKET_PRODUCT_ACCESS
                   : "MARKET_DEFAULT";
     }
}

The ProductConfiguration is taken from a properties file. This PropertiesResourceBundle is principally partly lazy. A ListResourceBundle would be totally immediate, as this is a java class containing arrays. If on the other hand you would like the startup as smoothly as possible, a totally lazy loading would need getters for the ProductConfiguration.

This seems still not very important, so be it.

The special cases of a brand LOCAL and type MARKET, and finally a special result DEFAULT and MARKET_DEFAULT hinting at yet another case handling are more cumbersome.

Old      New

LOCAL    ${productConf.productAccess}
other    Optional.empty()

MARKET   ${productConf.marketProductAccess}
other    Optional.empty()

So making the access field an Optional<...>, maybe even an optional getter.

Having two initialisation classes seems overdesigned, especially as they create two distinct categories of the same Product.

In general it seems too early to pay too much attention to adding extra code for nicety's sake.

    public void configAccessForDefault(Product p){
        p.access = p.brand.equals("LOCAL") ? ProductConfiguration.PRODUCT_ACCESS
             : "DEFAULT";
    }

    public void configAccessForMarket(Product p){
           p.access = p.type.equals("MARKET") ? ProductConfiguration.MARKET_PRODUCT_ACCESS
                   : "MARKET_DEFAULT";
     }


"Prev" / "Next" buttons for a circular list

I recommend splitting up the work into one function that is pure and another one that has side-effects.

const resultBox = document.getElementById('result')
const messages = ["cat", "dog", "fish"];
const length = messages.length;

const getNextIdx = (idx = 0, length, direction) => {
   switch (direction) {
     case 'next': return (idx + 1) % length;
     case 'prev': return (idx == 0) && length - 1 || idx - 1;
     default:     return idx;
   }
}

let idx; // idx is undefined, so getNextIdx will take 0 as default
const getNewIndexAndRender = (direction) => {
     idx = getNextIdx(idx, length, direction);
     result.innerHTML = messages[idx]
}

getNewIndexAndRender();

<button onclick="getNewIndexAndRender('prev')">prev</button>
<button onclick="getNewIndexAndRender('next')">next</button>

Note: getNextIdx is a pure function, which will never modify any value, it takes the arguments it needs and returns a new value, we pass into it the currentIdx, the lengthOfTheArray and an action which lets the function decide, what to do.


Making the parsing of a String to an Int32 robust (valid, positive, not 0 validation)

First: parsing

The shortest you can do is

int uiScale;
return
    int.TryParse(ConfigurationManager.AppSettings.Get("UiScale"), out uiScale)
    && uiScale!= 0 ? Math.Abs(uiScale) : 1 ;

Second: style

uiScale

This method should be called either GetUiScale or be a property if named UiScale because in C# we use PascalCase for public members and methods usually contain a verb (where it makes sense).

retint

Don't just call it like this. It's better to use the real name that better describes the purpose of the variable so uiScale would be fine.


You can pass context by defining extenstions inside the class + by using "Builder API". But I recommend you to avoid extensions like String.smt().

object ConnectionPool{
    fun useConnection(body: Connection.() -> Unit){
        val connection = Connection()
        connection.body()
    }
}

class Connection {
    val field = 42
    fun String.execute() {
        println(field)
    }
    fun execute2(query: String){
        println(field)
    }
}

fun sample() {
    ConnectionPool.useConnection {
        "CREATE TABLE".execute()
        execute2("CREATE TABLE")
    }
}

Also you can avoid mutablelist if you use generateSequence{} and map{}

generateSequence { if (resultSet.next()) resultSet else null }
   .map{ resultSetMapper(it) }.toList()

And I would reccomend to put close connection to useConnection().


Command-line program for applying several operations on a PDF file

Yep. I suppose your idea is generaly fine. This is being called Command Pattern. You might like to read more about it on Google. Used together with other well known pattern Strategy they both might be used here. Plus another one - Template Method. Let me just suggest some basic approach:

public abstract class BaseCommand
{
    protected BaseCommand()
    {

    }

    public void Process(StuffOptions options)
    {
        Logging.Log("here is a bunch of logging");

        // here sometimes there is some action-specific code but not often
        ExtraStuff();

        using (DocWrapper doc = new DocWrapper(options.File)) // this is in all actions
        {
            foreach (int page in doc.GetPagesToModify(options.Pages)) // this is in most actions
            {
                // call some stuff on the doc instance
                DoRealStuff(doc);
            }

            doc.Save(options.OutputFile); // this is in all actions
        }
    }

    protected abstract void DoRealStuff(DocWrapper doc);

    protected virtual void ExtraStuff()
    {

    }
}

So, now you can go and implement your commands. You have to ALWAYS implement abstract method DoRealStuff() but only override ExtraStuff() when needed.

class BaseCommandA : BaseCommand
{
    protected override void DoRealStuff(DocWrapper doc)
    {
        // Doing my stuff here!
    }
}

class BaseCommandB : BaseCommand
{
    protected override void ExtraStuff()
    {
        base.ExtraStuff();

        // I have to set some extra paramaetrs here...
    }

    protected override void DoRealStuff(DocWrapper doc)
    {
        // Doing my other stuff here!
    }
}

Then there is matter of implementing last part - strategy. You can keep your static switch-get approach if you like, bu t better is to hide your classes details and return commands only by their base type:

public static class CommandFactory
{
    private static BaseCommandA commandAInstance = new BaseCommandA();
    private static BaseCommandB commandBInstance = new BaseCommandB();

    public static BaseCommand GetCommand(invokedVerb)
    {
        switch (invokedVerb)
        {
            case "barcode": return commandAInstance;
            case "addblankpage": return commandBInstance;

            // ...
        }
    }
}

You might like to go into some lazy initialization inside if you like...

And then - grande finale - using all this stuff:

    public void Processing(cmd)
    {
        CommandFactory.GetCommand(cmd.Verb).Process(cmd.Options);
        // ...
    }

Ofcourse all types, and arguments are being simplified. Good luck and have nice coding.

EDIT: And yes - there ofcourse are some precautions - when commands are done like that (static) all processing shall be stateless (no properties or fields inside command classes). If this is required - for example to pass some data from DoExtraStuff() - you just remove static fields and create new instance of command every time the GetCommand() is being called. Good thing is - the main Processing function remains the same - power of encapsulation.
Delegate approach might also be fine, but I think my classic solution is much easier to expand, extend and maintain.

EDIT 2: I was asked by OP to explain more situation where there is some data to pass between preprocessing function and main function. There are at least two possible solutions.
First is to implement factory other way, so this is no longer using static instances of commands but creates a new one for each call:

public static class CommandFactory2
{
    public static BaseCommand GetCommand(string invokedVerb)
    {
        switch (invokedVerb)
        {
            case "barcode": return new CommandA();
            case "addblankpage": return new CommandB();

            // ...
        }

        return null;
    }
}

The only remaining thing is to add some fields / properties to BaseCommand or specific Command and just share values between methods of the class, like:

class CommandC : BaseCommand
{
    private string _extraValue = null;

    protected override void ExtraStuff()
    {
        base.ExtraStuff();
        _extraValue = ProcessExtraValue();

        // I have to set some extra parameters here...
    }

    protected override void DoRealStuff(DocWrapper doc)
    {
        // Doing my other stuff here!
        switch (_extraValue)
        {
           // ...
        }
    }

    private string ProcessExtraValue()
    {
        //...
        return "";
    }
}

The second approach would be suitable if you always produce same intermediate data, so then you do not alter Factory but rather BaseCommand interface and children, like:

public abstract class BaseCommand
{
    protected BaseCommand()
    {

    }

    public void Process(StuffOptions options)
    {
        Logging.Log("here is a bunch of logging");

        // here sometimes there is some action-specific code but not often
        ExtraData data = new ExtraData();
        ExtraStuff(data);

        using (DocWrapper doc = new DocWrapper(options.File)) // this is in all actions
        {
            foreach (int page in doc.GetPagesToModify(options.Pages)) // this is in most actions
            {
                // call some stuff on the doc instance
                DoRealStuff(doc, data);
            }

            doc.Save(options.OutputFile); // this is in all actions
        }
    }

    protected abstract void DoRealStuff(DocWrapper doc, ExtraData data);

    protected virtual void ExtraStuff(ExtraData data)
    {

    }
}

And then you just fill this ExtraData class with whathever proeprties you wan't to share.

I would personally prefer first one, as it is more elastic and introduces extra stuff only when this is required (ie. only inside these commands that need this). However drawback is if you are planning on intense processing - you will be creating new instance of command class every time you are going to use it...

Eventually, this can be solved on factory level - implement each command creation the best way that suits it better - even create deeper command inheritance to distinguish different behavior. But now I went too far (and broke SOLID a bit), so let allow me to finish at this point :P


WITH (nolock)

While there is nothing inherently wrong with using WITH (nolock) per-se, it's mostly meant to be used within transactions that have an isolation level that does cause locks, to mark that specific table as an exception to the locking. If your whole transaction is meant to not have any locks, just declare this at the top:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

Use variables

This will potentially help you make the code more readable and flexible.

--Using a variable for readability and flexibility
--This would make it easier also to turn into a script
--like a stored procedure in the future
DECLARE @top INT;
SET @top = 1;

Then you can do things like SELECT TOP (@top) * FROM ... and that will allow to easily adapt it if you want top 3, top 5, 10 etc. instead of just the top-most row.

Approach

As thoroughly explained and illustrated in Retrieving n rows per group on DBA.StackExchange site, there are two common ways of doing this which are simpler and much more efficient than UNION ALL.

Using ROW_NUMBER()

Per MSDN:

  Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

As applied to your query:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
DECLARE @top INT;
SET @top = 1;

WITH grouped AS (
    SELECT
      ROW_NUMBER() OVER
        --This is equivalent to GROUP BY + ORDER BY combined
        --where the first item in each group/partition will have
        --row number 1 and so on, based on the ORDER BY clause
        (PARTITION BY machineregisterid
        ORDER BY utctime) AS row_num
      , *
    FROM mrh_0000004
)
SELECT * FROM grouped
--Using <= in case @top was greater than 1
WHERE row_num <= @top;

Using APPLY

According to TechNet:

  The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query.

Again, as applied to your query:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
DECLARE @top INT;
SET @top = 1;

SELECT
    mrh1.machineregisterid,
    mrh2.utctime,
    mrh2.[value] --using brackets because VALUE is an ODBC reserved keyword
FROM mrh_0000004 AS mrh1
CROSS APPLY (
    SELECT TOP (@top) *
    FROM mrh_0000004
    WHERE machineregisterid = mrh1.machineregisterid
    ORDER BY utctime
) AS mrh2
ORDER BY machineregisterid, utctime;


WCF using TAP without worrying about timeouts

Design Trigger

I don't understand why you implement a duplex wcf operation to emulate a simplex operation, just to avoid configuring the timeout. Let's assume you have a really good reason why you don't want to change the default timeouts, then your solution can still time out on being idle (after 10 minutes), because you changed from timing out on SendTimeout to ReceiveTimeout.

As explained here the following timeouts have an impact on your code:

SendTimeout:
maximum threshold to expire an ongoing simplex operation. -> The timeout you don't like to configure (default: 1 minute)
ReceiveTimeout:
maximum idle time on a session. -> The timeout between the one-way message and the callback fired back. (default: 10 minutes)

Review

Your concern about using a single instance for multiple calls is valid. Using a single instance with a single callback is the simplest solution. Otherwise, you would need to implement a matching system with correlation ids in the request and callback contracts.
The lifetime management is not robust enough. Use a try-finally block to close the connection. Also, distinguish between Abort (when connection is Faulted) and Close (graceful disconnect) (Close Connection).

//wait for the result
var result = await tcs.Task;  // <- if this throws an exception

//close the connection
client.Close();       // <- this won't be called


Per the documentation for UserDict:

  The need for this class has been largely supplanted by the ability to subclass directly from dict (a feature that became available starting with Python version 2.2).

Rather than:

class LazyDict(IterableUserDict, object):

therefore, unless you have a really good reason to want to support 2.1 and earlier, I would use:

class LazyDict(dict):

or base it on collections.MutableMapping. This also makes compatibility with 3.x (where UserDict doesn't exist) less complex.

An edge case you may not have thought of: what if the function stored in the dictionary returns a callable object? Then you will get different results depending on when you access the dictionary. If this is intentional, it should be documented. If not, one solution would be to create a LazyCallable class (effectively a custom partial) to store the function and its arguments, so you can check if isinstance(item, LazyCallable) to distinguish between items added via set_lazy and any other callable values.

Overall, I'm not convinced I see the point to this. The function only gets called once, but I'm not sure the layer of additional complexity needed for:

lazy_dict.set_lazy(4, joiner, 'foo', 'bar', name='test', other='muah', sep=' ')

is better than:

vanilla_dict[4] = joiner('foo', 'bar', name='test', other='muah', sep=' ')

In both, the function only gets called once (at slightly different times, admittedly), and the latter doesn't require the reader to know about LazyDict. This also doesn't provide the functionality (that e.g. regular "memoization" does) to dynamically store results of calls to the function with different arguments, so it's only called once for each set of arguments.

I suppose one advantage would be in cases where you aren't sure, when you add the function to the dictionary, whether or not you will ever need to call it. If the function is very computationally complex but not actually needed, you can optimise one call down to zero, but there are probably easier ways to do that. There's no reason the user couldn't put a partial into the dictionary themselves.

Perhaps off-topic, but:

# Test caching functionality.
def call_at_max(count):
    counter = [0]

    def inner():
        counter[0] += 1
        if counter[0] > count:
            raise AssertionError('Called more than once')
        return 'happy'
    return inner

You have hard-coded 'Called more than once', which won't make sense for count != 1. Also, using a list to make a "mutable integer" isn't very neat. I would either make it non-generic (i.e. hard-code the 1, too), or implement as something like:

MULTIPLES = {1: 'once', 2: 'twice'}  # add 3: 'thrice' if you like!

# Test caching functionality.
def call_at_most(times):
    def inner():
        inner.counter += 1
        if inner.counter > times:
            raise AssertionError(
                'Called more than {}'.format(
                    MULTIPLES.get(times, '{} times').format(times)
                )
            )
        return 'happy'
    inner.counter = 0
    return inner

In use:

>>> test = call_at_most(2)
>>> test()
'happy'
>>> test()
'happy'
>>> test()

Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    test()
  File "<pyshell#47>", line 8, in inner
    MULTIPLES.get(times, '{} times').format(times)
AssertionError: Called more than twice

I'd also replace assert True with pass.


Simple recursive transformation solution in Python

Your code works correctly – as far as I can see – for strictly positive
integers \$ a, b, c, d \$. It fails if the integers are allowed to
be zero or negative. For example:

solve(-1, -1, -2, -3) returns False although \$(-1, -1) \$ can
be transformed to \$ (-2, -3) \$.
solve(0, 0, 1, 1) fails with a “maximum recursion depth exceeded”
because it calls itself with the same arguments.

The remainder of this review is based on the assumption that
\$ a, b, c, d > 0\$.

The number of recursive calls increases quickly with larger input values
because in most cases you have two possible branches at

return solve(a+b, b, c, d) or solve(a, a+b, c, d)

As an example, solve() is called

\$29\$ times to compute that \$(4, 6)\$ is not
reachable from \$(1, 1)\$, and
\$8189\$ times to compute that \$(127, 99)\$ is reachable
from \$(1, 1)\$.

The problem is that one does not know if \$(a, b)\$ should become \$(a+b, b)\$
or \$(a, a+b)\$ in order to reach \$(c, d)\$.

The “trick” to do the transformations backwards. If \$(c, d)\$ is
reached eventually, then the previous pair must be either
\$(c-d, d)\$ or \$(c, d-c)\$. But only one of these is possible, depending on the
sign of \$ c-d \$.

That leads to the following implementation:

def solve(a, b, c, d):
  if a == c and b == d:
    return True
  elif a > c or b > d:
    return False
  elif c >= d:
    return solve(a, b, c - d, d)
  else:
    return solve(a, b, c, d - c)

which is considerable faster: Now solve() is called

\$4\$ times to compute that \$(4, 6)\$ is not
reachable from \$(1, 1)\$, and
\$14\$ times to compute that \$(127, 99)\$ is reachable from \$(1, 1)\$.

The method can still fail with a “maximum recursion depth exceeded” runtime
error. But with this changed algorithm it is easy to replace the
recursion by an iteration:

def solve(a, b, c, d):
  while c >= a and d >= b:
    if c == a and d == b:
        return True
    (c, d) = (c - d, d) if c >= d else (c, d - c)
  return False

The algorithm itself can be improved further by replacing multiple transformations
$$
(c, d) \to (c-d, d) \to (c-2d, d) \to \ldots
$$
by a single transformation
$$
   (c, d) \to (c - kd, d)
$$
with a suitable integer \$k\$. How large can \$k\$ be chosen?
If that reminds you of the Euclidean algorithm for computing the greatest common divisor then you are on the right
track to implement an optimal method.


This seems quite fine. I can only nitpick.

Here, either the comment is wrong or you have a bug,
as the command will remove underscore instead of replacing with space:

// replace underscore "_" with space " "
$step = str_replace('_', '', $step);

Many of the expressions have unnecessary elements:

The /i flag in expressions that don't include case sensitive pattern
The grouping within (...) in expressions that don't use the capture group
\\ instead of a simple \

For example these can be simplified:

$step = preg_replace("/(\\[.*?\\])/is", '', $step);
$step = preg_replace("/(\\(.*\\))/is", '', $step);
$c = preg_match_all("/(\\d+)/is", $string, $matches);

To this:

$step = preg_replace("/\[.*?\]/s", '', $step);
$step = preg_replace("/\(.*\)/s", '', $step);
$c = preg_match_all("/\d+/s", $string, $matches);

I would add one more operation to remove spaces in front of dots:

$step = preg_replace('/ +\./', '.', $step);


A few comments:

It seems odd to write a function for formatting a number that takes a string as an argument;
Your function doesn't currently deal with float numbers correctly (and, as it takes a string argument, you can't easily check isinstance(arg, int));
Your function prints the output rather than returning it, severely limiting its usefulness; and
You aren't compliant with the style guide.

Also, as pointed out in the comments, this is handled by format already, and can be used in str.format too:

>>> "Number: {:,}".format(123456.789)
'Number: 123,456.789'


Well, you have started to use decimal instead of float and introduced a couple of named constants but pretty much every other point I stated in my answer to the other question still stands.

Naming conventions (PascalCase for properties)
You now have introduced a WithholdingRate property but that doesn't affect anything (the property is not used anywhere in the class)
Although you have introduced a named constant _PayRateDefault you are still using magic numbers in various places.
You have added some rules but they are implemented inconsistently - in hours you enforce the rule in the get while in payrate you do it in the set.
The way you have added the rules is simply bad - you silently coerce the values and the user of your class won't have a clue what's going on.

Assume this calculator is used to process the payroll in a company with lots of employees. Further assume that some of those are contractors which have not worked in the last week for whatever reason. Now you read in the work hours for each employee and everyone who hasn't worked at all (hours == 0) will get a full week payed - ouch.

If properties have restrictions on what range of values they should be in then enforce them in the set method by throwing an ArgumentException stating what was violated. It's better for your program to crash with an exception than to spit out bad data.

One of the few places where coercion of values makes sense is in user controls which force out of range values back into the range and then feed that back to the user (e.g. numeric up/down controls which a given min and max) but in most other cases it will do more harm than good.

Unfortunately your code has become somewhat more convoluted than the original.


Generic Meyers Singleton implementation in C++

Overview
I am not sure this byes you anything in savings.
Its one static function and making sure that you can't copy/move the object.
There are some issues aound using templates to implement this as I have tried exactly the same before. If this is a single application it is find but if you start using shared libraries then you may run into issues where you have several instances of T because there is a unique version of get() in every shared library that has not been removed.
Code Review
Not unique.
#ifndef SINGLETON_H
#define SINGLETON_H

Put your code in a namespace and add the namespace the include guards.

Reading ahead it looks like this only works because you assume T inherits from Singleton and thus makes sure that all the copy/move semantics are disabled.
    static T& get()
    {
        static T obj;
        return obj;
    }

But your get() method does not validate this. So I could call this method with anything and get a reference to a thing that is not a signelton.
    std::string myString = Singleton::get<std::string>();

You can make sure that the class works correctly by using static_assert.
    static T& get()
    {
        static_assert(std::derived_from<Singelton, T> == true);

        static T obj;
        return obj;
    }


Readability & Maintainability

Right now your code is a bit hard to read.  A way to greatly help this would be to use better variable names.

Put the variable declarations to separate lines and initialize them to some value at the same time. From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

You should declare your for loops as such:

for(int i = 0; i < size; ++i)

Note that this was introduced in the C99 standard.  There is no reason you should not be using this standard in your code.

Design

Group your variables in structs to make them more maintainable, a
good hint that you should be doing this is when you are passing in
9 parameters to your function.
Return the output vector; it makes your function easier to use.
You'll have to allocate the space in your method and free it
elsewhere.  This also eliminates the potential bug discussed below.
Don't cast malloc().
Right now you are using this loop to zero out temp (or at least part of it)

for (r = 0; r <= c - 1; r++){
    temp[r] = 0.0;
}

The original algorithm doesn't implement this in a separate loop, and I don't recommend you do either.  It's a loop in the code you don't need.
These lines:

temp[r] = temp[r] + Nu[k]*P[idx+r];
S[r] = S[r] + Nv[l]*temp[r];

Can be shortened to:

temp[r] += Nu[k]*P[idx+r];
S[r] += Nv[l]*temp[r];

Set those pointers you free()ed to NULL right after.  This prevents us from trying to access the data afterwards, which will result in undefined and usually catastrophic behavior.

Bug

Right now you are relying on the passed in values already stored in S[r] when you add Nv[l]*temp[r] to them.  In the original NURBS A3.5 algorithm, they are 0'ed out right before their use.  You could overwrite all these values to 0 with a memset() in our function and continue as is. However, overwriting something the user passes when we could've started from scratch is usually not expected behavior.

Create the array at the top of the function like you do with the other arrays, using calloc().


You should really use more functions,
for a little more to type def fn_name and fn_name() you can get way more readability.
You can also get quite a significant speed up.

For example the code to pick a class name can be wrapped in one.

def pick_class_name():
    classname = ""
    while True:
        classpick = input("Enter class name (\"A,B,C\") ").upper()
        try:
            if classpick in ["A","B","C"]:
                classname = "class"+classpick+".txt"
                break
            else:
                raise ValueError
        except ValueError:
            print("Invalid value. Please enter a letter A,B or C.")
            break

    return classname

This can be improved quite significantly.
The only time that the try will raise a ValueError is when you explicitly raise ValueError.
This basically means that your except should be your else.

def pick_class_name():
    classname = ""
    while True:
        classpick = input("Enter class name (\"A,B,C\") ").upper()
        if classpick in ["A","B","C"]:
            classname = "class"+classpick+".txt"
            break
        else:
            print("Invalid value. Please enter a letter A,B or C.")
            break

    return classname

The above clearly shows the while True is pointless, along with all the breaks.
Instead you could remove the break on the else and change the class_name = into a return.

def pick_class_name():
    while True:
        classpick = input("Enter class name (\"A,B,C\") ").upper()
        if classpick in ["A","B","C"]:
            return "class" + classpick + ".txt"
        else:
            print("Invalid value. Please enter a letter A,B or C.")

You do these try: if: ... else: raise: except: blocks rather than just a simple if ... else,
in a few places, mostly in while loops, that can probably be changed like the above.

You use test in a for loop but rely on the global i to output the correct question number.
This is just bad, first for i in ... is only good if you use that i in a small loop like:

def test(question_number):
    #...
    # Use `question_number` rather than `i`

for i in range(10):
    test(i)

This is as tracking global and local one letter variable names is hard and annoying.
Even more so if you are using an idiom unidiomatically.
So you would want to use question_number rather than i in this case.
You however don't want to change i to question_number in the loop,
as you'll still have to remember global variable.

This would also allow you to change that block of code into a one-liner:

correct_count = sum(map(test, range(question_count)))
correct_count = sum(test(i) for i in range(question_count))

Where if you used the first one in your current code you will get an error or the question number won't change.
And so it's prone to breaking your function depending on how it's used.

Your code is quite hard to read, as you rely on global variables in your functions, and you don't have many functions.
To both make it more efficient and easier to read you should add more functions.


Encapsulation preserving operator= overloading in C++

Design
I think it obfuscates the code with no real advantage.
// This adds an object `x` to the class `example` that
// when assigned a double will forward the
// value to the private method `setx()`
OPEQ_SETTER_GETTER( example, double, setx, x );

I think it would be easier to add a public function that forwards the value.
public:
void publicSetX(double v) {setx(v);}  // ? easier to read.

Also I add my usual rant about getters/setters breaking encapsulation by exposing internal implementation details.
Code Review
Make sure this is noted as a non-owning pointer.
Owner *owner;

When you construct the object. Owner should never be nullptr
accessor ( Owner* o, Setter &&f ): owner( o ), setter( f ) { }

So pass owner by reference to indicate this. Its OK to store as a pointer (as its hard to copy objects with references without additional work). But your interface should be as clean as possible so there is no misunderstanding. Pass by reference to indicate it can't be nullptr and that this object is NOT taking ownership.
The setter value f can be bound to an r-value reference. But the parameter f will not pass it on as an r-value reference. Named objects can not be r-value references. So you need to use std::forward to activate perfect forwarding. Otherwise you are just activating the copy constructor (not the move constructor).
accessor ( Owner& o, Setter &&f ): owner( &o ), setter( std::forward<Setter>(f) ) { }

OK. For doubles passing a reference around is fine. But this is supposed to be generic. You also need to allow for move assignment.
// What if T is big.
// I would want to move the `value` into the object using assignment.
accessor &operator=( const T &value ) { setter( owner, data, value ); return *this; }

Reading the value generates a copy. This is not usually desirable. Especially if T is large.
operator T() const { return data; }

I would do:
operator T const&() const { return data; }


Determine if 2 javascript objects have strictly the same properties

By this condition, the function returns false when both objects are empty:

if (isEmpty(firstObject) || isEmpty(secondObject)) return false;

I would expect true in this case, and rewrite the condition as:

if (isEmpty(firstObject) != isEmpty(secondObject)) return false;

That is, return false if one of them is empty while the other is not.

In fact, this special treatment is not even necessary, because the rest of the function naturally handles the case of empty objects.

  I was wondering if there is a more efficient, elegant or simpler way of doing this?

The current implementation is not efficient,
because of this step:

if (!firstObjectKeys.every(value => secondObjectKeys.includes(value))) return false;

The problem is that secondObjectKeys is an array,
and therefore .includes does a linear lookup.
You can improve the linear-time lookup to constant-time lookup by converting secondObjectKeys to a set.


Object-oriented Linux networking library

As Loki stated: don't re-invent the wheel. In the interest of learning and sharing, here are some ideas to consider:

if ( argc != 3 )

Use an API already designed for parsing the command line. There must be dozens.

socket.setOption(SO_REUSEADDR,1);

Since this is an object, I would hide the dependency as follows:

socket.reuseAddress();

Since this is a networking object, I would prefer not to write the above statement at all. Rather, if the socket mustn't reuse the address, the API should provide a method to disable the behaviour.

socket.hasUnreadData()

A socket typically doesn't offer direct data reading and writing. The reason is that a data stream is a much more reusable concept. Were a developer to use your API, they would have to code functionality separately for reading from a socket vs. reading from a file. This restriction seems to limit the potential of software developed. Rather:

InputStream *dataIn = new SocketInputStream();
OutputStream *dataOut = new SocketOutputStream();
socket.setSource( dataIn );
socket.setDestination( dataOut );

Now functionality can be written that reads data from any type of stream, making the source of the data independent (socket, file, database). If you absolutely must have the socket read/write datagrams, then use a terser method name:

socket.isReady()

This line:

socket.bind(Unet::Ipv4Address(argv[1],argv[2]));

Could be:

socket.bind(argv[1],argv[2]);

This simplifies the API for the developer. Otherwise all developers of the API will have to reference Ipv4Address. They shouldn't have to care. It's great to have the flexibility of putting in an Ipv6Address, but that can be handled automatically.

Regarding the exception handling:

        std::cout << "Unet exception: " << exception.getMessage() << std::endl;
        std::cout << "Standard exception: " << exception.what() << std::endl;

Having the API override what(), eliminates the duplication:

        std::cout << "Exception: " << exception.what() << std::endl;

The what() method will differentiate the exception classes in its message.

One more pet peeve:

while ( true )

Since the program doesn't actually continue forever, the loop should have a logical termination condition that tells the next person reading the source code when the program actually terminates. Some examples:

while ( socket.isOpen() )      // Exit upon socket closure
while ( isRunning() )          // Exit upon user request
while ( !command.is( EXIT ) )  // Exit when the QUIT command is received

Regarding the bind method, consider the following pseudo-code:

void Socket::bind( String host, String port ) {
  Address *address = AddressFactory.newInstance( host );
  bind( address, atoi( port ) );
}

Since the socket class already knows about Unet::Ipv4Address, adding a convenience method makes the class easier to use. Java gained popularity for a several reasons, including the simplicity of its networking API for trivial tasks. Using an AddressFactory, internally, will allow programs to work with either IPv4, IPv6, or any as-of-yet-invented protocol in the future. In C++, the application might have to be recompiled, but in Java, porting from IPv4 to IPv6 addresses has been mostly transparent.

If developers are forced to hard-code a reference to IPv4 in their application, then they will have to do extra work to make the software use a different Internet Protocol version.


The program does not solve the problem:

>>> get_optimal_value(1, (1, 1, 1, 1), (1, 1, 1, 1))
2.0

Here we have a knapsack with capacity 1, and four kinds of item, each with weight 1 and value 1. So all ways of filling the knapsack have value 1.


Find log4net logfiles at runtime without adding dependency to project

Well, that seems a strange solution to me. Despite the fact you don't have a formal reference in References folder of a VS project you still have a dependency on the log4net library. And if in runtime the log4net library won't be available, your code will fail. Moreover, somebody has to remember about that dependency and copy log4net.dll manually to you bin folder, so the code could be executed.

From my point of view, it is always better to have a visible dependency rather than having invisible one. The only exception comming to my mind is when you need to have a modular architecture where modules can be safely plugged and unplugged. And, as far as I can understand, it is not your requirement.

I would recommend you to create a separate project that would have a normal reference to log4net and which would be used by your main project. In that case you will have your main project unaware of log4net, but in the same time you would have all compile-time checks and every benefit of strongly typed language / framework.


I've done similar things in the past, although never with a scripting language and I haven't used Pascal in a really long time, so this is more of an approach review than a code review.

The action happens in MnC:

Procedure MnC(x,y : integer);
begin
  MoveMouse(x,y);
  Wait(30);
  ClickMouse(x,y,false);
  Wait(29);
end;

Moving the Mouse

The first thing you do is MouseMove.  The question that immediately springs to mind is do you need to move the mouse?  Unless the program your are interacting with actually tracks mouse movements in an attempt to detect bots, you probably don't need to move it.  Most of the times in the programs I have written I have been able to just send mouse click events at the relevant coordinates.  The library you're using supports a SetMousePos method that will simply set the coordinates of the mouse.  However, as ClickMouse calls this under the hood, this might not work for you.  I'd try running the script with just two clicks and a longer wait between them to detect if the program really requires the movements or if it's only concerned by the clicks.

ClickMouse(421,298,false);
Wait(100);
ClickMouse(470,311,false);
Wait(100);

If it is only concerned by the clicks, then great, you only need to worry about clicking the mouse.  If the program does care about the movement then you might want to think about using the MoveMouseEx function, which supports an additional parameter MouseSpeed.  The default speed is 20, with larger numbers being faster so increasing the number should either make the function return faster, or allow you to wait for less time before clicking.  Depending on whether the movement is async, you may also find that you need to wait less time for shorter movements (i.e. the mouse will get from 8 to 7 faster than it will get from 8 to 1).

Clicking the mouse

After you click the mouse, you wait before doing the next thing.  You may be able to make it so that you don't need to wait as long by using playing with MouseClickEx and passing in different values for Interval which is how long the mouse button is held down for.  Alternately, depending on how your application works you may be able to detect that the mouse click has been recognised (because some pixels have changes from red to green for example).  The library appears to have a few functions that might support this FindColors or FindBitmap would appear to be good starting points.  You could then loop until the click has been recognised, rather than waiting.


Counting number of pairs in an integer array

There are couple of improvement possible in your code.

In this method setMapAndReturnCount you should change the declaration of map from,

Map<String, Object> mapCount = new HashMap<String, Object>();

to

Map<Integer, Integer> mapCount = new HashMap<Integer, Integer>();

As you know, you want to store the input array numbers as key in Map and value is the count of occurence of a particular number in the array.

By using Object class as value in Map, you are defeating one of the main purpose of having generics implementation in Java. If you use Object then you need to uselessly cast, and otherwise don't have to.

Another point in same method, you can write your for loop in a better way like this, instead of your current code which does double work of first checking through containsKey and then uses mapCount.get to again pick the value of key.

public int setMapAndReturnCount(int[] sockArr) {
    Map<Integer, Integer> mapCount = new HashMap<Integer, Integer>();
    for (int j = 0; j < sockArr.length; j++) {
        Integer count = mapCount.get(sockArr[j]);
        if (count == null) {
            mapCount.put(sockArr[j], 1);
        } else {
            mapCount.put(sockArr[j], count + 1);
        }
    }
    return returnCount(mapCount);
}

Similarly, you can change returnCount method to this,

public int returnCount(Map<Integer, Integer> mapCount) {
    int count = 0;
    for (Integer value : mapCount.values()) {
        count += (value / 2);
    }
    return count;
}

As you don't need to first iterate on keySet and then retrieve the values with get which will be slower, and instead just iterate it on values as that is what you need for calculating number of pairs, which will be relatively faster.

Also, if you are using Java-8 and above,

You can change your returnCount to one liner like this,

public int returnCount(Map<Integer, Integer> mapCount) {
    return mapCount.values().stream().mapToInt(x -> x / 2).sum();
}


I think your code is pretty good.  The main opportunity for improved clarity I saw was to consolidate your validation code into one place.  In your code, validations are sprinkled across various methods, so that you are mixing the responsibility of "validation" and "work".

Here's a refactoring (not tested) which puts all the validation in one place, and gets it out of the way up front.  That way, the actual "work" you are doing becomes simpler to express, because you know your inputs are clean and meet all your assumptions at that point.

Also, note that you don't need to specify 0 as the first argument of reduce.

module StringCalculator

  def self.add(string)
    verify(string)
    delim = delimiter(string)
    numerics = string.gsub(/\n/, delim).split(delim).map(&:to_i)
    numerics.reject { |n| n > 1000 }.reduce(:+)
  end

  #######################
  ## Verification Code
  #######################

  def self.verify(string)
    verify_doesnt_end_with_newline(string)
    verify_no_negatives(string)
    verify_custom_delim(string) if has_custom_delim?(string)
  end

  def self.verify_doesnt_end_with_newline(string)
    fail('ends in newline') if string.end_with?("\n")
  end

  def self.verify_no_negatives(string)
    find = string.scan(/-\d+/)
    fail("negatives not allowed: #{find.join(', ')}") if find.any?
  end

  def self.verify_custom_delim(string)
    custom_delim = get_custom_delim(string)
    fail("invalid delimiter: #{custom_delim}") if custom_delim =~ /[0-9]/
  end

  #######################
  ## Delimiter Utilities
  #######################

  def self.delimiter(string)
    return ',' unless has_custom_delim?(string)
    get_custom_delim(string)
  end

  def self.has_custom_delim?(string)
    string[0, 2] == '//'
  end

  def self.get_custom_delim(string)
    string[2, 1]
  end

  private_class_method :verify, :verify_doesnt_end_with_newline, :verify_no_negatives, :verify_custom_delim, :delimiter, :has_custom_delim?, :get_custom_delim
end


Streaming floating point data in Python2

datalock seems to be unneeded, since data.append is thread-safe and iterating while appending is safe.

multiprocessing might be faster, but it might be slower. It depends on where you're bottlenecked. In particular, data transfer is slower with multiple processes.

The slow aspect here is primarily repeated conversions to numpy.ndarray objects. This can be avoided by only doing the translation once, which is easiest in the producer thread:

data.append(np.array(one_sample, dtype="float64"))

get_data is then simpler as

def get_data(raw_data, number_values=None):
    if number_values == 0:
        return []
    return np.array(raw_data[-number_values or 0:]).T

If the block size you want is bounded by a fixed limit, it's probably better to write into a circular numpy buffer of the right shape. This way, you can just do a single concatenation, rather than a concatenation of a large number of arrays.


Calculating the most profit from an array of stock prices

The following implementation will be \$O(n)\$.

public static int getMaxProfit(int[] stockPricesYesterday) {
    // make sure we have at least 2 prices
    if (stockPricesYesterday.length < 2) {
        throw new IllegalArgumentException("Getting a profit requires at least 2 prices");
    }

    // we'll greedily update minPrice and maxProfit, so we initialize
    // them to the first price and the first possible profit
    int minPrice = stockPricesYesterday[0];
    int maxProfit = stockPricesYesterday[1] - stockPricesYesterday[0];

    // start at the second (index 1) time
    // we can't sell at the first time, since we must buy first,
    // and we can't buy and sell at the same time!
    // if we started at index 0, we'd try to buy *and* sell at time 0.
    // this would give a profit of 0, which is a problem if our
    // maxProfit is supposed to be *negative*--we'd return 0.
    for (int i = 1; i < stockPricesYesterday.length; i++) {
        int currentPrice = stockPricesYesterday[i];

        // see what our profit would be if we bought at the
        // min price and sold at the current price
        int potentialProfit = currentPrice - minPrice;

        // update maxProfit if we can do better
        maxProfit = Math.max(maxProfit, potentialProfit);

        // update minPrice so it's always
        // the lowest price we've seen so far
        minPrice = Math.min(minPrice, currentPrice);
    }

    return maxProfit;
}


If you use a list of tuples instead of a dictionary and reverse the order, you can simply iterate over it. Your while loop also becomes a lot easier to understand and there is no longer any need to outsource it to another function that returns the literal and its count.

Instead of manually adding strings (something you should basically never do in in Python), use str.join.

ROMAN_LITERALS = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),
                  (90, 'XC'),  (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'),
                  (5, 'V'), (4, 'IV'), (1, 'I')]

def decimal_to_roman(x):
    out = []
    for value, literal in ROMAN_LITERALS:
        while x >= value:
            x -= value
            out.append(literal)
    return "".join(out)

Instead of the while loop you can also use integer division like you did:

def decimal_to_roman(x):
    out = []
    for value, literal in ROMAN_LITERALS:
        n = x // value               # will be 0 if value is too large
        out.extend([literal] * n)    # will not do anything if n == 0
        x -= n * value               # will also not do anything if n == 0
    return "".join(out)


First off, I'm assuming Object isn't java.lang.Object, but your own class. In that case you really should find a better name for it. Even if java.lang.Object didn't exist, "Object" is a terribly generic name giving absolutely no clue on what it represents.

The variable names flag1 and flag2 are beyond terrible, plus I believe you only need one boolean flag, if at all. Reading the algorithm gave me a headache, so I gave up after a while, so I can't say if it does what it should correctly.

Considering the method is working with sets it should return a Set and not a List.

Is the use of variable arguments really a valid usage pattern? That is usually only sensible if you call the method with separate arguments in code. This seems more like a situation where you have a Collection of objects to start with.

d is a bad variable name (again).

You should check if d actually contains at least one object (and return an empty list/set, if not), otherwise the user of the method will get an unhelpful IndexOutOfBoundsException.

In your method you only access the "neighboring objects" property of your Object and no other property. Instead of giving the method a list/array of your Objects, it would make sense to instead just give it a list/array of the sets of neighboring objects.

As @markspace says, the algorithm you are describing seems to simply be the intersection of all sets, which you can get using the method .retainAll() of Set.

Based on this the simplest attempt would be something like this (using Java 8 Streams):

// This first method is only needed if you really need the varargs:
public static Set<Object> getOverlapingNeighbors(Object... objects) {
   return getOverlapingNeighbors(Arrays.asList(d));
}

public static Set<Object> getOverlapingNeighbors(List<Object> objects) {
   return intersectionOf(objects.stream().map(Object::getNeighboringObjects).collect(Collectors.toList()));
}

// These are two generic methods that calculate the intersection of Sets of any (java.utils.)Objects.
// It could/should be placed in a general utility class.
public static <T> Set<T> intersectionOf(Collection<Set<T>> sets) {
    // It may be useful to first sort the list of sets by size, to optimize
    // runtime.
    // It is not the most optimal implementation, since it creates a new HashSet
    // in each call of intersectionOf(Set<T> a, Set<T> b)
    return sets.stream().reduce((r, s) -> intersectionOf(r, s)).orElse(Collections.emptySet());
}

public static <T> Set<T> intersectionOf(Set<T> a, Set<T> b) {
    Set<T> newA = new HashSet<>(a);
    newA.retainAll(b);
    return newA;
}


Writing a Counter object to a CSV-file in Python 3

Simplicity

I think that, for an easy task like this, the first version is better as it is considerably simpler while accomplishing the same goal.

It can still be improved though:

Cleaner deletion of file extension

infile[:-4] is probably used to remove the extension from the file, but it is not obvious, I suggest infile.replace(".txt","")(
where the extension may be different from txt but you get the idea).

Context managing

It is so easy to forget to close a file, it is better to use with that will close it automatically every time:

with open(outfile, encoding='utf-8-sig', mode='w') as fp:
fp.write('KMC|freq\n')
for tag, count in cnt.items():
    fp.write('{}|{}\n'.format(tag, count))

Naming

cnt is a mysterious name, I have no idea what kind of data it may contain, I suggest coming up with a better name.


Unfortunately, there is at least one blatant issue with the program in its current state: unused arguments. Let's have a look at it and find out why that's important.

Before that, a short disclaimer, though: I'm not a F# developer. However, I know functional programming (e.g. Haskell). I don't know the .NET lands by heart. Take this review with a grain of salt on the arguments that concern F#.

Functions and the world

When we write a function in a context, it gains knowledge of that context. For example, we bound five to addFive in the following example:

let y = 5
let addFive x = x + y

However, there is a possible issue with the code above: we might accidentally use y at a place we didn't intend, for example:

let add x z = x + y

This is exactly what happened in your functions:

        let stringInArray = fun (elem: string) ->
            query.IndexOf(elem) > -1

        let getBrands (query: string): string[] =
            Array.filter(stringInArray) brands

Note how stringInArray just uses query? And how getBrands completely ignores the given query? This means that we could use let result = getBrands "" and still end up with [|"Miso"|]. That's not what we intended!

Instead, let's go back to back to the drawing board. We need to make sure that the query gets used. So we need to add at least one argument to stringInArray:

        let stringInArray (query: string) (elem: string) =
            query.IndexOf(elem) > -1

Now we can use query in getBrands:

        let getBrands query =
            Array.filter(stringInArray query) brands

Great! Now let result = getBrands "" leads to an empty array. Success!

Names and tales

However, now that we changed stringInArray, we note that the name isn't quite fitting: if we add type signatures, we and up with:

        let stringInArray (query: string) (elem: string) =
            query.IndexOf(elem) > -1

Neither of the arguments is an array. We should call this function contains or similar. However, we could introduce another function that gets matching elements from an array:

        let isSubstringOf (haystack: string) (needle: string) =
            haystack.IndexOf(needle) > -1

        let matchingElements arr haystack =
            Array.filter(isSubstringOf haystack) arr

        let getBrands query = matchingElements brands query
        // or even
        //  getBrands = matchingElements brands

Note that with this approach we can keep the definition of getBrands to a minimum:

        let getBrands = matchingElements brands

General purpose functions and the world

Now that we used proper naming and split the functionality of our functions, it's time to re-evaluate whether they really belong in main. Remember how functions have their context saved? They provide a closure. It's therefore a good idea to keep the context small.

What functions should we therefore move out of main? We have the following at hand:

isSubstringOf, which searches in a string for another string
matchingElements, which filters an array of strings whether they are contained in the second argument
getBrands, which filters brands given a query

The first two functions sound very generic, so let's move them out of main:

module Program =

    let isSubstringOf (haystack: string) (needle: string) =
        haystack.IndexOf(needle) > -1

    let matchingElements arr haystack =
        Array.filter(isSubstringOf haystack) arr

    [<EntryPoint>]
    let main argv =
        let query = "Miso Power Washer X1000"

        let brands = [|
            "Hayo"
            "Miso"
            "The Master"
            "Vector"
        |]

        let getBrands = matchingElements brands

        let result = getBrands query
        printfn "%A" result

        0

Note how short our main got. It only contains the essential elements: query, brands, getBrands and result. One could argue that we can just replace getBrands by its definition, but premature brevity in source code is the source of future confusion, so let's keep it a little bit more verbose but self-explanatory.

Moving the functions might seem like an overkill, but note that this approach immediately had shown an error if we followed it right from the beginning. If we now use we now use query accidentally in isSubstringOf, we immediately get a compiler error (and probably an IntelliJ warning/note/error). That can be a huge boon in finding errors!

Furthermore, this approach makes it easy to unit test the functions later. Maybe we want to improve the isSubstringOf to use fuzzy logic so that it also works for "Mizo Power Washer". (Unit) tests can make sure that we don't accidentally break old functionality on the way.


Password-generation function using custom seed

I actually don't get the point of injecting so much system information into the mt_srand function. Looks like a total (and maybe even pointless) paranoia :)

But here you go with a cleaner code:

<?php
/**
* Random password generator
* v2.0
*/

define('APP_SECRET_KEY', 'qTgppE9T2c');

function randomPassword($length=10) {
  $charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';
  $charsetSize = strlen($charset) - 1;

  // Seeding the generator with a bunch of different system data and the secret key
  mt_srand(crc32(md5(microtime())
    . getmypid()
    . md5(implode(getrusage()))
    . md5(implode(stat(__FILE__)))
    . memory_get_usage()
    . disk_free_space('.')
    . APP_SECRET_KEY)
  );

  $password = '';
  foreach (range(1, $length) as $_)
    $password .= $charset{mt_rand(0, $charsetSize)};

  return $password;
}

echo randomPassword(), "\n";

Maybe you'll like the more perverted superslow version which returns CRC32 of randomly ordered entropy each time you generate a new symbol.

<?php
/**
* Random password generator
* v2.1
*/

function randomPassword($length=10) {
  $charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';
  $charsetSize = strlen($charset) - 1;

  $seeders = array(
    function () { return md5(microtime()); },
    function () { return md5(getmypid()); },
    function () { return md5(implode(getrusage())); },
    function () { return memory_get_usage(); },
    function () { return disk_free_space('.'); }
  );

  $randomSeed = function () use ($seeders) {
    shuffle($seeders);

    $entropy = '';
    foreach ($seeders as $seeder)
      $entropy .= $seeder();

    return crc32($entropy);
  };

  $password = '';
  foreach (range(1, $length) as $_) {
    mt_srand($randomSeed());
    $password .= $charset{mt_rand(0, $charsetSize)};
  }

  return $password;
}

echo randomPassword(), "\n";


Create an Array with n values that is able to use Array methods instantly

As the comments already say, I'd not put too much into such a function, that is, IMO creating the array with initial size and elements is probably enough to make a difference.

Array.create = function (n, initial) {
  var result = new Array (n);
  for (var i = 0; i < n; ++i)
    result[i] = initial;
  return result;
};

// Array.create (3);
// Array.create (5, "hi").map (...);

Which also could just be a regular function makeArray or so I guess. So you get one benefit without the rather cryptic calling convention (mapCB/method) you have at the moment. Sure, it's a matter of opinion, but I had to take a moment to understand what that is supposed to do, so arguably that is not a good choice if you want other people to read that later.

And good point about the apply, I wouldn't want to see that in real code as well.


public static int? LargestPrime(int max)
{
    if (max < 0)
        return null;
    int largestPrime = 0;
    for (int i = 0; i <= max; i++)
    {
        bool? isPrime = IsPrime(i);
        if ((bool)isPrime)
            largestPrime = i;
        if (i % 100000 == 0)
            Console.WriteLine(largestPrime.ToString("N0"));
    }
    return largestPrime;
}

Omitting braces {}, although they might be optional, won't do you good in the long run because it makes your code error-prone.

If an argument of a method isn't correct like max < 0 you should throw either an ArgumentException or better an ArgumentOutOfRangeException.

You are iterating from 0 to max to check if the value is a prime, but I wonder what else could the number be? Either it is a prime or it isn't a prime, there is no third way so it doesn't make sense that IsPrime() returns a nullable bool.

bool? IsPrime(int n)
Here you are iterating from 5 to i*i<n for each number which is passed to the method.
So let us assume that we pass max = 10.000.000 (the dots are there for clearity) this

    if (n % i == 0 || n % (i + 2) == 0)
        return false;

in the for loop in the IsPrime() method is executed 16.194.513 times.
By using a sieve you could pretty much speed this thing up like so
static int CalculateLargestPrime(int maxPrime)
{
    bool[] isComposite = new bool[maxPrime + 1];
    for (int x = 2; x * x <= maxPrime; x++)
    {
        if (!isComposite[x])
        {
            for (int y = x * x; y <= maxPrime; y = y + x)
            {
                isComposite[y] = true;
            }
        }
    }
    for (int i = maxPrime; i >= 0; i--)
    {
        if (!isComposite[i])
        {
            return i;
        }
    }

    return -1;
}

taken and adjusted from https://codereview.stackexchange.com/a/62158/29371


There reason languages like Java has that feature is because they don't have RAII like C++ does.

I don't quite see how that is better than simply:

// Note: Braces for scope. "mutex" could optionally be declared static, or as a class member.
{
    QMutexLocker lock(&mutex);

    /* code */
}


It is not necessary to decode and encode UTF-8, as split('\t') and lstrip('.\\') work fine on UTF-8-encoded strings.
The programs keeps an unlimited number of temporary files open simultaneously and will fail after exceeding the platform's maximum for open files. An approach where only a certain number of most recently used files are kept open could be appropriate here.
file_o.write(temp_files[key].read()) reads the entire file in memory. To conserve memory, use a loop and give a block size argument to read.


You should always convert the input data in something sane ASAP. Dealing with string can get inefficient and unreadable pretty soon. Something like

enum Type {SELL, BUY}

@RequiredArgsConstructor
@Getter
@ToString
class Order {
    private final Type type;
    private final int id;
    private final int price;
}

sounds good. The above annotations are from Lombok, but you can write the boilerplate manually if you really want to.

By using a class instead of extracting the information from the string again and again, you'll surely gain a factor of 10+. That's good, but the more important part is the quadratic complexity.

  Otherwise, the new buying bid is matched with the sell order with lowest asking price (earliest such order if there are ties).

This sounds like a Comparator: Order by price and then by id. I'd probably go for Guava's ComparisonChain, but it's simple enough:

class OrderComparator implements Comparator<Order> {
    public int compare(Order o1, Order o2) {
        int result = Integer.compare(o1.price, o2.price);
        if (result != 0) {
            return result;
        }
        return Integer.compare(o1.id, o2.id);
}

In theory, we could create an array of all sells and use Arrays.sort with our OrderComparator on it. However, when a new sell comes in, we'd need to insert it in the appropriate position or sort the array again. Too bad.

But we need no sorted array. All we need is

to get the least element
remove it if it's good enough
add a new element

Fortunately, there's a PriorityQueue, which provides these operations efficiently (O(log n)). So we're nearly done.

A piece of code could look like

private void processNextBuy(Order buy) {
    assert buy.type == Type.BUY;
    // just look at it, but don't remove yet
    Order sell = sellQueue.peek();
    if (sell!=null && sell.price <= buy.price) {
        sellQueue.poll(); // paired, so remove it
        price += 2 * buy;
        exchange += 2;
    } else {
        buyQueue.add(buy); // unpaired, so process later
    }
}

From the description, I'm unsure if a new sell should be processed the same way. The boring parts around are left as an exercise for the reader. ;)


Memory issues with Find Strings Problem on InterviewStreet

To successfully pass all test cases you need to implement something more sophisticated like suffix tree. That will allow you to solve this task in O(n) time using O(n) space.


Displaying recent buyers' feedback on games

Simple Approach

The simplest thing to remove copy-pasted code is to extract the exact duplication to its own function. Any variables that are needed can be passed on:

function printFeedback($st, $i) {
    if(!empty($st[$i]['feedback'])) {

        echo '

';
                    echo $st[$i]['feedback'].'

';

    }
}

Then use it:

$st = fetch([...]);

echo '
';

//Output the first 2 Feedback on line 1;
for($i = 0; $i < 2; $i++) {
    printFeedback($st, $i);
}

echo '

';

//Output the last 2 Feedback on line 2;
for($i = 2; $i < 4; $i++) {
    printFeedback($st, $i);
}

echo '
';

Now the duplication is gone.

Further Improvements

Now, the simple approach did remove the direct duplication, but we still have two similar for loops, and we have a function that accepts arguments that do not have real meaning in that context.

Let's improve it further by adjusting our print feedback function:

// echoes the given feedback array inside HTML.
function printFeedback($feedback) {
    if($feedback['feedback'])) {

        echo '

';
                    echo $feedback['feedback'].'

';

    }
}

Personally, I would create a real feedback object, but for this example I have kept it as an array, which may be fine for your purposes.

Now we can use this function in a more generic function:

// echoes the feedbacks in the feedback starting at position "from" and going to position "to" (exclusive).
function printFeedbackFromTo(Array $feedbacks, $from, $to) {
    for($i = $from; $i < $to; $i++) {
        printFeedback($feedbacks[$i]);
    }
}

And then use that function:

$st = fetch([...]);

echo '
';

printFeedbackFromTo(0,2);

echo '

';

printFeedbackFromTo(2,4);

echo '
';

Misc

Feedback seems to be user-supplied, so you have to HTML encode it, to prevent XSS.
Your comments are not needed. Just extract code into properly named functions, possibly with proper function comments (ideally using PHPDoc). In-code comments should not be used to structure your code - use functions for that - but to point out possible unclarities, problems, etc that could not be resolved otherwise.
The functions you might want to consider would be getFeedbacks($connection, $amountOfFeedbacks) and echoFeedbacks($feedbacks).
Don't put your style info in a style attribute, but in an external CSS file


Given an integer array of size n, find any three numbers

Return any three descending numbers that appear sequentially in the input such that A[i] > A[j] > A[k] and i < j < k.
  Since problem description contains 'any', I could not unit test using junits.

I think you could create inputs for tests where

there is only one of this sequence and check that,
there are only a couple of possible sequences and check that the returned one whether exists in the possible return values list or not,
there isn't any valid sequence.


TL;DR: dynamic programming.

If the alphabet has \$k\$ symbols (5 in the example), in the worst case there are \$k^N\$ possible strings and generating them is \$\Omega(k^N)\$. But it's possible to count them in \$O(k^2 N)\$ time and \$O(k^2 + N)\$ space using a simple dynamic programming approach.

The input gives the successor function: \$a\$ must be followed by one of \$\{i,e\}\$. The first step is to reverse that to get the predecessor function: \$a\$ must be preceded by one of \$\{i,u\}\$.

Then the number of strings of length \$l\$ which end in \$a\$ is \$1\$ if \$l=1\$, or the sum of the number of strings of length \$l-1\$ which end in \$i\$ or \$u\$ otherwise.

Actually, if \$N\$ is large enough relative to \$k\$ you can do even better with a more complicated approach. Treat it as a Markov chain and find a matrix power of the \$0-1\$ matrix which indicates the successor function. That takes \$O(\lg N)\$ matrix multiplications of a \$k\times k\$ matrix.


Mass and length calculator using Perl 6 custom operator

This is an interesting use case of postfixes.  Here's how I would go about it.  Unfortunately, because postfixes can't take regexen, you need to specify each one individually, but it's not horrible, especially if you throw things into a module.

Let's first create a postfix operator for each value type:

multi postfix:<kg> (Numeric() $m) { Mass.new: $m, 'k' }
multi postfix:<g>  (Numeric() $m) { Mass.new: $m      }
multi postfix:<mg> (Numeric() $m) { Mass.new: $m, 'm' }

Basically, we're saying we want to attach g onto something.  We'd like it to be a number type, so we make have it only act on Numeric types, but if someone passes us a string, the () tells it to coerce it for us.  And then we make a Mass object from those the value and the prefix.

Now let's take a look at the Mass class.  All we really need to have in it is a weight and probably store its prefix so if we create a kg if we want to display it we can keep it in kg and not switch to mg or something.  We'll store things in grams, so on creation we use the prefix to shrink/expand the value.

class Mass {
  has $.grams;
  has $.prefix;
  method new  ($value, $prefix) {
    self.bless:
      :grams($value * si-prefix{$prefix}),
      :$prefix
  }
}

The si-prefix is just a map of values:

my constant \si-prefix := Map.new( 'k', 1000, '', 1, 'm', 0.001 );

By making it independent of the gram, we can use it later for a length / etc class.  For that reason, I'd define it outside of the class so that it can be used by others easily.  Believe it or not, it is possible to have an empty string as a key.  Kind of useful in our case.

At this point, we can start to use our values:

say 500g; # --> Weight.new(grams => 500, prefix => "")
say 2kg;  # --> Weight.new(grams => 2000, prefix => "kg")

Okay, not the most useful output, but at least we know everything is working.  Let's make a Str and gist method that makes more sense:

  method Str {
    $!grams / si-prefix{$!prefix}
    ~ $!prefix
    ~ 'g'
  }
  method gist { self.Str }

Now all we really have to do is handle the addition:

multi infix:<+> (Mass \a, Mass \b) { Weight.new: a.grams + b.grams }
multi infix:<-> (Mass \a, Mass \b) { Weight.new: a.grams - b.grams }

This works great, but does automatically convert everything back to being a g unit even if both were kg, etc.  At this point, it's a bit of taste.  You could decide that the first or second unit has precedence, or implement some more complex logic (larger or smaller, or the one that results in no more than three decimal places or no more than three whole units, etc).  I'll leave that for you to implement.

As I said, this would work great as a module.  You can do that like this:

unit module SI-Operators;

my constant \si-prefix := Map.new(
  'Y',  10 **  24,   'y',  10 ** -24,
  'Z',  10 **  21,   'z',  10 ** -21,
  'E',  10 **  18,   'a',  10 ** -18,
  'P',  10 **  15,   'f',  10 ** -15,
  'T',  10 **  12,   'p',  10 ** -12,
  'G',  10 **   9,   'n',  10 **  -9,
  'M',  10 **   6,   'μ',  10 **  -6,
  'k',  10 **   3,   'm',  10 **  -3,
  'h',  10 **   2,   'c',  10 **  -2,
  'da', 10 **   1,   'd',  10 **  -1,
  '',   1
);

# MASSES

class Mass is export (:mass) {
  has $.grams;
  has $.prefix;
  method new  ($number, $prefix = '') {
    self.bless:
      :grams($number * si-prefix{$prefix}),
      :$prefix
  }
  method Str {
    $!grams / si-prefix{$!prefix}
    ~ $!prefix
    ~ 'g'
  }
  method gist { self.Str }
}

multi infix:<+> (Mass \a, Mass \b) is export (:mass) { Mass.new: a.grams + b.grams }
multi infix:<-> (Mass \a, Mass \b) is export (:mass) { Mass.new: a.grams - b.grams }

multi postfix:<Yg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'Y'  }
multi postfix:<Zg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'Z'  }
multi postfix:<Eg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'E'  }
multi postfix:<Pg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'P'  }
multi postfix:<Tg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'T'  }
multi postfix:<Gg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'G'  }
multi postfix:<Mg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'M'  }
multi postfix:<kg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'k'  }
multi postfix:<hg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'h'  }
multi postfix:<dag> (Numeric() $m) is export (:mass) { Mass.new: $m, 'da' }
multi postfix:<g>   (Numeric() $m) is export (:mass) { Mass.new: $m       }
multi postfix:<dg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'd'  }
multi postfix:<cg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'c'  }
multi postfix:<mg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'm'  }
multi postfix:<μg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'μ'  }
multi postfix:<ng>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'n'  }
multi postfix:<pg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'p'  }
multi postfix:<fg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'f'  }
multi postfix:<ag>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'a'  }
multi postfix:<zg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'z'  }
multi postfix:<yg>  (Numeric() $m) is export (:mass) { Mass.new: $m, 'y'  }

# LENGTH

class Length is export (:length) {
  has $.meters;
  has $.prefix;
  method new  ($number, $prefix = '') {
    self.bless:
      :meters($number * si-prefix{$prefix}),
      :$prefix
  }
  method Str {
    $!meters / si-prefix{$!prefix}
    ~ $!prefix
    ~ 'm'
  }
  method gist { self.Str }
}

multi infix:<+> (Length \a, Length \b) is export (:length) { Length.new: a.meters + b.meters }
multi infix:<-> (Length \a, Length \b) is export (:length) { Length.new: a.meters - b.meters }

multi postfix:<Ym>  (Numeric() $l) is export (:mass) { Length.new: $l, 'Y'  }
multi postfix:<Zm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'Z'  }
multi postfix:<Em>  (Numeric() $l) is export (:mass) { Length.new: $l, 'E'  }
multi postfix:<Pm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'P'  }
multi postfix:<Tm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'T'  }
multi postfix:<Gm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'G'  }
multi postfix:<Mm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'M'  }
multi postfix:<km>  (Numeric() $l) is export (:mass) { Length.new: $l, 'k'  }
multi postfix:<hm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'h'  }
multi postfix:<dam> (Numeric() $l) is export (:mass) { Length.new: $l, 'da' }
multi postfix:<m>   (Numeric() $l) is export (:mass) { Length.new: $l       }
multi postfix:<dm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'd'  }
multi postfix:<cm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'c'  }
multi postfix:<mm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'm'  }
multi postfix:<μm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'μ'  }
multi postfix:<nm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'n'  }
multi postfix:<pm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'p'  }
multi postfix:<fm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'f'  }
multi postfix:<am>  (Numeric() $l) is export (:mass) { Length.new: $l, 'a'  }
multi postfix:<zm>  (Numeric() $l) is export (:mass) { Length.new: $l, 'z'  }
multi postfix:<ym>  (Numeric() $l) is export (:mass) { Length.new: $l, 'y'  }

What's great about doing it as a module is you can only import what you need.  For example, if in most of your program you're not using SI units, there's no reason to polute the operator namespace with lots of postfixes.  But when you do:

sub stuff-with-lengths {
  use SI-Operators :length;
  say 25mm + 78km # 78000.025m
}

Note that multiplying, etc, would need you to implement more math operator subs.  But could also lead to interesting things like a Length * Length generating an Area etc, and Area * Length getting Volume


If this is for a complex web application, I would recommend using some sort of MVC framework. Personally I prefer backbone.js. Here are some great resources that should help you develop a maintainable app, as well help with updating and refreshing views.

MVC explanation: http://msdn.microsoft.com/en-us/library/ff649643.aspx

Backbone.js: http://documentcloud.github.com/backbone/

Connection between the two: http://css.dzone.com/articles/backbonejs-mvc-javascript

As a more direct answer to your question, I believe the code you have looks fine. But if you have multiples modules in your application, running view refresh functions on timers is not a good idea.


Find the next prime number — flow control of nested `for` loops

Factor out the inner loop into a method (not just for the sake of structure, but because it is a method bool is_next_prime(int testNum)):

    for (...) {
        if (testNum % prime) == 0)
            return false;
    }
    return true;

Then

    int getNextPrime() {
        int testNum = primeList.get(primeList.size() - 1) + 2;
        while (!is_next_prime(testNum)) {
            testNum += 2;
        }
        return testNum;
    }