Converting a List of arcs into Adjacency list representation for graph using dictionary

Overall this is pretty good. Here are a few suggestions for making it even better:

You have a lot of repeated code in your if branches. Since this code will run on either iteration, it’s better to pull it out of the branches. This reduces code repetition, and makes it clearer that this code will always run. Here’s what it reduces to:

for row in data:
    if row[0] not in graph.keys():
        graph[row[0]]={}
    if row[1] not in graph.keys():
        graph[row[1]]={}
    graph[row[0]][row[1]]=row[2]
    graph[row[1]][row[0]]=row[2]

Next you have the problem that you need to initialise every vertex with one empty dictionary. Rather than doing this by hand, you can use collections.defaultdict from the standard library. You specify a “default factory” method, and whenever you try to access a key which hasn’t already been set, it fills in the default for you.

Now the code becomes:

import collections

graph = collections.defaultdict(dict)

for row in data:
    graph[row[0]][row[1]]=row[2]
    graph[row[1]][row[0]]=row[2]

It can be a bit unwieldy to follow these numeric indices around. You can use tuple unpacking at the top of the for loop to name the individual parts of the row:

for vertex0, vertex1, weight in data:
    graph[vertex0][vertex1] = weight
    graph[vertex1][vertex0] = weight

It would be better to wrap your graph-making code in a function, graph_from_data(), so that you can reuse it in other modules.

You should also move the bits of this code that can’t be reused into an if __name__ == '__main__' block – this means the same file can be both a module and a script. If I do an import from this file, I won’t get an example graph printed as a side effect.


Converting an object to be used with a treegrid

I believe this does the same as yours, except it uses buildLeaf on each step (your function skips it in the "middle" loop, and just makes an empty object).

// Recursive convertion function
function convert(obj) {
  var item, leaf, key, leaves = [];
  for( key in obj ) {
    if( !obj.hasOwnProperty(key) ) continue;
    item = obj[key];
    leaf = buildLeaf(key, item)
    leaves.push(leaf);
    if( typeof item.children === 'object' ) {
      leaf.children = convert(item.children);
    }
  }
  return leaves;
}

// I also refactored buildLeaf slightly to accept both
// name and content, and to make use of JavaScript's
// `||`-style fallbacks

function buildLeaf(name, node) {
  var leaf        = { name: name, children: [] },
      clicks      = node.clicks || 0,
      conversions = node.conversions || 0,
      earned      = node.earned || 0,
      spent       = node.spent || 0;

  leaf.clicks          = clicks;
  leaf.conversions     = conversions;
  leaf.earned          = '$' + earned.toFixed(2);
  leaf.spent           = '$' + spent.toFixed(2);
  leaf.conversion_rate = conversionRate(conversions,clicks);
  leaf.net_earned      = netEarned(earned,spent);
  leaf.epc             = epc(clicks,earned,spent);
  leaf.roi             = roi(earned,spent);

  return leaf;
}

// In the calculation functions, I made the value checking
// less strict. Generally, strong checking is encouraged,
// but in this case other useless values would slip through,
// when only strongly checking for zero (since that allows
// `false`, empty strings, etc. to pass through).

function conversionRate(cv, cl) {
  if( !cl ) return '0%';
  return ((cv/cl)*100).toFixed(1) + '%';
}

function epc(cl, e, s) {
  if( !cl || !e ) return '$0.000';
  return '$' + ((e - (cl * s)) / cl).toFixed(3);
}

function netEarned(e, s) {
  if( !e ) return '$0.00';
  return '$' + (e - s).toFixed(2);
}

function roi(e, s) {
  if( !e ) return '0%';
  return (((e - s) / s) * 100).toFixed(0) + '%';
}

Addendum

If you need to handle the conversion differently for different levels of nesting (re: the comments), you could do something like this

function convert(obj) {
  // get the extra, optional, argument.
  // It defaults to 1, and increments otherwise
  var level = (arguments[1] || 0) + 1;

  var item, leaf, key, leaves = [];
  for( key in obj ) {
    if( !obj.hasOwnProperty(key) ) continue;
    item = obj[key];
    // Check the level here
    if( level === 2 ) {
      // 2nd level will only be converted to a simpler, non-leaf object
      leaf = { name: key, children: [] };
    } else {
      // Other levels will become "leaves"
      leaf = buildLeaf(key, item);
    }
    leaves.push(leaf);
    if( typeof item.children === 'object' ) {
      // remember to pass the level on
      leaf.children = convert(item.children, level);
    }
  }
  return leaves;
}

I don't know if there's a system in the data you're converting, but you could also check for level % 2 === 0 to handle every second (i.e. even-numbered) level differently.


Calculating distance and angle between two points, C# program

You should avoid using goto statements. Not because it took me a minute to recall what NewPoints : syntax even means, but because goto makes it extremely hard to follow the execution flow. Cases where goto makes code more readable are rare, and yours is not on of those. Just use another while (or do while) loop instead.
Calc is a poor name for a method, because it doesn't say anything about what sort of calculation it performs. It calculates distance you say? Name it CalcDistance then. Oh, wait, it also calculates angle! Maybe CalcDistanceAndAngle then? That doesn't look right... Which is an indication, that you probably need two separate methods: one to calculate angle and one to calculate distance (related to SRP).

var distance = CalcDistance(...);
var angle = CalcAngle(...);

There is a lot of copy-pasting in GetPoints method. You should probably have a method to query single value. For example

static float RequestValue(string message)
{
    float value;
    while (true)
    {
        Console.WriteLine(message);
        Console.SetCursorPosition(14, Console.CursorTop - 1);
        if (float.TryParse(Console.ReadLine(), out value)) break;
        Console.WriteLine("Invalid data has been entered. Try again.");
    }
    return value;
}

Then you can just initialize individual points:

var point1X = RequestValue("\nPoint 1\nX Coordinate: ");

I am pretty sure you don't need to move cursor, if you call Console.Write instead of Console.WriteLine.
You are using both floats and doubles in your calculations. You should probably use one or the other.
else return; is unnecessary.
I think it would make more sense for Calc to take actual points as input instead of "delta"-s. Meaning you should move:

//Getting the change in x and y from point 1 to 2.
deltaX = point2X - point1X;
deltaY = point2Y - point1Y;

inside Calc's body.


This strikes me as the sort of code that's likely to make a lot of old C programmers cringe and think that C++ programmers are wasteful. It reads in the entire input file at once, even though it only ever looks at one byte of that file at any given time. Then it creates an output string the same size as the input file (and writes zero bytes to the whole thing). So, if your input file is, say, 20 megabytes, this allocates a minimum of 40 megabytes of memory to process it.

Along with that, it writes its output over the input file. If (for whatever reason) processing stops in the middle, you've destroyed the data. Your file might have some of the encrypted data, or it might have nothing at all.

So, for a moment, let's consider how that C programmer would probably do the job, and then see if we can't do something that's at least sort of close to the same, but with (perhaps) a little more abstraction.

If I were a C programmer, I'd probably do something like this:

FILE *infile = fopen(argv[1]);
FILE *keyfile = fopen(argv[2]);
FILE *outfile = fopen(argv[3]);

char key[BUFFER_SIZE];

size_t key_size = fread(infile, 1, BUFFER_SIZE, keyfile);

size_t current = 0;

int ch;

while ((ch=getchar(infile)) != EOF) {
    putchar(ch ^ key[current], outfile);
    current = (current + 1) % key_size;
}

This reads and processes one character at a time from the input file. Even if the input file is several gigabytes, it allocates only a small, fixed amount of memory.

At the same time, the C streams do actually do buffered reading and writing, so even though this may not be the most efficient code possible, it's usually going to be reasonably fast nonetheless.

The biggest drawback here is that we've set a fixed maximum size for the key. If the user supplies a short key, we're probably wasting quite a bit of memory. If they supply too long of a key, we use only part of it so we lose some security (though, in fairness, unless the key is huge this has no real security to lose).

So what we'd like would be to read the entire key into a string (so we get the whole thing, regardless of size, without wasting a lot of extra space. Other than that, we'd like to process the data directly from input to output, and let the iostreams handle buffering enough to make that reasonably efficient.

At the same time, we'd like a nice iterator-based model for most of the processing. Since we're taking some input, transforming it, and writing the result to an output, we can use std::transform to do most of the dirty work.

The place iterators break down is in working with our key. Normally iterators go from the beginning of a collection to the end (or vice versa), but in this case we need it to (potentially) iterate through the collection holding the key many times. To do that, we can write ourselves a custom iterator, something like this:

template <class Container>
class mod_iterator {
    using value_type = typename Container::value_type;
    using it = typename Container::const_iterator;

    it begin;
    it end;
    it current;
public:
    mod_iterator(Container const &c) : begin(c.cbegin()), end(c.cend()), current(c.cbegin()) { }
    value_type operator*() { return *current; }
    mod_iterator &operator++() { ++current; if (current == end) current = begin; return *this; }
};

To make it a little more convenient to use that, we can add a little builder function template:

template <class T>
mod_iterator<T> make_mod_iterator(T const &t) { return mod_iterator<T>(t); }

To avoid overwriting the input file, we can open a third file to hold the encrypted data. Once we've done the (boring) work of opening all three files, and reading the key into a string, the processing looks something like this:

auto m = make_mod_iterator(key);

std::transform(std::istreambuf_iterator<char>(data_in), {},
    std::ostreambuf_iterator<char>(data_out),
    [&](char c) { char ret = *m ^ c; ++m; return ret; }
);

One minor addition: you want to specify std::ios::binary when you open the file of the encoded data, because the data you produce may no longer be a proper text file. Since you can use the same code to either encrypt or decrypte, that means you want to specify it for both the input file and the output file:

std::ifstream data_in(argv[1], std::ios::binary);
std::ofstream data_out(argv[3], std::ios::binary);

then the processing looks something like this:

auto m = make_mod_iterator(key);

std::transform(std::istreambuf_iterator<char>(data_in), {},
    std::ostreambuf_iterator<char>(data_out),
    [&](char c) { char ret = *m ^ c; ++m; return ret; }
);


More elegant way to get timestamp from day/hour? (Perl)

There's a timestamp file available here: http://coolwx.com/buoydata/data/curr/timestamp, so I think it'll be easier if you download and parse both data and timestamp files.

You can parse the timestamp with this with %Y%m%d%H pattern, for example using core Time::Piece module and its strptime function:

use Time::Piece;
my $time = Time::Piece->strptime("2013092616", "%Y%m%d%H"); # Time::Piece object, see docs
say $time->datetime; # outputs: 2013-09-26T16:00:00

See documentation for more formatting methods of Time::Piece object.


tl;dr: See the bottom of the post for my implementation of the function.

As mentioned in Ben Rudgers's answer, lists should not be treated as vectors, as they are not random-access. That means you should not be using numeric indices, list lengths, etc.

Lists are recursive data structures

Lists are recursive data structures: a list is either an empty list, or else it's a non-empty list which conceptually has a first element and a rest of the list. For example:

() is an empty list
(1) is a non-empty list with a first of 1 and a rest of ()
(1 2) is a non-empty list with a first of 1 and a rest of (2)

To perform an operation across all elements of a list, you make use of this recursive structure:

You check whether the list is empty. If so, do the base case.
Otherwise, do something with the first element, then call the same function with the rest of the list. This is the recursive case.

Examples of list-processing functions

Here's a simple example, that calculates the sum of a list of numbers:

(define (sum lst)
  (if (empty? lst)
      0
      (+ (first lst) (sum (rest lst)))))

Base case: if the list is empty, the sum is 0.
Recursive case: if the list is not empty, the sum is the first element plus the sum of the rest of the list. (Recursive case.)

Another example. Suppose you want to write a function that takes a list of numbers, and returns the square of all of the numbers:

(define (square-all lst)
  (if (empty? lst)
      empty
      (cons (expt (first lst) 2) (square-all (rest lst)))))

Base case: If the list is empty, return an empty list.
Recursive case: If the list is not empty, return a new list where:

the first element of the new list is the square of the first element of the old list, and
the rest of the new list is the "square of all the numbers" of the rest of the old list.

As a third example, consider a function where you want to take a list and return all the elements that are numbers:

(define (only-numbers lst)
  (if (empty? lst)
      empty
      (if (number? (first lst))
          (cons (first lst) (only-numbers (rest lst)))
          (only-numbers (rest lst)))))

Base case: If the list is empty, return an empty list.
Recursive case: If the list is not empty, then:

If the first element of the old list is a number, return a new list where:

the first element of the new list is the first element of the old list, and
the rest of the new list is only the numbers from the rest of the old list.

If the first element of the old list is not a number, discard it and return only the numbers from the rest of the old list.

Generalising the above examples

Do you see a pattern? You always check the list for empty, and handle the base case if so, and otherwise handle the first element along with calling itself with the rest of the list. In fact, all three of the functions above fit this pattern:

(define (FUNCTION lst)
  (if (empty? lst)
      BASE-CASE
      (SOMETHING (first lst) (FUNCTION (rest lst)))))

This pattern is called a right-fold, or foldr as it's called in Racket. All three of the functions above can be written using foldr (I use the parameter name next to refer to the result of the recursive call, (FUNCTION (rest lst))):

(define (sum lst)
  (foldr (lambda (element next)
           (+ element next))
         0 lst))

(define (square-all lst)
  (foldr (lambda (element next)
           (cons (expt element 2) next))
         empty lst))

(define (only-numbers lst)
  (foldr (lambda (element next)
           (if (number? element)
               (cons element next)
               next))
         empty lst))

This pattern can be used whenever you are writing a function that processes all the elements of a list, one by one. Usually, you would use the element's value to compute the result, but it's not always necessary; for example, you can implement length like this:

(define (length lst)
  (foldr (lambda (element next)
           (+ next 1))
         0 lst))

Putting all this together

All the above is a very roundabout way to say that the splitting function you're trying to write is also a right-fold operation. It looks like this:

(define (split-by lst x)
  (foldr (lambda (element next)
           (if (eqv? element x)
               (cons empty next)
               (cons (cons element (first next)) (rest next))))
         (list empty) lst))

Let's break this down:

Base case: If the incoming list is empty, return a list with an empty sublist inside.
Recursive case: If the incoming list is not empty, consider the first element:

If that element is equivalent (eqv?) to the splitter, then prepend an empty sublist to the next result.
Otherwise, prepend the element to the frontmost sublist of the next result.

The code is quite dense, but I intentionally wrote it the way a seasoned Schemer would write it (except that it's more common to write car, cdr, null?, and '() instead of first, rest, empty?, and empty). It may take you a while to unpack all this information, if you're new to Scheme. Please feel free to ask for any clarifications.


Multiple nav elements

While multiple nav elements are allowed for any given section, it looks dirty to me.  Consider using a single nav instead.  If you need an extra element as a style hook, then use div or section.

Duplicate content

Having content that is only visible to mobile users and similar content that's only visible for desktop users is code smell.  This one is extra bad because it uses identical markup for both.  Just use one set of markup and have CSS style it differently depending on the viewport.

Using px for the width of text elements

Text is not something you as a designer have any control over, all you can do is make suggestions.  An element that's 210px wide might look good for text that's 16px Times, but what happens when the user has specified that they need 20px Segoe because their eyesight isn't as good as it used to be?  Using em/rem is a better choice in most situations.

Using px for media queries

When you use px for your media queries, they'll fall apart when you start zooming (not sure if this is still the case).  Using ems are more reliable, especially if you're following my last point.

See also: http://bradfrost.com/blog/post/7-habits-of-highly-effective-media-queries/

Redundancy

When you float an element, most display values are ignored, including inline.

.main-nav ul li {
    display: inline;
    padding-left: 28px;
    float: right;
}

On a relatively positioned element, a top/right/bottom/left value of 0 does nothing.  I don't see anywhere where this is overriding a previous setting either.

.menu {
    overflow-x: hidden;
    position: relative;
    right: 0;
}


After revisiting this, and even though I prefer to handle tasks like this with node, it is possible to write a bash script using curl, and/or xpath that accomplishes this same task. The ratings could filtered with a regex pattern within grep just to lay down a few ideas. Again, this is just an alternative solution.


I encourage you to abandon your present approach.

Instead, try expressing each of your A/B/C/D proteins as integer numbers. Then express those integer numbers in binary form, and see if you can determine the operation(s) underlying the very, very regular pattern visible in the table given in the problem.

If you transcode the "protein sequences" to a series of 2-bit numbers, I believe you can profitably perform your mutations at a high rate of speed.


I'm learning Java too!

Looking at this the only thing I might suggest is that you only do the calculations that you need to. You could then remove all answer variables and print the result of the calculations directly, saving time and memory, albeit not much.

In terms of presentation, I personally would use lowerCamelCase for variable naming, e.g. firstNum, and I would also indent all of the cases as they are within the switch block. Finally, for input. nextDouble(); I'd make sure there was no space there.

Despite what I say for the presentation, that part of it is totally up to you, so do what you prefer, as long as it looks clear!


I ran your code and it ran in 1397 milliseconds, so that's not something to worry about. However, there is something very inefficient about your code: you calculate Factorial for every digit you encounter.
Calculate them in advance.

You have declared your sum variable inside the Factorial(i) method as an int, while the return type is long. However, you are never dealing with a long value, so you can just change the return type to int.
(You're only calculating up to 9!, which fits well within the range for int)

Also, converting each number to a string and back again is kinda slow too.

class Euler034
{
    //Calculate the factorials in advance and just look them up.
    private static readonly int[] fact = Enumerable.Range(0, 10).Select(Factorial).ToArray();
    private static readonly int max = fact[9] * 7;

    public static void Main()
    {
        //Convenient method for creating and starting a Stopwatch
        Stopwatch watch = Stopwatch.StartNew();
        int sum = 0;
        for (int i = 4; i <= max; i++) {
            if (IsCuriousNumber(i)) sum += i;
        }
        watch.Stop();
        Console.WriteLine(sum);
        Console.WriteLine("Time to calculate in milliseconds : {0}", sw.ElapsedMilliseconds);
        Console.ReadKey();
    }

    private bool IsCuriousNumber(int number) {
        return number == Digits(number).Select(i => fact[i]).Sum();
    }

    private static int Factorial(int number)
    {
        int sum = 1;
        for (int i = 1; i <= number; i++) {
            sum *= i;
        }
        return sum;
    }

    private static IEnumerable<int> Digits(int number)
    {
        while (number > 0) {
            yield return number % 10;
            number /= 10;
        }
    }
}


Since you are writing FizzBuzz in assembler, you are obviously concerned about performance and code size.

For performance, div is one of the worst instructions. Since the divisibility repeats modulo 15, you could define some constants:

const divisible_by_3 = 0b1001001001001001
const divisible_by_5 = 0b1000010000100001

To test the divisibility, have an extra register that is initialized with i mod 15 and adjusted whenever i changes. The basic idea is:

dec i
dec i_mod_15
cmovs i_mod_15, 14   ; the maximum value mod 15

You can also combine divisible_by_3 and divisible_by_5 into a bit vector of two-bit entries (divisible) and define a jump table based on that. To do the actual testing, use bit-shifting.

const divisible_by_3 = 0b_1_0_0_1_0_0_1_0_0_1_0_0_1_0_0_1
const divisible_by_5 = 0b1_0_0_0_0_1_0_0_0_0_1_0_0_0_0_1_
const divisible      = 0b11000001001001000001100001000011

Another idea is to use unroll the loop by using Duff's Device.

Right now, your code is a really boring, straight-forward translation of some higher-level language, probably C. In assembler, you have much more potential to compress the code (DRY principle). For example, you can jmp do_printf instead of writing push ecx; call printf; pop ecx several times.

… 90 minutes later …

Based on the above ideas, the code might look like this, tested and works.

format PE console
entry main

include 'macro/import32.inc'

section '.rdata' data readable

; Each of these messages takes exactly 8 bytes,
; except for the last one.
; This is important for addressing them efficiently.
messages db '%d', 13, 10, 0, 0, 0, 0
         db 'Fizz', 13, 10, 0, 0
         db 'Buzz', 13, 10, 0, 0
         db 'FizzBuzz', 13, 10, 0

; This bit mask selects one of the above messages
; to be printed. The counter is always passed to
; printf, and in 8/15 cases it is ignored.
; The uu entry at the end is unused.
;
;                0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
; div3 mask =    1  0  0  1  0  0  1  0  0  1  0  0  1  0  0  u
; div5 mask =   1  0  0  0  0  1  0  0  0  0  1  0  0  0  0  u
div_mask =      11_00_00_01_00_10_01_00_00_01_10_00_01_00_00_00b

section '.text' code readable

main:
        push ebp
        mov ebp, esp

        mov ecx, 100            ; ecx = the counter
        mov eax, ecx
        xor edx, edx
        mov ebx, 15
        div ebx                 ; edx = counter mod 15

        mov ebx, div_mask       ; ebx = bit mask for selecting the message
        rol ebx, 2
        xchg edx, ecx           ; Variable-width rotation is only possible
        rol ebx, cl             ; with cl, therefore the temporary swap
        rol ebx, cl             ; of edx and ecx.
        xchg edx, ecx           ;

.again:
        mov eax, ebx            ; Select the message format for printf.
        and eax, 11b
        shl eax, 3
        add eax, messages

        push ebx                ; save registers before printf
        push ecx
        push edx

        push ecx                ; actually call printf
        push eax
        call [printf]
        add esp, 8

        pop edx                 ; restore registers after printf
        pop ecx
        pop ebx

        dec edx                 ; Adjust counter, counter mod 15
        jns .normal             ; and bit mask.
        add edx, 15
        ror ebx, 2              ; Rotate one extra time since
.normal:                        ; the bit mask has 16 entries.
        ror ebx, 2

        dec ecx
        jnz .again

        xor eax, eax
        pop ebp
        ret

section '.idata' import data readable

library msvcrt, 'msvcrt.dll'

import msvcrt, printf, 'printf', system, 'system'

Some more things I took care of:

The code must not be in a writeable section.
Since the program can return from main, it should do so. To make that work, I had to add the pop ebp that corresponds to the push ebp at the very top; in your code that was missing.
I carefully avoided many branching statements, since they are poisonous to performance. See Why is it faster to process a sorted array.
The one remaining conditional behaves well in that it follows the jump in 14/15 cases, which is easily predictable.
Of course, using printf and the C stdio for output ruins all performance effects. But that's outside the scope for this little fun experiment.
All arguments to printf may be modified by printf. There's no guarantee that you get your ecx back at the point where you commented ; Get the counter back into ecx. To hide the counter from printf, you must push it once more to the stack. That's why I explicitly commented on this saving/calling/restoring in my code.

A nice thing is that you can play with the bit mask, which feels just like an ordinary configuration file.


Couple of Points.

Most Important: If your looking for secure password storage do not write your own library. Password storage is a very complex at best pratice. So I you care about the contents of the plain text password file being accessed don't do this.

If this is a learning exercise or not that critical go ahead, just keep that in mind.

Now for the actual review.

First thing that grabs me is if you are using Java 7 then you should
look at using try with resources. Try with resources has two
advantages for your code. First it always closes the streams (Under
normal jvm operation) secondly it is a little less verbose to write.

Basic syntax would be :

        try (PrintWriter pw = new PrintWriter(new BufferedWriter(
                new FileWriter("c:/" + name + ".dnx")));)
        {
        //Rest of code here.
        catch (IOException e)
        {
            e.printStackTrace();
        }

This eliminates the need for a lot of the closing resources.

Second problem you open a File reference that is never used. Remove all occurences of fop and file.
Consider moving the two "cases" to seperate methods. They are seperate things and don't need to share blocks.
I'm not convinced as your printing the stack trace anyway if there is any need to catch the exceptions. Let the method just throw them (Note this is only because this is a self contained program I'm suggesting this.

EDIT:

This is a first stab at refactoring. I've followed my advise above then further more there are three places where your writing a key and value into a stream followed by a blank line. I've moved that to a seperate method. I've also added in your pattern for user input to a method. Hopefully you find this shorter and not too hard to read.

There are a few other points that came up when I was doing this but their not so important.

Class Name: Your class doesn't follow java naming conventions.
All in Main: If the objective is to practice with java please note that this isn't very object orientated. The standard java idiom would be to create a class (possibly an instance of itself) and set the values you want on this for example no need to pass scanner and pw arround as I have done in my refactor.
Naming no huge deal but you should consider more meaningful names for variables "string" I'm looking at you.

import java.io.*;
import java.util.*;

public class testing_file {
    public static void main(String args[]) throws IOException {

        Scanner input = new Scanner(System.in);
        String select = prompt(input, "Access or create?");

        switch (select) {
            case "Create":
                createPasswordEntry(input);
                break;

            case "Access":
                readPasswordFile(input);
                break;

            default:
                System.out.println("Invalid method, terminating program");
                break;
        }
    }

    private static String prompt(Scanner input, String question) {
        System.out.println(question);
        return input.nextLine();
    }

    private static void readPasswordFile(Scanner input) throws IOException {
        String name = prompt(input, "Enter the account you wish to view");

        //reading
        try (
                InputStream ips = new FileInputStream("C:/" + name + ".dnx");
                InputStreamReader ipsr = new InputStreamReader(ips);
                BufferedReader br = new BufferedReader(ipsr);
        ) {
            String line, string = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                string += line + "\n";
            }
        }
    }

    private static void createPasswordEntry(Scanner input) throws IOException {
        String name, user, password;
        name = prompt(input, "What account is this for?");
        user = prompt(input, "Enter the Username");

        try (
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:/" + name + ".dnx")));
        ) {
            password = prompt(input, "You may now input your password");
            writeKeyValue(pw, "Account", name);
            writeKeyValue(pw, "Username: ", user);
            writeKeyValue(pw, "Password", password);
            pw.flush();
            pw.close();
            System.out.println("Operation Complete");
        }
    }

    private static void writeKeyValue(PrintWriter pw, String key, String name) {
        pw.write(key + ": " + name);
        pw.println();
    }
}


check if two elements exist in array with older browser support

From a short look

foo is a terrible name

If this is not the real name, then please do submit the real code

arr seems to be a global, bad practice
You don't need current, you could just go for var id = arr[i].id;
For older browsers, it is faster to cache arr.length instead of retrieving it every time
bar is a terrible name, I really hope you don't write production code like that
the call to bar should probably happen outside of that function

Given that, I would go for the below pseudo code:

function arrayHasBothObjects(list, id1, id2){
    var boolOne = false,
        boolTwo = false,
        size = list.length;

    for (var i = 0; i < size; i++) {
        var id = list[i].id;

        boolOne = boolOne || id == id1;
        boolTwo = boolTwo || id == id2;

        if(boolOne && boolTwo){
            return true;
        }
    }
    return false;
}


You want to be careful with setInterval() and setTimeout(), because javascript runs in only a single thread if the event loop is busy it won't fire the code in setInterval() or setTimeout() exactly as expected.  This means your timer could take longer than you expected.

Instead of starting with a counter and decrementing on each interval, you can calculate a time difference and then use setInterval() to refresh the frontend.  This will be more accurate.

The following code calculates a completion date and then can calculate how many seconds are remaining.

    //sets a completion date 60 seconds into the future
    // Date.getTime() returns the time in milliseconds
    var completion = new Date(new Date().getTime() + 60000),
    function calculateSecondsRemaining() {
        var now = new Date(),
            //Math.max is used to prevent negative numbers from being returned
            differenceInMilliseconds = Math.max(0, completion.getTime() - now.getTime()),
            differenceInSeconds = Math.floor(differenceInMilliseconds / MILLISECONDS_IN_SECOND);
        return differenceInSeconds;
    }

calculateSecondsRemaining() handles the complex logic that was once in cro(), but I feel that is is more readable.  When dealing with time and numbers, tracking each digit can be tedious.  I prefer to not deal with it at that level.

I prefer to split logic into multiple functions so that the code is more readable.  In your code what jumped out at me is three different bits of logic, calculateSecondsRemaining(), updateDisplay(), and formatNumberTo2Places().  By spliting the functions up, the logic within your setInterval() is very small and very easy to understand.

As a final note, once your timer hits zero, the interval no longer needs to fire.  The following code cancel the interval using clearInterval() once the timer has reached zero.

  var refreshIntervalId = setInterval(function () {
        var secondsRemaining = calculateSecondsRemaining();
        updateDisplay(secondsRemaining);
        if (secondsRemaining <= 0) {
            //clear timer once time expired
            clearInterval(refreshIntervalId);
        }
    }, 1000);

All Together

The following is wrapped in a self-invoking anonymous function to prevent spilling code into the global scope.

(function (window, document, undefined) {
    var MILLISECONDS_IN_SECOND = 1000,
        SECONDS_IN_MINUTE = 60,
        timerLength = 60, //seconds
        start = new Date(),
        completion = new Date(start.getTime() + (timerLength * MILLISECONDS_IN_SECOND)),
        pentruminut = document.createElement('span');

    // add elements
    document.body.appendChild(pentruminut);

    function formatNumberTo2Places(n) {
        //this assumes 1 or 2 digit positive numbers
        var buffer = (n > 9) ? "" : "0";
        return buffer + n;
    }

    function calculateSecondsRemaining() {
        var now = new Date(),
            //Math.max is used to prevent negative numbers from being returned
            differenceInMilliseconds = Math.max(0, completion.getTime() - now.getTime()),
            differenceInSeconds = Math.floor(differenceInMilliseconds / MILLISECONDS_IN_SECOND);
        return differenceInSeconds;
    }

    function updateDisplay(secondsRemaining) {
        var minutes = Math.floor(secondsRemaining / SECONDS_IN_MINUTE),
            seconds = Math.floor(secondsRemaining % SECONDS_IN_MINUTE);
        pentruminut.innerHTML = formatNumberTo2Places(minutes) + ":" + formatNumberTo2Places(seconds);
    }

    window.onload = function () {
        var refreshIntervalId = setInterval(function () {
            var secondsRemaining = calculateSecondsRemaining();
            updateDisplay(secondsRemaining);
            if (secondsRemaining <= 0) {
                //clear timer once time expired
                clearInterval(refreshIntervalId);
            }
        }, 1 * MILLISECONDS_IN_SECOND);
    };
}(window, document));


I would change your Character.__init__ to this:

def __init__(self, **kwargs):
    for key, value in kwargs.iteritems():
        setattr(self, key, value)

It isn't any shorter but it's more clear what's happening.
For one thing, i is not a descriptive name by any means.  For another thing, you might as well iterate through key-value pairs1 rather than just keys.  You use both; why not iterate through both?

I would also change your other __init__ methods.  If Character.__init__ sets attributes, why not take advantage of it?  Instead of self.canRange = ..., add canRange=... to the arguments to Character.__init__.

That brings me to something else.  PEP 8, the Python style guide, says this about instance variables (such as canRange):

  Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

1 You could also do self.__dict__.update(kwargs) but that isn't recommended and seems hackish to me anyway.


kotlinify getViewModel

I would change

protected fun <T: ViewModel>getViewModel(c: Class<T>): T
            = ViewModelProviders.of(activity)[c]
}
//with
protected fun <T: ViewModel>getViewModel(c: KClass<T>): T
            = ViewModelProviders.of(activity)[c.java]
}

after replacing the Class with KClass in the activity, you can use the kotlin ones instead of the java-ones.

then you can use:

private typealias RVM = RotateViewModel
private typealias CVM = CropViewModel
class CropFragment: BaseFragmentInOut<CVM, RVM>(CVM::class, RVM::class) {
    ...
}

second example

In your second example, you tell me you must do everything in the Cropfragment.
This isn't true as your Basefragment can have those fields and the parent can set them.

abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel : BaseFragment() {
    protected lateinit var inViewModel: InVM
    protected lateinit var outViewModel: OutVM
    fun getInBitmap(): Bitmap = inViewModel.bitmap
    fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        inViewModel = getViewModel(c1)
        outViewModel = getViewModel(c2)
    }
}

and in your CropFragment:

class CropFragment: BaseFragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        inViewModel = getViewModel()   //changes the field in BaseFragment
        outViewModel = getViewModel() //changes the field in BaseFragment
    }
}

template method

If you don't want to have onViewCreated in the basefragment or you want to de other things after having set the viewmodels in onViewCreated in the basefragment, use a template method:

create an abstract method in the super-class that should do what you want... In this case create the ViewModels

abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel : BaseFragment() {
    abstract fun createInViewModel() : InVM
    abstract fun createOutViewModel() : OutVM

    @CallSuper
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        inViewModel = createInViewModel()
        outViewModel = createOutViewModel()
    }
}

your sub-class is then forced to implement them:

class CropFragment: BaseFragment() {
    override fun createInViewModel() = getViewModel()
    override fun createOutViewModel() = getViewModel()
}

to much?

You can of course also combine both the template methods to one called createViewModels.
Then you can create a helper-function in BaseFragmentInOut:

protected inline fun <reified I : InVM, reified O : OutVM>  initialize(){
    inViewModel = getViewModel(I::class)
    outViewModel = getViewModel(O::class)
}

The only thing you have to do at that moment is to implement createViewModels the following way:

override fun createViewModels() = initialize<RVM, CVM>()

At the moment it's not possinle to remove RVM and CVM from the initialize, but it's on the table


php one-time prepared statement execution function

I tested your code and it does work, so far, so good. This type of code has been written many times, so by searching online you can find a lot of good examples.

The main problem I have with your code is that it is rather difficult to understand. I can work it out, but it is not obvious. Starting with prepending the $params with something, then the very weird: $params[$i] = &$params[$i] loop, followed by the usage of ReflectionMethod normally used for reverse-engineering code.

I prefer more down to earth code for a simple function like this. Something like:

function executeQuery($mysqli, $query, $parameters)
{
    $stmt = $mysqli->stmt_init();
    if ($stmt->prepare($query)) {
        $types = str_repeat("s", count($parameters));
        if ($stmt->bind_param($types, ...$parameters)) {
            if ($stmt->execute()) {
                return $stmt->get_result();
            }
        }
    }
    return ['error' => $stmt->error];
}

Short and sweet. Some notes:

I try to use a function name that actually reflects what the function does.
I supply the database connection as an argument, for more flexibility. You can use multiple database connections and they don't need to be in the global scope.
I check whether the query could be properly prepared.
My code differs quite a bit from your code when it comes to binding the parameters. As you can see this is quite straightforward. Using ... to access variable arguments has been available since PHP 5.6 which came out in 2014.
By directly returning the results when the execution was successful I know that an error must have occurred when the last line of the function is executed. This therefore also catches other problems.

Personally I would not have expected to get a MySQLi result object out of this function. Because it will always have to be processed. Why not do this processing inside this function? Like this:

function executeQuery($database, $query, $parameters)
{
    $stmt = $database->stmt_init();
    if ($stmt->prepare($query)) {
        $types = str_repeat("s", count($parameters));
        if ($stmt->bind_param($types, ...$parameters)) {
            if ($stmt->execute()) {
                if ($result = $stmt->get_result()) {
                    $rows = [];
                    while ($row = $result->fetch_assoc()) {
                        $rows[] = $row;
                    }
                    return $rows;
                }
            }
        }
    }
    return ['error' => $stmt->error];
}

Now you simply get an array back. I agree that is not much different from returning a MySQLi result, but I am thinking ahead. Suppose you decide to change over from MySQLi to PDO in the future. You can easily recode the function above to work with PDO, but recoding the handling of MySQLi results everywhere in your code will be a lot harder. So I am using the function to abstract away from a particular database interface.

Some people don't like the deep nesting of if () {} blocks. To prevent this you could instead write something, like the code below, for all these blocks:

 if (!$stmt->prepare($query)) {
     return ['error' => $stmt->error];
 }

I have to repeat that there are lots of ways of doing this. The answer I gave is based on the code you presented. It is, for instance, not hard to find out the type of the parameters, and adjust the $types string accordingly.


Printing characters in a matrix as a string

I would suggest to create a 1000x1000 testcase and measure the performance before the optimization process. Please use the following test generator:

import os
import random

f = open('1000x1000.in','w')
f.write('1000 1000\n')
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(1000):
       f.write(''.join([ALPHABET[random.randint(0, len(ALPHABET)-1)] for _ in range(1000)]) + '\n')
f.close()

After that just run it and measure the performance of your application. I got about 47 ms on my pretty old C2D E7200.


Not essential but I would find it neater to make a function that translates a single word, then join those together. You should also deal with the case of a word containing no vowels or 'y', which currently gets your programme stuck in an infinite loop.

def get_pig_latin(string):
    return ' '.join(map(translate_word, string.split(' '))).upper()

def translate_word(word):
    vowels = "aeiou"
    if len(word) < 2 or word[0] in vowels:
        return word + 'tay'
    elif contains_any(word, vowels + 'y'):
        while word[0] not in (vowels + 'y'):
            word = word[1:] + word[0]
        return word + 'ay'
    else:
        return '???'

Then add docstrings to your functions.

EDIT: It might be better to use a for loop instead...

def translate_word(word):
    if len(word) < 2 or word[0] in 'aeiou':
        return word + 'tay'
    for i, ch in enumerate(word):
        if ch in 'aeiouy':
            return word[i:] + word[:i] + 'ay'
    return '???'

You could also consider building the string validation into your translation function with a user-defined exception:

class TranslationError(Exception):
    def __init__(self, value):
        self.value = value

def translate(word):
    if word.isalpha():
        if len(word) < 2 or word[0] in 'aeiou':
            return word + 'tay'
        for i, ch in enumerate(word):
            if ch in 'aeiouy':
                return word[i:] + word[:i] + 'ay'
    # if there is no aeiouy or word is not alphabetic, raise an error
    raise TranslationError(word)

def run():
    commands = { "-h" : print_help,
                 "-x" : exit }
    print_title()
    while True:
        inp = raw_input(":: ").strip().lower()
        if inp in commands:
            commands[inp]()
        else:
            try:
                translation = ' '.join(map(translate, inp.split(' '))).upper()
                print("-> " + translation + "\n")
            except TranslationError as e:
                print("   Unable to translate:" + e.value + ".\n")


I think this is pretty good code!  I have only a few minor suggestions:

Rename image and images to something that makes clear they are URLs, not files, not numpy ndarrays, and not any other format.  Maybe image_url and image_url_list?  The first time I read the code I didn't know what they were.  Your docstrings are good, but IMO, its even more Pythonic to have your code speak for itself (with docstrings present as backup obviously).
It took me several times of reading the code to figure out exactly what need_reload_file is.  Could you name it to be more descriptive?  Maybe failed_image_urls_file or something?
Web programmers might know what various request status codes mean, but in case a web noob like me reads your code, a comment explaining the meaning of r.status_code == 200 would be helpful.
I don't understand the file_name.split('=')[-1] bit.  What constraint are you assuming about the structure of file names?


Formatting

formatting inside your foreach should be indented

This:

        foreach (Earning e in earningList)
        {

// Sum all earnings...

        var totalEarnings = earningList[i].AmountForEPF + earningList[i].OverTimeAmount + earningList[i].IncentiveAllowance + earningList[i].SpecialAllowance + earningList[i].OtherAllowance + earningList[i].ExtraShiftAmount + earningList[i].BroughtForwardAmount;

Should look like this

        foreach (Earning e in earningList)
        {
            // Sum all earnings...
            var totalEarnings = earningList[i].AmountForEPF + earningList[i].OverTimeAmount + earningList[i].IncentiveAllowance + earningList[i].SpecialAllowance + earningList[i].OtherAllowance + earningList[i].ExtraShiftAmount + earningList[i].BroughtForwardAmount;
            ...
        }

When you are adding things together (either in concatenation or variable addition) you can multi-line the expression because C# is awesome and isn't NewLine Terminated, so this:

  var totalDeductions = deductionList[i].AdvanceAmount + deductionList[i].CarriedForwardAmount + deductionList[i].DeathDonationAmount + deductionList[i].EPFAmount + deductionList[i].FineAmount + deductionList[i].InsuranceInstalmentAmount + deductionList[i].LoanInstalmentAmount + deductionList[i].MealsAmount + deductionList[i].OtherDeductionAmount + deductionList[i].UniformInstalmentAmount + deductionList[i].WelfareAmount;

can be easier read when written like this:

  var totalDeductions = deductionList[i].AdvanceAmount +
      deductionList[i].CarriedForwardAmount +
      deductionList[i].DeathDonationAmount +
      deductionList[i].EPFAmount +
      deductionList[i].FineAmount +
      deductionList[i].InsuranceInstalmentAmount +
      deductionList[i].LoanInstalmentAmount +
      deductionList[i].MealsAmount +
      deductionList[i].OtherDeductionAmount +
      deductionList[i].UniformInstalmentAmount +
      deductionList[i].WelfareAmount;

I am looking into making this easier to do as well,  that just looks messy

Organization

The more that I look at your code, there are more things that I would change.

your Deduction and Earning objects are created and maintained by your WageInfo class  so really you should be using a wageInfoList  and each item in that list will have one Deduction object and one Earning object

This means that the WageInfo object should have all the information to hand off to the WageManager.  The WageManager shouldn't directly see the Deduction or Earning objects that live in the WageInfo Object that is called by the WageManager.


GLSL atomic float add for architectures with out atomic float add

I did not realize what atomicCompSwap did nor that it was common for this kind of usecase: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/atomicCompSwap.xhtml .  This function handles the case of the loaded value for MEM being read incorrectly, this check is automatically handled via the function itself, and simplifies the code.  Using the original value of memory we can verify if our assumptions about what we should be adding to are correct:
#define atomicAddFloatX(MEM, INDATA)      \
{                                         \
    uint expected_mem = MEM;              \
    float input_mem = (uintBitsToFloat(MEM) + INDATA); \  //initially this is what we assume we want to put in here.
    uint returned_mem = atomicCompSwap(MEM, expected_mem, floatBitsToUint(input_mem)); \ //if data returned is what we expected it to be, we're good, we added to it successfully
    while(returned_mem != expected_mem){ \ // if the data returned is something different, we know another thread completed its transaction, so we'll have to add to that instead.
        expected_mem = returned_mem; \
        input_mem = (uintBitsToFloat(expected_mem) + INDATA) \
        returned_mem = atomicCompSwap(MEM, expected_mem, floatBitsToUint(input_mem)); \
    } \
}

Basically the code I wrote before was attempting to do something like this, but more confusing and a much less safe way.


Enumerating smart card terminals asynchronously in ViewModel constructor

I saw that you use in your test async/await, so you can do the GetClassUnderTest in the same way. Return a Task and wait for it asynchronously.

Also you can change the inner while and Thread.Sleep to something else.
I'd change the PopulateTerminals to public (it doesn't change any inner state except for the Terminals collection and you can do a check before the population that verify if is already populated) and then from your test call it.

I think make it public is the best way, but if you prefer not to do it, consider to use some signal to indicate about IsLoading and not do a useless while.

I don't like that EnumerateTerminals returns IEnumerable<ITerminal>. I don't know what is the logic of the enumerating, but I guess you return List from there so change also the return value to Task<List<ITerminal>>. If you indeed return IEnumerable, this can be a problem because the laziness.

In the VM why is your collection ICollection and not ObservableCollection? If you do it purposely for some reason (sorting) it's OK but if not change it to concrete type (its clearer and avoid conversions).

The ITerminalFactory can be injected to VM as property for example and then you don't need to pass it to populate the collection.


Create a simple hangman game using OOP and Javascript

Good things

The code appears to function properly.
The code makes good use of strict equality operators and functional techniques like using .every().
const is used for most variables.
Prototypes are used properly.

Suggested changes
Strict mode flaw
Strict mode is enabled with the string literal:
"use strict";

Yet the first line of the two JS files is

"strict";

Variable declarations
Some variables declared with let could be declared with const since they are not re-assigned - e.g. puzzle since it is never re-assigned. Using const instead of let helps avoid accidental re-assignment and other bugs.
status values
The values for status could be stored in constants - e.g.
const STATUS_FAILED = 'Failed';
const STATUS_PLAYING = 'Playing';
// ... etc...

Then those can be used in the code- e.g. instead of

this.status = "Playing";

it can use the constant:
this.status = STATUS_PLAYING;

Those could also be stored in "an enum"
const STATUS_VALUES = Object.freeze({ FAILED: 0, PLAYING: 1, FINISHED: 2});

With this approach, there is no risk of mistyping the values throughout the code, and if a value needs to be updated, it can be done in one place.
Selecting elements
It isn't wrong to use querySelector to get elements by id but using getElementById() "is definitely faster" 1 (see this jsPerf test for comparison).
ES-6 class syntax
The code could be converted to the newer ES6 class syntax - bear in mind that it is "primarily syntactical sugar over JavaScript's existing prototype-based inheritance". If there were many subclasses then it would help simplify setting up the prototypal inheritance.


Reorder a list in Python to avoid repeats

Ideally a function will return a particular type of value. Python may be dynamic and allow you to return anything, but it's less surprising behaviour if you don't return two types of value. Instead, consider returning None or an empty list. Both of which will still evaluate as False when tested because of Python's truthiness. I'd personally suggest None, as an empty list might be mistaken for a useable list. Python will automatically use None as the return value in the absence of any other argument, so just using return returns None.

You should use snake_case for naming variables and functions, so checkRepeat should be check_repeat. I also don't like lst as a name. It's good that you're avoiding shadowing the built in list, but lst is unclear and can look like 1st. Perhaps iterable or source could be better names.

hasRepeat doesn't need to be a nested function, you could have it separated as it's own. Having it nested implies that you're trying to do a more complicated structure when really it's just because you call hasRepeat in checkRepeat. Also, checkRepeat isn't a good name as it's actually removing repeating values (if it can). Instead perhaps something like reorder_repeats? It would not be the clearest name because it's not an easy process to describe, but the docstring can provide help there too.

You should have spaces either side of your mathermatical operators, it makes them more readable and is recommended by the style guide. So this:

offset=numIter=0

should be this:

offset = numIter = 0

Also try to avoid inline comments, they make lines exceedingly long. They should be used sparingly for short comments. If your comment is a sentence it will almost always need its own line. The style guide also says to keep below 79 characters per line, which this comment invalidates:

if Counter(lst).most_common()[0][1]*2 > len(lst)+1: #checks if it will be impossible to find a working order

Split it onto the line above and it's much more readable.

# Check if it will be impossible to find a working order
if Counter(lst).most_common()[0][1] * 2 > len(lst) + 1:

Instead of curElt try the name element or item. Shortened words often make for odd names that people can easily interpret differently to you. Except that you don't end up using this value at all. Instead you access elements by their index, which I personally think is more readable in this case and better, but then you could just loop with this:

    for i in range(len(source)):

What's the point of numIter? It's the exact same value of offset but never even used? If it was a testing value you should remove it now. While we're on it, I don't entirely understand offset, a comment about it would be helpful when you're incrementing the values.

Don't use a bare except. It's very bad practice because you might ignore all sorts of errors that you should really be paying attention to. In this case, it seems like IndexError is what you're expectin to happen, so use that specifically.

The line where you swap values is too long and hard to read, instead you should calculate the index of your second value on the line before:

            if lst[i] == lst[i+1]:
                index = (i + offset) % len(lst)  # Wrap around the list
                lst[i+1], lst[index] = lst[index], lst[i+1]

Now that it's clear that index is the same value on either side, it's obvious that you're swapping values. You can make this comment inline since it's a brief note about the meaning of an unusual calculation.

Here's how I'd put the script together:

from itertools import groupby
from collections import Counter

def has_repeat(source):
    """Returns true if there are any repeats"""

    return len([x[0] for x in groupby(source)]) < len(source)

def check_repeat(source):
    """Returns a list that has no repeating elements or None if such a list can't be found"""

    # Check if it will be impossible to find a working order
    if Counter(source).most_common()[0][1] * 2 > len(source) + 1:
        return

    offset = 0
    while has_repeat(source):
        for i in range(len(source)):
            try:
                if source[i] == source[i+1]:
                    index = (i + offset) % len(source)  # Wrap around the list
                    source[i+1], source[index] = source[index], source[i+1]
            except IndexError:
                break
        offset += 1
    return source


Conciseness

Python overloads operators, that is * works differently for numbers or numbers and strings. You can use it to shorten some functions of yours:

def makeSpace(num):
    return " " * 7 * num

def makeFloor(num):
    return "*" * 7 * (num + 1)

Global typo

white_space5 = makeSpace(Num - num2)
                         ^

That n should be lowercase as uppercase it refers to a global and referring to a global variable from a function is very bad.

Use your functions

You can use makeSpace once more in render:

def render(num, num3):
    num2 = num - 1
    white_space7 = ""

    white_space = makeSpace(num)
    white_space5 = makeSpace(num - num2)
    # ...

The same goes for the top level code (that should be put in a main function for modularity)

def main():

    Num = raw_input("Number of Stairs:" )
    Num = int(Num)

    white_space2 = makeSpace(Num + 1)
    print(white_space2 + "*******")
    # ...

Variable names

Naming the variables and arguments num or num3 or Num is a very bad idea as it does not tell me about the meaning of what is contained inside.
 I suggest, Num -> staircase_height as an example but all the names can and should be improved.

Avoid reassigning the same variable

You re-assign white_space7 and that gave me headaches when refactoring, reassigning is generally avoided in Python.

Simplify branching

The printing part in render:

print(white_space + "      *" + white_space5 + "*")
print(white_space + "   o  *" + white_space5 + "*")
print(white_space + "  /|\ *" + white_space5 + "*")
print(white_space + "  / \ *" + white_space5 + "*")
if num3 != 0:
    print(white_space + "*******" + white_space7 + "*")
else:
    print(white_space + "*******" + white_space5 + "*")

Extract common code out of branches.

and

for x in range(staircase_height - 1):
    render(staircase_height - x, 0)
render(staircase_height - (x + 1), staircase_height - 1)

Use less variables

You can use a simple subtraction in the loop to easily avoid the y variable:

for x in range(staircase_height):
    if (x < staircase_height - 1):
        render(staircase_height - x,0)
    else:
        render(staircase_height - x,staircase_height - 1)

and:

print(makeSpace(staircase_height + 1) + ("*" * 7))

Further simplify render

Simply right_pad  = makeSpace(1), not the long winded expression that always evaluated to one.


Scan files and pick overlapped hex codes

Repeating the match can be avoided by storing it in a variable first:

match = re.search(r'^0[xX][0-9a-fA-F]+', line)
if match:
    event_codes.add(match.group())

Note also that you don't need to strip a trailing \, because it is ignored afterwards anyways and you are only interested in hex codes at the beginnings of the line and all your multilines seem to have some whitespace at the beginning of the continued line. Note that you could have used re.match(r'0[xX][0-9a-fA-F]+', line), instead of re.search, because it always matches only the beginning of the line.

Python also caches your regex, once you have used it, but you may still squeeze out a bit of performance with re.compile.

I also used the match.group() method, which immediately returns the matching part if the string.

I would also not suggest caching the file content of all the files in the directories. This seems like a huge waste of memory. Instead process them one at a time and add it to your event code sets, or even better, just generate a stream of event codes that you can consume with set:

import os
import sys
import re

def event_codes_file(path):
    with open(path) as file:
        for line in file:
            match = re.match(r'0[xX][0-9a-fA-F]+', line)
            if match:
                yield match.group()

def event_codes_dir(dir):
    for root, dirs, files in os.walk(dir):
        for name in files:
            if name.endswith('Efile'):
                path = os.path.join(root, name)
                yield from event_codes_file(path)

if __name__ == "__main__":
    event_codes1 = set(event_codes_dir(sys.argv[1]))
    event_codes2 = set(event_codes_dir(sys.argv[2]))

    overlap_event_codes = event_codes1 & event_codes2
    print(overlap_event_codes)

yield from x was introduced in Python 3.3 and is mostly equivalent to for i in x: yield i.

Also note that name in ('Efile') is almost the same as name == 'Efile', but matches a bit more (like 'E'). Unless of course you meant what you wrote in process_cache, name.endswith('Efile'). I am assuming the latter.

On a file "test", containing your example content, this produces:

set(event_codes_file("test"))
# {'0x00010d35', '0x04b60ff6', '0x84900c5'}


Assignment function as alternative to std::tie

This "idiom" seems strictly more confusing than the std::tie(a,b,c) = std::make_tuple(1,2,3) idiom. (I mean, the latter is an idiom because multiple people use it and know it. Your thing doesn't count as an idiom yet because nobody uses or understands it.)
Your thing does save a lot of template instantiations — you don't have to instantiate std::tuple at all, for example. That's potentially nice for people who are doing lots of multiple assignments in header files and care about compile times. But who's doing lots of multiple assignments in header files??
Your thing doesn't fix the most important shortcoming of std::tie, which is that you can't use it to introduce a new variable. It's still fundamentally a std::cin-style API, where the caller is supposed to define all their variables with garbage values and then use this API to mutate them into the desired state.
// To mutate three variables:

int a, b, c;
assign(a, b, c)(1, 2, 3);
std::tie(a, b, c) = std::tuple{1, 2, 3};  // same deal, easier to read, harder to compile

// To define three new variables (ish):

auto [a, b, c] = std::tuple{1, 2, 3};

"C++17 structured binding that also includes an existing variable" gives the skeleton of an API that could be used to define and mutate different sets of variables at the same time:
// To define one new variable and mutate two others:

auto [a] = AndTie(_1, b, c) = std::tuple{1, 2, 3};

But again, I wouldn't describe this as an "idiom", because if you showed it to an ordinary C++ programmer who knew all the C++ idioms, they likely still wouldn't understand it at a glance.

Oh, and a code-style nit: I would prefer to see your fold-expression with spaces around the , operator, to emphasize that it's an operator and not a separator. Like this:
((a = std::forward<decltype(v)>(v)) , ...);

and in fact as long as we're saving on function template instantiations, let's do
((a = static_cast<decltype(v)>(v)) , ...);

The inner set of parentheses is redundant, I think, but I'm keeping them. (Precisely because I had to say "I think." I'm not even gonna go find out. They're a good idea.)


It's hard to review code that doesn't work per se, but I'll try my hand at a style review anyways.

func Search(re *regexp.Regexp, logs []string) []string

Nice method signature! But, exported function Search should have comment or be unexported. I trust there are docstrings in your code, right? That's valuable stuff, don't omit it here!

var lwg sync.WaitGroup
var lresults = make([]string, 0)
NumCPU := runtime.NumCPU() * 2
var divided = make([][]string, 0)

Personally, I find this kinda hard to read. You should do this instead:

var (
  lwg        sync.WaitGroup
  divided  = make([][]string, 0)
  lresults = make([]string, 0)
  NumCPU   = runtime.NumCPU() * 2
)

So much nicer.
That's the handiwork of my IDE. The Go language distribution comes with a lot of code quality tools for readability and static analysis, and you should really use them often. (Every save, perhaps?)

// Splits the log lines into sub slices based
// on the number of CPUs available.

Yay, comments! /* multiline comments are more readable, though */.

ChunkSize := len(logs) / NumCPU
if ChunkSize == 0 {
    ChunkSize = 0
}

First of all, ChunkSize would ideally be declared in the var () block up there, because it seems like there are no other uses for NumCPU. Go is fastest when you are smart and efficient with your memory, so don't leave variables lying around for no reason.

Second, I find this pointless. Yes, I, too, cry at Go's lack of ternary operator, but it's missing for a reason. That being said, I don't understand why you are setting a variable to what it is... ?

if ChunkSize > 200000 {
    log.Warnf("There are %s lines of logs available. Searching may take awhile.", humanize.Comma(int64(len(logs))))
}

2e5 is more readable and more easily changeable later. Moreover, I don't understand the coersion to int64 here. Does humanize really only like int64? That seems lame.

for ii := range divided {
    lwg.Add(2)
    total := len(divided[ii])
    mid := total / 2
    array := divided[ii]
    first := array[:mid]
    second := array[mid:]
    go func(s []string) {
        for _, xx := range s {
            if re.MatchString(xx) {
                locker.Lock()
                lresults = append(lresults, xx)
                locker.Unlock()
            }
        }
        lwg.Done()
    }(first)
    go func(s []string) {
        for _, xx := range s {
            if re.MatchString(xx) {
                locker.Lock()
                lresults = append(lresults, xx)
                locker.Unlock()
            }
        }
        lwg.Done()
    }(second)
}

Whoa. Alright:

array := divided[ii] is pointlessly cryptic, instead use for e, i := range divided {} and get the element and index that way -- it's cleaner.
Naming. I understand it's hard; I struggle with it too: every coder does. But please, for the love of Go, either use i, index or int_theIndexOfTheFreakinFullyQualifiedStringObjectWeAreIteratingOn. ii is hard to pronounce, not rememberable... I hate it.
As far as I can tell, these variables total, mid, first, second have exactly one use: right here in this loop. Remember what I said about Go being faster when you keep the work for the GC down to a minimum. I get it improves readability, but at a point, that stuff should just be inlined to keep the cache happy.
I see zero difference between these go funcs, because they're identical. Ideally, you would assign it to a local var and call it on first and second.
I can't run your code right now, which means I can't make it testable and I can't ask go race to take a look at it. What I can tell you, from a glance, is that you're accessing the same resources through two goroutines at once. The locker, assuming it does what it says on the tin, is a good thought, but you're still locking them at the same time and it's a recipe for disaster in the form of race conditions. See here, here, here, and the other results from the first page of google results on "avoid race condition golang".

return lresults

This could be a bare return if you put (lresults []string) in the signature, which would in my opinion improve readability both of the code and any generated docs.


Accurately calculating gravity for large systems

Gravity for small distances

I've seen two simple ways that are used to fix this problem:

Add a small amount to each distance:

double d2 = d2(p);

d2 += EPSILON_DIST;

Use a minimum distance:

double d2 = d2(p);

if (d2 < MIN_DIST)
    d2 = MIN_DIST;

Either way will prevent small distances from causing huge accelerations.  Since d2 is in units of distance squared, your EPSILON_DIST and MIN_DIST should also be squared distances.

More efficient gravity computation

Your gravity calculation could be improved a little.  I answered another almost identical question here, so you can take a look at the solution I came up with there.  The main point is that you can reduce the number of divisions to only one in grav() and zero in move().  Although it doesn't exactly match your Particle class, I think you can extrapolate from it.  Here is the code, pasted from that other question:

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

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

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

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


Given a string and a word dict, find all possible sentences

I have figured out how to do this problem and achieve the time and space requirements. It is faster than 64% of submissions but only more space efficient than 5% of submissions (woops). I ended up modifying the code that fails the space requirements. Here is my solution:

class Solution:
    def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':
        from collections import defaultdict

        if not wordDict:
            return []

        wD = set(wordDict)
        childs = defaultdict(list)
        childs[len(s)] = [None]

        for i in range(len(s) - 1, -1, -1):
            for j in range(i + 1, len(s) + 1):
                if s[i:j] in wD and j in childs:
                    childs[i].append(j)

        paths = []

        def dfs(nd, path):
            if nd is None:
                paths.append(path)
                return

            for ch in childs[nd]:
                dfs(ch, ' '.join([path, s[nd:ch]]))

        dfs(0, '')
        return [x.strip() for x in paths]

Any optimizations are still welcome.


Another dynamic array implementation in C

In C, as in C++, object pointers can be freely converted to void*, so quite a few casts can be removed.
It's probably convenient to store data as a char*, since that's how we use it.  We should still use void* as external interface, of course.
This is a dangerous anti-pattern:

            p->data = realloc(p->data, VECTOR_RESERVE_SIZE);

If the realloc() fails, it returns a null pointer.  By overwriting p->data before we check for null, we leak the old value of p->data, which is no longer accessible.  And the null-check is also missing, so subsequent access is Undefined Behaviour.
Style-wise, I think I'd find (!(i > p->used)) easier to read as (i <= p->used).  And if (p->data != NULL) { return false; } else { return true; } as return !p->data;.
The example code should set a good example, and check the return value of vector_init() (and also vector_append() once you realise it needs to indicate success/failure) and react appropriately.  Otherwise, you'll find you're encouraging slapdash usage.


Looks good overall. Some suggestions:

The newton_sqrt is written in a quite generic manner. Unfortunately it may only calculate square roots - because lambdas are defined inside the function. I would rewrite it along the lines of

def newton_raphson(x, x0, func, derivative, governing_options):
    your code verbatim, except the lambda definitions

def newton_sqrt(x, governing_options):
    return newton_raphson(x, x/2, lambda y: y*y - x, lambda y: 2*y, governing_options)

In any case, you most likely want to test for n > 0 and raise InvalidArgiment accordingly.
I am not sure about the epsilon. If an abs(prime) < epsilon condition triggers, the iteration would not converge anyway. I don't see an extra value here, but maybe it is just me.


Add a class to an element when it's loaded

To select the p elements that have an img as child element,
you can use the p:has(> img) selector, like this:

$(".entry-content p:has(> img)").addClass("no-orphans-ctnr");


If the point of the sentinel is to, as the wiki article says:

The basic algorithm above makes two comparisons per iteration: one to check if Li equals T, and the other to check if i still points to a valid index of the list. By adding an extra record Ln to the list (a sentinel value) that equals the target, the second comparison can be eliminated until the end of the search, making the algorithm faster.

Then the approach should be to tack on the value to find onto the end of the array, instead of replacing the last value of the array with the value to find. I guess you can replace the last value, then once a match is found, replace it back, then check it, but that's unnecessarily convoluted.
Your code has a bug: if the first element of the array is the item to search for, while (array1[i] !== x) { will evaluate to false, and the IIFE will terminate immediately without logging anything.
That test is superfluous anyway, since inside the loop, the array item will either be found before the end, or at the end - either way, console.log will be called.
To add an element to the end of an array in JS, it's easier to use push:
array1.push(x);

You might consider using more precise variable names, to make the code more readable. (I'd avoid using single-letter variable names except maybe for i, which is pretty universally understood to be an index.)

const linearSearchSentinel = (array, itemToFind) => {
    const { length } = array;
    array.push(itemToFind);
    for (let i = 0;; i++) {
        if (array[i] === itemToFind) {
            array.pop(); // remove the added item from array
            if (i === length) {
                return console.log('NOT FOUND');
            }
            return console.log('FOUND ON INDEX', i);
        }
    }
};

linearSearchSentinel(['foo', 'bar', 'baz'], 'foo');
linearSearchSentinel(['foo', 'bar', 'baz'], 'baz');
linearSearchSentinel(['foo', 'bar', 'baz'], 'nope');

Or, if you wanted to use the while approach, then don't put any testing inside the loop - simply increment the index:

const linearSearchSentinel = (array, itemToFind) => {
    const { length } = array;
    array.push(itemToFind);
    let i = 0;
    while (array[i] !== itemToFind) i++;
    array.pop(); // remove the added item from array
    if (i === length) {
        return console.log('NOT FOUND');
    }
    console.log('FOUND ON INDEX', i);
};

linearSearchSentinel(['foo', 'bar', 'baz'], 'foo');
linearSearchSentinel(['foo', 'bar', 'baz'], 'baz');
linearSearchSentinel(['foo', 'bar', 'baz'], 'nope');

It's also a good idea to prefer const over let when you don't need to reassign the variable name.
I'd prefer one of the easy-to-understand versions above, but if you really want to avoid changing the length of the array for optimization purposes, I suppose you could replace the last item similar to you're originally doing instead.

const linearSearchSentinel = (array, itemToFind) => {
    const { length } = array;
    const lastItem = array[length - 1];
    array[length - 1] = itemToFind;
    let i = 0;
    while (array[i] !== itemToFind) i++;
    array[length - 1] = lastItem;
    console.log(
        (i !== length - 1 || lastItem === itemToFind)
            ? 'FOUND ON INDEX ' + i
            : 'NOT FOUND'
    );
};

linearSearchSentinel(['foo', 'bar', 'baz'], 'foo');
linearSearchSentinel(['foo', 'bar', 'baz'], 'baz');
linearSearchSentinel(['foo', 'bar', 'baz'], 'nope');

This is all for informational purposes only, of course - if you were actually facing a practical problem where you needed to find the index of an element in an array in JavaScript, it would make more sense to use the built-in indexOf method, which would be far faster and easier. Better not to reinvent the wheel unless an assignment like this one requires it.


Determine the complexity of sorting a binary array

I agree with your analysis that both algorithms have O(n) time complexity (where n is the number of elements in the array). An important factor to note is that both algorithms also use constant extra space.
However, you can include other metrics in your analysis too. Anything that may be expensive  to do can be considered. Two common metrics are the number of comparisons and the number of exchanges.
The number of comparisons tells you how often an element of the array is accessed and then compared. Memory access can be quite expensive, depending on how far up the memory hierarchy (registers, cache levels, RAM, local storage, external storage) you need to traverse before getting the value.
The number of exchanges tells you how many times elements are swapped. This can be expensive any time writing to memory is. For instance, writing to shared memory in a multi-process program.

Taking the above into account, ignoring the error checking case, and also ignoring any potential optimisations from the compiler, I would argue the second algorithm is better. For the first implementation I count 2 comparisons per element, and 1 exchange per element. For the second, I count 1 comparison per element, and then 1 assignment per element (an assignment of a constant is cheaper than exchanging two elements).
You can replace the exchange with assignments in the first implementation. Since the array only contains the values 0 and 1, and you've checked that the two elements are different.
if (j > i && value[i] > value[j] )
{
    value[j] = 1;
    value[i] = 0;
    j--;
    i++;
}

Without profiling the code, I don't think it is possible to tell if the extra number of comparisons in the first implementation are more costly than the overhead of the second pass through the array in the second implementation. I would not be surprised if the numerous bounds checks in the first piece of code (i < j) are the actually largest performance hit.

Third implementation
Based on the comment that the first implementation is still faster, here is another solution that tries to improve upon the second. I'm hoping that by writing it with well known operations, the compiler can work some magic.
public static int[] SortOnesZerosAlternate(int[] values)
{
    int countOfZeros = values.Length - values.sum();
    // Maybe replace this with values.Clear?
    for (int i = 0; i < countOfZeros; i++)
    {
        values[i] = 0;
    }

    for (int i = countOfZeros; i < values.Length; i++)
    {
        values[i] = 1;
    }

    return values;
}


Simple "nullable" template class. Are there weaknesses in the implementation?

Don't see the point in:
using std::swap;

It adds a line. It is also longer to type than just prefix each swap with std::
As pointed out by @Matt below. There is a good reason to do this.
Read his links below for a more detailed description.
No point in doing copy-swap idiom for a class that is not managing resources.
So really there is no need for the copy constructor or the assignment operator: the compiler-generated versions will work perfectly well.
If you can compare against a value:
bool operator==(T value) { return m_isSet && value == m_value; }

Why can't you compare against Nullable<T>? The cast operator does not help you here - operator T() const { return get(); } - as it potentially throws. Yet it is still logical to be able to compare or it should throw if either side has m_isSet as false.
Nullable<int>   x(5);
Nullable<int>   y;

if (y == x){} // works as expected (always false as y is not set).
if (x == y){} // throws an exception.

Also operator== should be const.
Cast and get methods should be returning a reference (big T objects are expensive to copy). You will also want const versions of these functions.
On a reset:
void reset() { m_isSet = false; m_value = T(); }

Why reset the m_value when it can not be accessed anyway when m_isSet is false. Also the cost of setting T here may be expensive for some classes.
As a general comment.
I don't see the point. Each class should have its own serialization operators (>> and <<) and you will need to serialize the whole state for this to work symmetrically. Anything that is not needed for serialization is already marked as mutable (i.e. it is not part of the logical state of the object). Everything else is part of the logical state of the object. Anything that is optional has its own serialize operator and understands when not to serialize its own state.


Selecting a prize category based on two parameters

To make @kfx's answer more readable:

const getFirstCategory = (bonusPlus, prizeCategories) => {
  const bonusPlusLevel = bonusPlus ? 2 : 1;
  if (prizeCategories[0].playLevel === bonusPlusLevel) {
    return [prizeCategories[0]];
  }
  return [prizeCategories[1]];
};


Which class is best to call .getResource on?

I would prefer the second one. The others will bite if the library runs inside an OSGi container.

Furthermore, I would

pass UTF-8 character encoding to the constructor of the InputStreamReader. Otherwise it will use the system encoding which vary from system to system. (Or let the user to set it with a third method parameter.)
use longer variable names. is, r, c are not too easy to read. I would call them resourceStream, clazz and resourceReader. It does not force readers to decode them.
reverse the order of String location, Class c parameters. It would be in the same order as the first line use them (c.getResourceAsStream(location)). I don't know if there is a rule of thumb for this, but it looks more natural to me. (Any pointers are welcome.)
remove the * @throws IOException javadoc line. It is meaningless in this form.


Generating pattern similar to QR code using strings

You are doing unnecessary work by first looping over each row and each column to initialise the field to empty squares; and then looping over each row and each column to change the state based on a random condition. You can do it in one looping by assigning the "empty" or "filled" state based on said condition.

And while we're at it, you could simplify the condition as there is exactly 67 numbers that are either multiple of two or three between 1 and 100. So you could at least test if randNum <= 67 which would yield the same probability. But this probability is pretty close to \$\frac{2}{3}\$ so we can come up with an other approach: use a tupple composed of two " filled" patterns and an "empty" one and use random.choice instead.

You could also benefit a lot from the str.join method instead of concatenating the chosen pattern and a separator to a temporary string. It will help improve your memory usage. Just put the selected patterns in a list and use the join method of your separator to create the whole string at once. Better yet, join over a list-comprehension or a generator expression.

Lastly, you don't need a class to solve this problem as you don't have any state. The various attributes are only there to store temporary variables. A simple function will do:

import random

def generate_image(size, *, filled='|0|', empty='|-|'):
    patterns = filled, filled, empty

    return '\n'.join(
            ' '.join(random.choice(patterns) for _ in range(size))
            for _ in range(size)
    )

if __name__ == '__main__':
    print(generate_image(20))


Chatroom log in with no 3rd party libraries

You have a number of missing links in your code, which makes a review hard to do.

Your ServerSocket code at first glance looks OK, but it is actually broken.

    this.running = true;
    ServerSocket ss = new ServerSocket(1000);
    while (this.running) {
        this.threadPool.execute(new InfoGrabber(ss.accept()));
    }

You don't have a declaration for running. If it is a volatile boolean, then it will probably work. If it is not volatile, it'll possibly never work, depending on the setup. I would never recommend the use of volatile, though, so I would recommend an AtomicBoolean. Still, even with an atomic boolean, you may never exit your server loop because it only checks to see if it should stop after it has accepted a connection. The code will sit waiting on the accept() until something happens, even if the running is false. You need a different mechanism, or timeouts, on your code.

The actual socket you get is also badly handled. You create a thread to run the socket on, and you create an ObjectInputStream on the socket. This is OK, but you then schedule that on a thread which exits quickly... the ClientClass instance is registered on to the clientManager, but then no thread appears to be listening for more input from the client? Additionally, nothing has told the client that it is connected.

This code appears to be pretty new, and incomplete.


Is this jQuery Plugin for TreeView correct?

First off it'd be good to run the code through jslint or jshint. It identifies a few issues, such as an extra comma in the default options list; that'll break the code in older IE versions. Also, it flags some things like the block-less if, which - while allowed - it's best to avoid for the sake of consistency and maintainability.

As for the code itself, here are the things I noticed:

jQuery objects should be cached whenever possible
The code only handles unordered lists (ULs), not ordered lists (OL) although it might as well
The event handling is added document-wide every time the code is run. If you use the plugin twice in a document, the first tree gets double event handlers. That spells trouble.
The setFocus function might misbehave if the tree list is itself inside a list element, as it loops through all list-type parents up to the document root.
The classPrefix option is confusing: It's not used for the expand/contract classes, only for the toggle button's "main" class. But since that's the only one, why not just let the user define that as well? Basically, if a prefix is used only once, it's not necessary.
Comparing against undefined is a no-no. undefined is not a reserved word, and can (in some runtimes) be defined. In this case, a simple boolean works just as well.

Here's what I arrived at

(function ($) {
  var methods = {
    init: function(options) {
      // Default Settings
      var settings = $.extend({
        expandIconClass:   'closed',
        contractIconClass: 'open',
        toggleButtonClass: 'toggle',
        setFocus:          false      // just use a boolean here
      }, options);

      return this.each(function() {
        var target = $(this);

        // walk the tree
        target.find('li').each(function() {
          var node = $(this),
              branches = node.children('ul, ol'),
              button;

          if(branches.length > 0) {
            branches.hide();
            button = $('<div />', {
              'class': settings.toggleButtonClass + " " + settings.expandIconClass,
              on: {
                click: function (event) {
                  // we already have the correct elements here
                  branches.toggle();
                  button.toggleClass(settings.expandIconClass + " " + settings.contractIconClass);
                }
              }
            });

            node.prepend(button);
          }
        });

        if(settings.setFocus === true) {
          target.goodtree('setFocus');
        }
      });
    },

    setFocus: function(element) {
      return this.each(function() {
        $(element).parents('ul, ol').each(function() {
          var ancestor = $(this);
          if( this.is(ancestor) ) { // better check
            return false; // stop the each-loop
          }
          ancestor.show();
        });
      });
    }
  };

  $.fn.goodtree = function(method) {
    if(typeof methods[method] === 'function') { // stronger conditional
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if(typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist on jQuery.goodtree');
    }
  };
}(jQuery));

Here's a demo (I reused your demo markup and styling, minus the open/close icons)


Resource caching in Java with soft references

Double-checked
Double-checked locking does not work. There are some complicated reasons for this, but, it's enough to say that the Java specification allows the Java runtime to legitimately reorder some of the checking code in a way that makes the sync lock out-of-alignment with the checks you think you are checking. (See: Double checked locking pattern: Broken or not? )
AutoClosable
Now, about the AutoClosable.
Why?
What does that get for you? You forcefully "forget" a reference that was allowed to be garbage collected anyway. Additionally, it does not close the instance at all, it just makes it refresh later. The AutoClose is a shim, that's not a very useful one at that.
SoftReference
Here's a paradox with caching. What are you caching here? The instance of the resource that you read from the ResourceLoader, or the Resource class itself? It would be preferable to cache the Resource instance itself, but you cache the underlying data. Additionally, you re-load it if the cache is cleared by the GC.
My problem is that anything that has a strong reference to the Resource instance probably wants to find the content again at some point.... otherwise it would not need to hold the reference. Thus, if you have memory problems, it is possibly just better to reload the resource each time, than to possibly hang on to it.
Are you sure that you want a SoftReference?
If yes, why don't you have a ReferenceQueue? A reference queue allows you to back-reference a SoftReference to the Resource that owns it. It works as follows:

create a sub-class of SoftReference (not a wrapper, but an actual "extends" instance).
put a strong-reference back to the Resource that the SoftReference comes from
register the SoftReference on a queue

Then, in a separate thread, pull GC'd items off the queue, and process them. This allows you to get an ahead-of-time peek at data that has been de-cached.
It also allows you to have a colleciton of Resources that are held in, for example, a Map, and you can clear the Resources out of the map as they are cleared out by the GC.


Because you can't update a written value without replacing the value, you have no other possibility to overwrite your metadata (currentTerm and votedFor) if they had changed.

For the log file you can use another approach by using an appendable FileOutputStream, but you will get problems if you just use

logWriter = new ObjectOutputStream(new FileOutputStream("Server"+id+"Log", true));

because the ObjectOutputStream is always writing a header first.

To overcome this problem you need to subclass the ObjectOutputStream like

public class AppendableObjectOutputStream extends ObjectOutputStream {

    public AppendableObjectOutputStream(OutputStream out) throws IOException {
        super(out);
    }
    private boolean append = false;
    public AppendableObjectOutputStream(String fileName, boolean appendIfExists) throws IOException {
        super(new FileOutputStream(fileName, appendIfExists && Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)));
        append = appendIfExists && Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS);
    }

    @Override
    protected void writeStreamHeader() throws IOException {
        if (append) {
            reset();
        } else {
            super.writeStreamHeader();
        }
    }
}

See also: https://stackoverflow.com/a/1195078/2655508

Using braces {} for single statements while loops too will make your code less error prone.

A ObjectInputStream should like any other stream be closed after the usage is finished.

//if Log file exists then should exists Metadata too

Assuming that something should be can lead to problems. One could have deleted the metadatafile and you would get problems.

Your method is doing to many things. You should extract parts of it to separate methods. Like

private List<LogEntry> readLogFile(String fileName) throws IOException {
    List<LogEntry> logs = new ArrayList<>();
    if (Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)) {
        ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fileName));
        try {
            //until there are LogEntry objects in the file, read them and add them to log
            while (true) {
                logs.add((LogEntry) reader.readObject());
            }
        } catch (EOFException e) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(reader != null){
                reader.close();
            }
        }
    }
    return logs;
}

For reading the metadatafile I would suggest you create a MetaData class which holds the voteFor and Term and is beeing written by using writeObject() and read by readObject() methods. The voteFor and Term should be initialized in the constructor to voteFor = -1 and Term = 1.

This would give you the possibility to use this method

private MetaData readMetaDataFile(String fileName) throws IOException {
    if (Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)) {
        ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fileName));
        try {
            return ((MetaData) reader.readObject());

        } catch (EOFException e) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(reader != null){
                reader.close();
            }
        }
    }
    return new MetaData ();
}

Implementing the above mentioned points will lead to

MetaData metaData = null;
String logFileName = "Server" + id + "Log";
String metaDataFileName = "Server"+id+"Metadata";
try {
    log = readLogFile(logFileName );
    metaData = readMetaData(metaDataFileName);

    logWriter = new AppendableObjectOutputStream(logFileName, true);
    metadataWriter = new AppendableObjectOutputStream(metaDataFileName, false);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

but you should create the metadataWriter only if you really write the data.


Static helper function to set a property on another object

I would argue that setTimestampRadioButton can be improved in three ways.

Side effects. By mutating the passed dataModelObject, the function immediately makes any function that uses setTimestampRadioButton harder to understand as it magically sets a property name that the calling function did not specify.
Typing. Mutating the argument the function forces you to create a Partial<IDataModel> (or cast an object which is not an IDataModel to IDataModel). This is not ideal.
Alternative property names. Currently only IDataModel uses the format from a RadioButton, what happens when ITimeModel needs the timestamp format stored in a format property? We are now back to the original problem.

I would instead recommend creating a method to get the expected format.

public static getTimestampFormat(radioControl: RadioButton): IFormat {
    if (radioControl.value() === 1) {
      return { format: "foo" };
    } else if(radioControl.value() === 2) {
      return { format: "bar" };
    }
    return { format:
}

This simplifies your generateDataModel method even more.

public generateDataModel(): IDataModel {
  return {
    name: this._name.value(),
    type: this._type.value(),
    timestamp: Helpers.getTimestampFormat(this._radioControl)
  };
}

Instead of a static helper method, you might also consider adding the method as an instance method of the RadioButton class, or creating a child of the RadioButton class with a TimestampRadioButton class.

A couple other general things:

Avoid casting like the plague. It is almost as bad as using the any type as it hides potential problems in a very similar way.
I can't think of any instance in which adding Object or data to a variable name makes it more descriptive. dataModelObject doesn't really tell you any more than model.


Some general remarks:

Use more and consistent spacing, e.g.

digits[i]=temp%10;

should be

digits[i] = temp % 10;

Define variables only at the scope where they are used, e.g. carry
is used only inside the while (b--) { ... } loop.
Move the actual computation to a separate function so that main() becomes
shorter. That makes it also easier to add test cases.
Assuming that int has (at least) 32 bits (which is the case on all modern
platforms), there is no need to use long long at all in your code.
There is no need to treat the case b = 0 separately. a ^ 0 is 1, and that can be covered with the general case if you
start with digits[] = { 1 } instead of digits[] = { a }.

The performance can be increased by storing more than a single decimal
digit in each array element digits[i]. Since 10^9 < 2^31, you can store
8 decimal digits in digits[i] and digits[i] * a + carry will still not
overflow.

Your program would then look like this:

const int BASE = 100000000; //  10^8

int powerDigitSum(int a, int b) {
    int digits[4000] = { 1 } ;
    int len = 1;

    while (b-- > 0) {
        int carry = 0;
        for (int i = 0; i < len; i++) {
            int temp = digits[i] * a + carry;
            digits[i] = temp % BASE;
            carry = temp / BASE;
        }
        if (carry != 0) {
            digits[len++] = carry;
        }
    }

    int sum = 0;
    for (int i = 0; i < len; i++) {
        int d = digits[i];
        while (d > 0) {
            sum += d % 10;
            d /= 10;
        }
    }
    return sum;
}

int main() {
    int test, a, b;
    scanf("%d",&test) ;
    for (int i = 0; i < test; i++) {
        scanf("%d %d",&a,&b) ;
        int sum = powerDigitSum(a, b) ;
        printf("Case %d: %d\n", i, sum) ;
    }
    return 0 ;
}

Your original algorithm corresponds to BASE = 10. Using BASE = 100000000
instead reduced the computation time for a=9, b=4000 from 0.095 seconds
to 0.014 seconds on my computer.

If that is not sufficient, you can use (unsigned) long long for the digits[] array  and work with an even larger BASE.