In :

table = []
valid_idxs = [(r,c) for r in range(level) for c in range(level)]
[compute(table, r, c) for r, c in valid_idxs]
print(table)

the line [compute(table, r, c) for r, c in valid_idxs] definitly shouldn't be a list comprehension as we are building a list that we do not use. If it is side-effects we are interested in, we might as well use a for.

table = []
valid_idxs = [(r,c) for r in range(level) for c in range(level)]
for r, c in valid_idxs:
    compute(table, r, c)
print(table)

Once, this is done, it seems quite clear that the first list comprehension is not really required neither as it could be :

table = []
for r in range(level):
    for c in range(level):
        compute(table, r, c)
print(table)

This being said, even though it looked like a good idea to use a function to extract common code, the responsabilities are not clearly defined making things a bit hard to track. Let's put the body of the function back in the loop and try to see what can be improved :

def pascal_triangle(level):
    table = []
    for r in range(level):
        for c in range(level):
            if r == 0:
                table.append([])
            if c == 0 or r == c:
                table[r].append(1)
            elif c <= r:
                table[r].append(table[r-1][c] + table[r-1][c-1])
    print(table)

First thing to improve : print the content of table before or after the table.append([]) : isn't it a bit weird to build all lists as we go through the c variable ? Also, the first list created is non-empty but the other one are. Let's make the process clearer and add an empty list at each r iteration.

def pascal_triangle(level):
    table = []
    for r in range(level):
        print(table) # look how the tables gets populated now : isn't it cool ?
        table.append([])
        for c in range(level):
            if c == 0 or r == c:
                table[r].append(1)
            elif c <= r:
                table[r].append(table[r-1][c] + table[r-1][c-1])
    print(table)

Let's go one step further, please note that the deeper loop will not do anything if c > r (this wasn't true before previous change but it is now correct). We can easily remove this pointless iterations (and the pointless check) :

def pascal_triangle(level):
    table = []
    for r in range(level):
        print(table)
        table.append([])
        for c in range(r+1):
            if c == 0 or r == c:
                table[r].append(1)
            else:
                assert(c<=r)
                table[r].append(table[r-1][c] + table[r-1][c-1])
    print(table)

Now, it's time for the special trick : we could remove the test if c == 0 by performing this before the loop. Also, we could't remove the if c == r by performing this after the loop (but we need to check that this would have happened which is when r>0).

def pascal_triangle(level):
    table = []
    for r in range(level):
        print(table)
        table.append([])
        table[r].append(1)
        for c in range(1, r):
            table[r].append(table[r-1][c] + table[r-1][c-1])
        if r:
            table[r].append(1)
    print(table)

Now, we can try to be more fancy : instead of calling table[r] every time : let's introduce a line variable and use it :

def pascal_triangle(level):
    table = []
    for r in range(level):
        line = []
        line.append(1)
        for c in range(1, r):
            line.append(table[r-1][c] + table[r-1][c-1])
        if r:
            line.append(1)
        table.append(line)
    print(table)

We can see that this looks a lot like a list comprehension scenario and indeed, we can use it :

def pascal_triangle(level):
    table = []
    for r in range(level):
        table.append([1] + [table[r-1][c] + table[r-1][c-1] for c in range(1, r)] + ([1] if r else []))
    print(table)


Switching directions in iterating 2D arrays

I do prefer the solution with the boolean. Also, a third possible variant would be to fill every other from left to right and remaining rows from right to left

In any case, they way you are supposed to handle arrays where size is not A*B might help you to pick the best solution for you.


Take postcodes and get the Lat long information from them

Test case structure
It doesn't seem like the code totally "lacked effort and structure" but the structure, at least of the test cases, could be better. Since all three describe() blocks contain a test that calls getLatlonFromPostcode so there could be a single describe() block with three it() blocks to test the various aspects of how the function should handle given postcodes.
Utilizing await
One of the main benefits of using await is to eliminate the need for callbacks to .then(). Some code utilizes this benefit e.g. the test functions but the methods in app.js do not - e.g.

await getLatlonFromPostcode(postcode).then((data) => {
  res.send(data);
});

Ideally, the res.send() call would be on a sequential line instead of in a .then() callback function:
const data = await getLatlonFromPostcode(postcode);
res.send(data);

Or even simpler:
res.send(await getLatlonFromPostcode(postcode));

Error handling
As an interviewer I would be checking to see how well the code handles edge cases. Obviously with promises comes rejection. The first couple methods don't appear to handle rejected promises at all.
Import Star
The two import statements import everything from the modules being imported. In the Airbnb style guide, it recommends no wildcards:

Why? This makes sure you have a single default export.1

The import for axios could be simplified using destructuring assignment:
import { get, post} from "axios";

That way the code can call get() and post() without needing to reference axios, and the other items exported from axios that are not needed are not imported.


Building a better Data Access Layer Class

This is going to be just a partial review, I don't have much time but I can't help it, I have to say something.

usr_OrderFulfillment might be how the table is called in your database, and SOPNUMBE might be how a column is called in that table. It doesn't mean your entities have to be as painful. Entity Framework is an object/relational mapper; this implies a mapping - you can easily map table usr_OrderFulfillment to entity OrderFulfillment and column SOPNUMBE to property OrderNumber.
Your DeploymentOrderDataLayer class (I wouldn't call a class a layer - call it a service if you will, but a layer is more for an assembly than for a type), is tightly coupled to TPGContext, and each new method requires a new instance of your context - even if 20 calls are made in the same request. You should inject the instance through the class' constructor and use a single instance per request. There's really no need to new it up and dispose it in every method. The class being static isn't helping either (it does explain the non-existing constructor though). Always prefer instances over static helpers.
This architecture feels like stored procedures written in C# code. It's bloated, over-engineered and makes you almost as good as me in shredding KISS into tiny little pieces. Have you tried using the EF DbContext directly in your controller to get the job done, and then refactor into a more structured approach?


Test driven development

In test driven development you let the code and the tests evolve by repeating the following steps:

Add a new test case that fails, the simplest possible
Fix the implementation the simplest possible way so that all test cases pass
Optionally refactor the existing code, while keeping all tests passing
Repeat from step 1

There are variations to these steps, but one thing is certain: in the end you will have many test cases. The posted code has one, which means it wasn't really developed using TDD.

Keep it simple

It's good to keep everything as simple as possible. In the test class, do you really need a Number class to wrap an number, so that you create an instance and then call a method on that instance? A simple method would have been enough, that takes an integer as parameter and returns a string.


This is a really good question -- starred it! I am not very experienced with RxJs, but I believe your code around BehaviorSubject and Observable is as concise as possible.

BehaviourSubject itself is "subscribable" (just like an Observable) but it's a really bad practice to expose it directly to the consumer, i.e. your separation of users$ and usersSource is a right thing to do. Exposing Observable is okay because it's designed to be read-only.

usersSource.getValue() is inevitable in your code, unless you decide to keep the usersSource state as a local field, but IMO it does not do any good in this scenario. Having state to be stored as a part of the BehaviorSubject is handy.

There are minor style things that could be improved in the code, but that's unrelated to RxJs, so I'll not comment on that.

Update 1

Just a few months ago I was not aware of .startsWith() which seems to be an answer to a part of your question:

const neverButStartsWithZero = Rx.Observable
                                .never()
                                .startWith(0);
// Emits 0
const subscription1 = neverButStartsWithZero
                        .subscribe(value => console.log('subscription1:', value));

const threeEventsWithExtraZero = Rx.Observable
                                .of(1, 2, 3)
                                .startWith(0);
// Emits 0, 1, 2, 3
const subscription2 = threeEventsWithExtraZero
                        .subscribe(value => console.log('subscription2:', value));


Structure of inheritance between Animal classes and methods

Inheritance is typically describe as an "is-a" relationship.  So when you derive a Dog from an Animal, we can say that a Dog is a Animal.  However, when you derive a Cat from a Dog, unless this is some other planet, we can't correctly say that a Cat is a Dog.  Further, we can, without error, invoke Tina.woof('ferocious') to cause "Tina just did a ferocious woof".  Since no Persian cat I've ever seen has been known to "woof" either ferociously or not, this is an alarming and surprising result.

Better would be to derive both Dog and Cat types from Animal.  If you have other animals which don't have names, breeds or genders, you could have some intermediate class such as Pet that would capture the additional detail not already in Animal.  Otherwise, just add those attributes to Animal.

Finally, we can put the speak method in the base Animal class.  One simple illustration is this:

class Animal:
    def __init__(self, kind, place):
        self.kind = kind
        self.place = place

    def speak(self, adverb):
        print("%s just did a %s %s" % (self.name, adverb, self.speechtype))

    #getallinfo method, get's all the parametrs of both classes.
    def getallinfo(self):
        print("%s is a %s %s %s, sitting on the %s" % (self.name, self.gender, self.breed, self.kind, self.place))

#This class inherits kind and place arguments from Animal class (which can work for any animal)
#Initiates a Dog object with name, gender and breed parameters.

class Dog(Animal):
    def __init__(self, name, gender, breed):
        self.name = name
        self.gender = gender
        self.breed = breed
        self.speechtype = "woof";
        Animal.__init__(self, 'Dog', 'Ground')

#Cat class inherits the paramets of use for a Cat (similar things) like name, gender and breed, which they both share, also the getallinfo method and initiate them.
class Cat(Animal):
    def __init__(self, name, gender, breed):
        self.name = name
        self.gender = gender
        self.breed = breed
        self.speechtype = "meow";
        Animal.__init__(self, 'Cat', 'Ground')

#Here I create 3 objects, 2 dogs and 1 cat with selected arguments.
#And check for some methods on the objects.
Mickey = Dog('Mickey', 'Male', 'Bulldog')
Flora = Dog('Flora','Female','Pug')
Tina = Cat('Tina','Female','Persian')
Tina.getallinfo()
Tina.speak('soft')
Flora.getallinfo()
Mickey.speak('loud')

There's more that could be improved, but I hope that helps until others weigh in on your question and give more expansive answers.


def self.divisible?(n)
    is_divisible= false
    (2...n).each do |divisor|
      division=n/divisor
      if n== divisor*division
        is_divisible= true
      end
    end
    is_divisible
  end

since you're returning a flag just after computing it, you could just return true instead of setting the flag, and return false if you get to the end. This saves you one line. But, Ruby arrays have the any? and all? predicates. Let's rewrite your code to use any?. This reduces the if condition to only its head. I hope you don't mind if I normalise the whitespace along the way:

def self.divisible?(n)
  (2...n).any? do |divisor|
     division = n / divisor
     n == divisor * division
  end
end

we could inline division (n == (n / division) * division), but let's use the modulo operator instead. Note that unlike your algorithm, modulo even works for floats and even rationals.

def self.divisible? (n)
  (2...n).any? do |divisor|
     n % divisor == 0
  end
end

If you don't mind, I'll reduce the line count further by performing a style change here.

def self.divisible? (n)
  (2...n).any? {|divisor| n % divisor == 0}
end

I don't think you can get shorter than that.

but if your intention is to generate a list of primes, you should only test divisibility by said primes.

def primes_until n
  list = []
  (2..n).each do |x|
    list << x unless list.any? {|d| x % d == 0}
  end
  list
end

Written as a reduce:

def primes_until n
  (2..n).reduce([]) do |list, x|
     list << x unless list.any? {|d| x % d == 0}
     list
  end
end


Determining if a connection has been made to a communications device

I agree with Alex that ManualResetEvent may be a little cleaner simply because you don't need to perform manual signal tracking to ensure you don't wait due to the Monitor already pulsing but, as I understand it, WaitHandle (used by ManualResetEvent) has more overhead. It's also quite possible to use memory barriers and Application.DoEvents/Thread.Sleep in a time-limited loop to achieve a lockless solution, but none of this matters unless you have very strict resource/performance concerns.

Regardless, there's always more than one way to skin a cat and your usage is indeed safe and correct.

If the Connect method is running on your UI thread be sure your timeout isn't really long or windows may think your application is not responding because blocking in Monitor.Wait does not resume the window's message pumping; if you need a long timeout or it is not running on the UI thread you will need to ensure the Connect method cannot be called again before the last has finished (if this._channel.Open() returns false if it is already open that should suffice). In the case of it being on the UI thread, besides preventing double execution, you would want to switch to a small timeout in a time-limited loop that calls Application.DoEvents(). You may already be aware of these concerns but I'm having to make a lot of assumptions to review the code. While I'm at it, it's probably trivial, but you can also move you Command instantiation to just before the lock to save yourself unnecessary instance creation in some cases.


Public versus private fields
In Java, it is a custom to make all your fields private, unless they must be explicitly accessed by other sources. I believe this custom also applies to JavaScript.
Instead of having the element be a public (this) field, why don't you make it a private (var) field? There doesn't really seem to be another place you use it.
And, if there is another place that on using it in, why don't you create a getter? This would be a function that returns the field, and it might be named something like getElement.
This is up to you.
Defining the functions with Filter.prototype
You did exactly this, and that is perfect. Keep that up, it is a great practice.
querySelector versus getElementsByClassName
This is a matter of efficiency versus readability - whatever you chose to have.
It would be more efficient to use getElementsByClassName in place of querySelector in the link field, as the getElementsByClassName function doesn't have to do checks on the argument provided(whether or not the argument is a class, an id, a tag name, or a mixture); it knows it's looking for a one class and one class only.
It is slightly more readable having querySelector, as the syntax for it's arguments is the same syntax for CSS; it's a "universal" syntax.
Indentation
With only 2 spaces for an indent, your code looks fairly cramped. I recommend using tabs or 4 spaces as an indent.


Hand crafted longest common sub sequence

Interesting question,

I would say for an interview, if you are given a task and you think you need combinations or permutations, then there is a good chance it's a trick question. Those are terrible for performance and I would avoid them as the plague during interviews.

Secondly, your code is hard to read. Only because of the comment on the very last line did things come together for me.

Other than that;

Try to be consistent

function allButLast(arr) {
  return arr.slice(0, arr.length - 1);
}

function last(xs) {
  return xs.slice(-1);
}

These functions both get an array, but in one the argument is called arr, in the other one xs. They should have the same name, I would go for list.
I like your powerset routine, and might borrow it
I dont understand [].reduce.call in sum, why not just xs.reduce ? From an interview perspective it makes me think you dont understand how reduce works :/

On the whole this implementation should be light years faster, though I only tested it with your test case which I got right the first time, so I have good hopes ;)

console.log(LIS([2, 3, 1, 4, 0, 5])); // [2, 3, 4, 5]

//Find the longest common sub sequence
function LIS( list ){

  var indexes = {},
      //Possibly too verbose variable name ;)
      lastIntegerofLargestSequence,
      largestSequenceLength = 0,
      output = [];

  for( n of list ){

    //Have we processed a predecessor yet?
    if( indexes[n-1 ] !== undefined ){
      //There is a predecessor, if we have never found n,
      //then put n with predecessor's length + 1
      if( indexes[n] === undefined ){
        indexes[n] = indexes[n-1] + 1;
      //Otherwise ONLY put that predecessor length + 1
      //if that would make a better (longer sequence)
      }else if( indexes[n-1] + 1 > indexes[n]  ){
        indexes[n] = indexes[n-1] + 1;
      }
      //First number in a possible sequence
    }else if( indexes.n === undefined ){ //That 0 ;/
      indexes[n] = 1;
    }

    //Keep track of the largest sequence
    if( indexes[n] > largestSequenceLength ){
      largestSequenceLength = indexes[n];
      lastIntegerofLargestSequence = n;
    }
  }

  for( var i = lastIntegerofLargestSequence - largestSequenceLength + 1; i <= lastIntegerofLargestSequence ; i++ )
    output.push(i);

  console.log(output)

}


Calculator Program which can operate on multiple numbers

After a little back and forth, we got the suggestions of the previous question implemented. However there are still some minor issues:

Kind of strange mixing int and float calculations – I know you got 0 when doing divisions, but that is more of a test number issue than a fault in code. As it currently stands you do float numbers for the division, but your operator is operator.floordiv which rounds of the division.

If you want to use floats when dividing, then change to operator.div, and if you want to use integer division remove the float(input("Number: ")) ..., and let the operator.floordiv remain.
No need for the initializing values when using functools.reduce – The newer reduce function does what is expected when reducing, so you don't need this at all in the new code.
The advice to use doctest still applies – This both provides examples for use, and verifies that your code does what it is expected to do.
Don't use top level code, include it in main() - Move all of your code at the top level into a function, which you call from if __name__ == '__main__':, as this cleans up the code interface, allows your function to be called if imported in another file, and it looks nice.

Refactored code

When implementing all of this, and using integer division the code looks like this:

import operator
import functools
import doctest

OPERATION = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv
}

def calculate(numbers=None, operator=None):
    """Apply the operator to all numbers, and print result.

    >>> calculate([1, 2, 3, 4], '+')
    10
    >>> calculate([1, 2, 3, 4], '-')
    -8
    >>> calculate([1, 2, 3, 4], '*')
    24
    >>> calculate([120, 2, 3, 4], '/')
    5
    """

    if not numbers:
        amount_of_numbers = int(input("How many numbers? "))
        numbers = [int(input("Number: ")) for _ in range(amount_of_numbers)]

    if not operator:
        operator = input("Which operator (*, /, +, -)? ")

    result = functools.reduce(OPERATION[operator], numbers)
    print(result)

if __name__ == '__main__':
    doctest.testmod()
    calculate()

Note how this way of making it a function allows for 'proper' use as a function, whilst still allowing for user to input the missing numbers and/or operator of choice.

Another possible extension would be to add another parameter to control whether it is printing the result, or returning it for further calculations. Possibly even adding a loop around it, so you can repeat calculating other stuff?


Optimizing digit sum and product with GMP

There are a few ways to speed up your division.  First, note that because rem is declared within the while loop, it's both constructed and destroyed every loop iteration.  That's not really necessary, so you could instead declare it outside the loop and simply assign a new value within the loop each time.  Also by changing the line from num = num / 10 to num /= 10, you avoid creating and destroying yet another temporary.  Applying both of those saves a little time, but it's still slower than the string method because you're essentially performing the division twice (once for num % 10 and again for num / 10).

The key is to do only a single division per loop, but you'll have to resort to using the underlying C function since it's not exposed to the C++ interface. Fortunately, it's simple to do so:

unsigned long digit;
while(num != 0) {
    digit = mpz_tdiv_q_ui(num.get_mpz_t(), num.get_mpz_t(), 10);
    sum += digit;
    pro *= digit;
}

On my machine this is slightly faster than the string method, and probably uses a little less memory.

Update:

Because the speed of that code relative to the string method varies based on what compiler optimizations are used, it's not necessarily always faster.  This version uses low-level GMP calls for more speed:

__mpz_struct *q = num.get_mpz_t();
while(*(q->_mp_d) != 0) {
    auto digit = mpn_divrem_1 (q->_mp_d, (mp_size_t) 0,
            q->_mp_d, q->_mp_size, (mp_limb_t) 10);
    sum += digit;
    pro *= digit;
}

This makes a couple of assumptions that are important.  First, it assumes that num > 0 and it dives deep into the internal structure of __mpz_struct so it will not be very durable to changes in GMP, should they decide to change the underlying representation of numbers.  However, with this code, I find that it's a bit faster on my machine than the string method, both with and without -O3 optimizations.

Also, note that within your range of integers, the sum of digits will always fit within a long int which will save time, but could equally be applied to the string method.


Create a unique four digit code from 35 characters

By my count, 0-9 + a-z gives 36 characters rather than 35.

For four digits like that, the number of combinations is \$36^4\$, which works out to 1,679,616.

As for the code itself, I think I'd do things just a little differently. What you really have is a 4-digit number in base 36. It's probably easiest to just use a normal number, and then use toString to generate the base-36 representation when you need it:

Integer counter;
String result = toString(counter, 36);

This does differ in one minor detail: it won't fill in leading zeros, so if it's shorter than 4 characters, you'll have to fill in the leading zeros yourself (still a pretty trivial operation though).

For the sake of security, I don't install Java on my machines, but there's a rough imitation of the basic idea, but in C++:

#include <iostream>
#include <string>
#include <deque>
#include <cassert>

// This should be approximately equivalent to what you'd get from
// Java's `toString`, at least for non-negative numbers:
std::string toString(unsigned value, unsigned base) {
    static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";

    assert(base <= 36);

    std::deque<char> ret;

    while (value) {
        unsigned digit = value % base;
        value /= base;
        ret.push_front(digits[digit]);
    }
    return std::string(ret.begin(), ret.end());
}

// This calls toString, then pads the result out to 4 digits.
std::string paddedToString(unsigned value, unsigned base, unsigned num_digits) {
    std::string s = toString(value, base);

    // Add enough 0's to get to the desired width:
    return std::string(num_digits - s.size(), '0') + s;
}

// A quick test of the code.
int main() {
    // First we'll write the first few values:
    for (unsigned value = 0; value < 256; value++)
        std::cout << paddedToString(value, 36, 4) << "\t";

    std::cout << "\n\n";

    // Then some values from around the middle of the range:
    unsigned base = 512 * 1024;

    for (unsigned i = 0; i < 256; i++)
        std::cout << paddedToString(i + base, 36, 4) << "\t";
}


If a regex match is found assign it to a variable

Do not set the materialCode to another string. I am not sure, but NA might also be a valid choice for Material=<value>. Instead, just set it to null.

As for the pattern itself, instead of searching for [^,] (anything except ,), you should look for only the valid values. Based on the given examples, I'd assume that only alphanumericals are accepted. If there is a limit on the length, then you should specify that as well.

Since, you are only looking for values assigned to Material property; no need to store the word Material as a matched-group result.

For eg.

Material=(?<value>[A-Z\d]{6})


Optimizing a script that switches function arguments in code files

General
C function arguments are only passed by position and not by name. As such, any attempt to make this modify real code is likely to break callers, and it's possible for that breakage to be silent during compile-time if the exchanged parameters have the same type. That makes this kind of refactoring deeply ill-advised. You're better off using the built-in signature refactoring feature of (pick any grown-up IDE).
Early continuation
Consider rewriting
        if(func_name in file_content):
            has_function = True

as
if func_name not in file_content:
    continue

Note that the parens have been dropped; you don't need a flag variable; and you can de-indent the rest of the loop.
Fragility
Before asking

How can this code be optimized for performance?

you need to make it correct, and it definitely isn't right now for all cases. Functions in C are easily (and fairly often) aliased by pointer, and these aliases will not be modified if the pointer doesn't have the same name as the original function. Following such aliases would only reasonably be done by calling into an existing C parser like Clang/LLVM, which you should probably be doing anyway for robustness.


I suggest that you start by considering what it means for two points to be the same vertex.

In the toxiclibs library, a Vec2D consists of an x- and y-coordinate, each stored as a float.  In shareVertex(), you've defined two Vec2Ds to be the "same" point if they are less than one unit apart.  (Using == to compare floats is generally a bad idea, so setting some threshold for equality is good, though 1.0 might be a bit sloppy relative to the precision that a float is capable of.)

However, in getTraingle() [sic], you use a different criterion for equality of Vec2Ds.  You're relying on a TreeSet<Vec2D> to do the de-duplication for you.  In the absence of any comparator given to the TreeSet constructor, it will use Vec2D.compareTo().  Vec2D.compareTo() is a bit weird: it compares vectors by their distance from the origin (the weirdness being that if two points are the same distance from the origin, the ordering will be somewhat arbitrary, thus breaking the Comparable consistency requirement — but that's of no concern to you).  What does matter to you, though, are:

All you care about is equality, but you'll end up doing a lot of wasted magnitude calculations instead.
Your criterion for equality in shareVertex() (less than one unit separation) is inconsistent with the criterion for equality in Vec2D.compareTo() (strict float equality).

Once you've figured out which endpoints of the line segments coincide, the actual coordinates no longer matter.  At that point, you would be better off treating this as a problem in graph theory rather than one in computational-geometry.  Your algorithm is currently O(n3) due to the three nested loops.  You could probably do better with a smarter algorithm.


Also I had a question over this line specifically:

if (sortVampire(fangOne + fangTwo + fangThree).equals(sortVampire(vampire)))

  Instead of concatenating all three fangs, would it be worth it to use
  a StringBuilder in this scenario?

Not in this case. The compiler is smart enough to replace the concatenation of the String with the use of a StringBuilder. Using a StringBuilder to create a String from multiple concatenation is typically useful when it is done inside a loop.

For 3 fangs of length 2, your code is straight-forward and will be performant. A couple of notes:

There is a mathematical property that could be used to further improve performance. For bigger lengths, it can improve considerably the performance.
To determine whether all of the fangs have the same digits as their product, you are currently creating a list of characters and sorting those lists to test for equality. You could do that in a simpler and faster way without sorting anything.

To support arbitrary vampireLength, i.e. an arbitrary count of numbers to multiply to make up the final vampire number, we can resort to a recursive algorithm. For that, we will define a method generate

List<String> generate(int fangLength, int vampireLength, int... previousNumbers)

It takes as input the fangLength (count of digits in each fang), the vampireLength (count of fangs) and the previousVampires (array of all the numbers considered so far). This previousNumbers will be sorted ascendingly by construction. It returns the list of all the solutions.

The base case is when vampireLength is 0: it means that previousNumbers contains all the numbers to decide whether their product makes a vampire number. In this case, we perform the multiplication of all those numbers and compare the digits together: if they are the same then we can build the String representing the solution and return it in a singleton list; if they are not, we can return an empty list.
In the recursive case, we need to loop over all the possible numbers. First, the upper bound to consider: with a count of digits fangLength to consider, the upper bound is simply \$10^{\text{fangLength}}\$. Then, the lower bound: if there were no previous numbers then it is 10 (the starting point); else it is the last considered previousNumbers (so the greater). For each of those possible numbers i, we concatenate all the solutions by invoking the generate method again, adding i to the previousNumbers.

A sample code would be:

private static List<String> generate(int fangLength, int vampireLength, int... previousNumbers) {
    if (vampireLength == 0) {
        int product = Arrays.stream(previousNumbers).reduce(1, (a, b) -> a * b);
        if (sameDigits(product, previousNumbers)) {
            String op = Arrays.stream(previousNumbers).mapToObj(String::valueOf).collect(Collectors.joining(" * "));
            return Collections.singletonList(op + " = " + product);
        }
        return Collections.emptyList();
    }
    List<String> list = new ArrayList<>();
    int end = (int) Math.pow(10, fangLength);
    int start = previousNumbers.length == 0 ? 10 : previousNumbers[previousNumbers.length - 1];
    for (int i = start; i < end; i++) {
        int[] currentVampires = Arrays.copyOf(previousNumbers, previousNumbers.length + 1);
        currentVampires[currentVampires.length - 1] = i;
        list.addAll(generate(fangLength, vampireLength - 1, currentVampires));
    }
    return list;
}

private static boolean sameDigits(int target, int... numbers) {
    int[] array = new int[10];
    Arrays.stream(numbers).flatMap(i -> String.valueOf(i).chars()).forEach(c -> array[c - '0']++);
    String.valueOf(target).chars().forEach(c -> array[c - '0']--);
    return Arrays.stream(array).allMatch(i -> i == 0);
}

Some notes in this code:

It is using the Stream API to make the code more fluent: the product is calculated by reducing over the array of numbers and multiplying each of them together; the String solution is build by joining all the numbers, converted to a String, separated by " * ".
The sameDigits method was rewritten to implement the simpler algorithm of checking whether the digits are the same.


I know this isn't what you're asking, but what's up with your variables? You should always turn on Option Explicit which will catch things like k, q and i not being dimensioned.

When you don't define your variable, VBA defines it as a variant. I'm pretty sure variants are objects:

  Performance. A variable you declare with the Object type is flexible
  enough to contain a reference to any object. However, when you invoke
  a method or property on such a variable, you always incur late binding
  (at run time). To force early binding (at compile time) and better
  performance, declare the variable with a specific class name, or cast
  it to the specific data type.

So you pay a penalty when you don't dimension your variables.

I imagine defining your variables might shave some milliseconds off over the long run.

For variables I'm getting 570ish

For selection I'm getting 950ish

For i=1 to 10000

using your variables is giving me about 5200
while using option explicit I'm getting around 5100.

For i=1 to 50000

option explicit is 24165
your variables is 24476

Option Explicit has the gainz.

And now, my version (why are you [A1].Selecting?) for i=1 to 50000 comes in at 23182. That right there should show you the .select statement was slowing it down.

Option Explicit

Private Declare Function GetTickCount Lib "kernel32.dll" () As Long

Sub UsingVaribles()
    Application.ScreenUpdating = False
    Dim NumberToday As Long
    NumberToday = 40000
    Dim StartTimer As Long
    StartTimer = GetTickCount
    Dim rngCells As Range
    Dim rng As Range
    Dim k As Long
    k = 1
    Dim i As Long
    Dim q As Long

    For q = 1 To 26
        For i = 1 To 50000
            NumberToday = NumberToday + 1
            Set rngCells = Cells(i, k)
            rngCells = NumberToday
        Next i
        Range(rngCells, Cells(1, k)).NumberFormat = "m/d/yyyy" ' 1 bug out
        k = k + 1
    Next q

    MsgBox (GetTickCount - StartTimer & " Milliseconds")
    Application.ScreenUpdating = True
End Sub


How can I reverse the first K elements of an array?

Performance

You know exactly how long the resulting array should be, so don't make the interpreter guess.  Any time the interpreter underestimates the length of an array and has to expand it, there's a significant performance penalty, as it reallocates a larger chunk of contiguous memory and transfers the already copied elements there.

var copyarray = new Array(arr.length);

That said, do you really need to copy the array?  If not, then you should just swap the first k elements in place for best performance.

As for the looping, it doesn't much matter whether you write it as one loop or two loops.  The running time will be dominated by the memory accesses: n reads and n writes.

Code hygiene

Did you really drop a vowel from the function name to save one byte?  If so, you are repeating Ken Thompson's greatest regret.

Although JavaScript allows you to omit semicolons at the end of each statement, it's considered bad practice to do so in all but the most trivial cases, such as Hello.

It's odd to have a function that just logs its results.  Either return copyarray (and let the caller call console.log()), or reverse the entries in place.


Computing the standard deviation of a Number array in Java

You are traversing the collection twice to determine the standard deviation when you could do it in a single pass.
Also, you could accumulate quickly rounding errors with the Math.pow(x.doubleValue() - average, 2.0) call. It would be best to implement the Kahan summation algorithm (that the Stream API has for DoubleStream#sum()).
In the lambda expression (x) -> x.doubleValue(), you don't need to add the parentheses around (x). You can just have x -> x.doubleValue(). You could also use a method-reference, which avoids a lamda, and have Number::doubleValue.

On Stack Overflow, I wrote an answer which calculates the standard deviation in a single pass with compensation. It is parallel-friendly:

static class DoubleStatistics extends DoubleSummaryStatistics {

    private double sumOfSquare = 0.0d;
    private double sumOfSquareCompensation; // Low order bits of sum
    private double simpleSumOfSquare; // Used to compute right sum for
                                        // non-finite inputs

    @Override
    public void accept(double value) {
        super.accept(value);
        double squareValue = value * value;
        simpleSumOfSquare += squareValue;
        sumOfSquareWithCompensation(squareValue);
    }

    public DoubleStatistics combine(DoubleStatistics other) {
        super.combine(other);
        simpleSumOfSquare += other.simpleSumOfSquare;
        sumOfSquareWithCompensation(other.sumOfSquare);
        sumOfSquareWithCompensation(other.sumOfSquareCompensation);
        return this;
    }

    private void sumOfSquareWithCompensation(double value) {
        double tmp = value - sumOfSquareCompensation;
        double velvel = sumOfSquare + tmp; // Little wolf of rounding error
        sumOfSquareCompensation = (velvel - sumOfSquare) - tmp;
        sumOfSquare = velvel;
    }

    public double getSumOfSquare() {
        double tmp = sumOfSquare + sumOfSquareCompensation;
        if (Double.isNaN(tmp) && Double.isInfinite(simpleSumOfSquare)) {
            return simpleSumOfSquare;
        }
        return tmp;
    }

    public final double getStandardDeviation() {
        long count = getCount();
        double sumOfSquare = getSumOfSquare();
        double average = getAverage();
        return count > 0 ? Math.sqrt((sumOfSquare - count * Math.pow(average, 2)) / (count - 1)) : 0.0d;
    }

    public static Collector<Double, ?, DoubleStatistics> collector() {
        return Collector.of(DoubleStatistics::new, DoubleStatistics::accept, DoubleStatistics::combine);
    }

}

It has the same logic as DoubleSummaryStatistics but extended to calculate the sum of squares.

With such a class, you can then have:

public static double computeStandardDeviation(Number... collection) {
    return Arrays.stream(collection)
                 .map(Number::doubleValue)
                 .collect(DoubleStatistics.collector())
                 .getStandardDeviation();
}


Is this recursion a bad idea and does it make for clean code?

Before explaining why I think recursion might be a bad idea here, let me show you the solution I came up with.

class Wave8 {

  public static void bounce() {
    String spaces = "";
    for (int i=0; i<80; i++, spaces += " ")
    {
        System.out.println(spaces + "a");
    }
    for (int i=0; i<80; i++, spaces = spaces.substring(1))
    {
        System.out.println(spaces + "a");
    }
  }

  public static void main(String args[]) {
      bounce();
  }
}

The advantage of this solution against the recursive one :

clarity : one can clearly see what was intended.
termination : there is no doubt on the fact that this solution will eventually return
no use of object members : if I call bounce() twice, I expect it to behave the same way twice.
performance : I'd expect this solution to be much faster.

On the other hand, many functions are much better when written in a recursive way. This is the case when it's easy to see that we call the function on a "smaller" problem.


Find the lengths of strongly connected components in a graph

class Graph:
    def __init__(self):
        self.graph = {}
        self.rev_graph = {}
        self.num_vertices = 0

This looks reasonable. Note that the PEP8 style guide wants you to add a blank line after each method.

    def addEdge(self, tail, head):
        if tail in self.graph:
            self.graph[tail].append(head)
        else:
            self.graph[tail]=[head]
        if head in self.rev_graph:
            self.rev_graph[head].append(tail)
        else:
            self.rev_graph[head] = [tail]

The failure to update self.num_vertices here does not look reasonable. I suspect that the reason is that num_vertices shouldn't be a property of the class.

    def dfs(self, visited, start_node, stack):
        visited[start_node] = True
        if start_node in self.graph:
            for i in self.graph[start_node]:
                if not visited[i]:
                    self.dfs(visited, i, stack)
            # del self.rev_graph[start_node]
        stack.append(start_node)

In future, please remove commented code before submitting the code for review.

I could use a comment to explain the purpose of stack, and why it adds in post-order rather than pre-order.

    def dfs_counter(self, visited, start_node, delim='  '):
        l1 = sum(visited)
        visited[start_node] = True
        if start_node in self.rev_graph:
            # print(delim, 'rev graph neighbors: ', start_node, self.rev_graph[start_node])
            for i in self.rev_graph[start_node]:
                if not visited[i]:
                    self.dfs_counter(visited, i, 2*delim)
        l2 = sum(visited)
        return l2 - l1
        # print(stack)

sum(visited) is expensive: too expensive to use in this method, which is called inside a loop. If you refactor to track the sum directly then I expect you'll see a notable speedup.

2*delim probably isn't really desirable: it should probably be delim + '  '.

    def find_scc_lens(self):
        self.num_vertices = len(set(list(self.graph.keys()) + list(self.rev_graph.keys())))

It should be possible to do this without using list.

        visited = [False]*self.num_vertices

This is buggy. num_vertices is the number of vertices, not the largest vertex. Consider the graph

g = Graph()
g.addEdge(2, 3)
g.addEdge(3, 2)

The output should be either [2] (vertices with no edges don't exist) or some permutation of [1, 1, 2] (with vertices 0 to 3).

        stack = []
        self.dfs(visited, 0, stack)
        # stack = stack[::-1]
        # print(stack)
        # del(self.graph)

This is also buggy. What about vertices which aren't reachable from 0? Even if you add documentation saying that this method only works for connected graphs, that doesn't rule out

g = Graph()
g.addEdge(1, 2)
g.addEdge(2, 1)
g.addEdge(1, 0)

        visited = [False] * self.num_vertices
        scc_lengths = []
        for k,i in enumerate(stack[::-1]):
            if not visited[i]:
                # print("rev graph node count", k, i)
                scc_lengths.append(self.dfs_counter(visited, i))
        return scc_lengths

In order to validate the correctness of this implementation, it would be immensely useful to have a comment which says which algorithm it implements (and ideally links to reference material).


Before starting with feedback on the actual code, I would like to share some thoughts about the style.

Chose a style, be consistent

Python comes with an official style guide called PEP8 which summarizes a whole lot of style advice and best practices generally to be used while coding Python. If you decide to stick with PEP8 or not is up to you, but if you chose a style, e.g. for variable names, stick to it. Your code has a mix of camelCase (e.g. iTrial), snake_case (e.g. initial_guess, actually most of the code is like this and also the PEP8 recommendation) and snake_swallowed_CASE_case (e.g. MC_analysis_a).

Another recommendation of PEP8 is to omit whitespace around = when used as keyword arguments to functions/methods. Incorporating the first one the line

yTrial = y_signal_a + np.random.normal(loc = y_signal_a, scale = e_signal_a, size = np.size(y_signal_a))

would become

y_trial = y_signal_a + np.random.normal(loc=y_signal_a, scale=e_signal_a, size=np.size(y_signal_a))

The same goes for np.array(...) and friends earlier in the code.

As a final note, do your future self a favor and document what you're doing in that function in a short little description right at the beginning. You might think you will remember your thoughts when looking at it in three months, but trust me, you won't. It is as simpe as:

def mc_analysis_a():
    """Running Monte Carlo analysis on some 1D sample data

    This function uses scipy.optimize.curve_fit to estimate the parameters of
    a simple x -> y timeseries.
    """

This type of documentation has the nice feature that it will be picked up by Python's built-in help(...) function.

The code itself

At the moment, there are some unused imports in your code (namely import scipy.optimize and from scipy.stats import kde, but that might be a symptom from bringing the code here on Code Review.

The next thing that caught my attention was that you do not use the estimated covariance matrix returned by curve_fit. If you really have no use for it, replace covariance_matrix by _ (underscore). This a convention used to tell yourself and others that you don't care about that (part of the) return value.

Next up comes total_iterations = 5000 as hardcoded value. If you ever try to increase or decrease that value you would have to edit your function before rerunning the experiment. A more convenient approach from my point of view would be to use it as input parameter with an default value of 5000. The same applys to initial_guess and friends. (Sidenote: if you were to use initial_guess' current value as default value and ever modified it in the function, funny things can happen. See this link for more information on this topic, since this would get to involved for this review.)

Now to the core loop of the function. While generating the noisy y values, np.size(y_signal_a) should be equal to y_signal_a.size. In your case, one could also use y_signal.shape in that spot which would then guarantee that the noise also fits the shape of the array if it was multidimensional.

Using try: ... catch: ... without specifying an exception type is considered a bad practice since it will catch all kinds of exceptions including keyboard interupts (Ctrl+C). So if you ever decide to stop the test because 5000 iterations where to much, well, you would have to kill the Python process itself. The documentation of curve_fit lists all the exceptions that might be raised while using this function. These are ValueError for bad input data or input options and Runtime Error in case the least-squares minimization failed. So these would likely be your candidates to catch, with the following construct:

try:
    ...
catch (ValueError, RuntimeError):
    continue # or handle the exception however you want

This would still stop the execution if something unexpected has happened and, as you can see, works for multiple exceptions as well.

On the same loop you're using the NumPy array MC_pars to collect the results of those iterations step by step. As you might have noticed NumPy arrays are not really comfortable to use in an expanding way since their main purpose is to allow fast vectorized operations on "fixed" size numerical data (though their use is not limited to that). At this point using a simple Python list might be a better option. This would allow you to .append(...) the results of every run very conveniently. And, as you seem to know, it's quite easy to convert Python iterables (lists, tuples) into NumPy arrays.

For reference you can find the modified version of the total script below.

import numpy as np
from scipy.optimize import curve_fit

def mc_analysis_a(total_iterations=5000):
    """Running Monte Carlo analysis on some 1D sample data

    This function uses scipy.optimize.curve_fit to estimate the parameters of
    a simple x -> y timeseries.
    """
    x = (0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.064, 0.128)
    y_signal_a = (1.0, 0.83, 0.71, 0.62, 0.55, 0.49, 0.45, 0.42)
    x = np.array(x, dtype = float)
    y_signal_a = np.array(y_signal_a, dtype = float)
    e_signal_a = (0.06, 0.05, 0.04, 0.05, 0.04, 0.02, 0.04, 0.03)

    def func(x, a, b):
        return a * np.exp(-b * x)

    initial_guess = [1.0, 1.0]
    fitting_parameters, _ = curve_fit(func, x, y_signal_a, initial_guess)
    print(round(fitting_parameters[1], 2))

    # ---> PRODUCING PARAMETERS ESTIMATES
    mc_pars = []
    for _ in range(total_iterations):   # i was replaced by _ here, because it was not used
        x_trial = x
        y_trial = y_signal_a + np.random.normal(loc=y_signal_a, scale=e_signal_a, size=y_signal_a.shape)
        try:
            iteration_identifiers, _ = curve_fit(func, x_trial, y_trial, initial_guess)
        except (ValueError, RuntimeError):
            continue

        mc_pars.append(iteration_identifiers)

    # ---> SLICING THE ARRAY
    mc_pars = np.array(mc_pars)
    print(mc_pars.shape)
    print(mc_pars[:, 1].std())

if __name__ == "__main__":
    mc_analysis_a(5000):


Surely this is possible. Only the fetch and parse functions would need to call notify with the respective message on the Deferreds they return. The code then could look like this:

fetchSomeData().pipe(parser).progress(showMessage).done(hideMessage, updateView);


If you are certain that you only have standard ASCII characters in the file, it's more efficient to just map the whole space and print it out with a counting sort.

The idea is that you use the character itself (a number between 0 and 255) as the index of an array, count how many of those are in the file, and then write the array starting from the beginning.

This is some sample code. Please note that I cannot test it right now, but it should give you a basic idea on how to do it.

#include <stdio.h>

int main()
{
    //You may want to consider a 'long long' type
    long char_count[256];

    FILE *input_file, *output_file;

    input_file = fopen("ltr.txt","r"); //Assuming that the file exists
    output_file = fopen("aux.txt","w+");
    memset(char_count, -1, 256);
    char input_char;
    while (input_char = getc(input_file)) {
        char_count[input_char] = char_count[input_char] > 0 ? (char_count[input_char] + 1) : 1;
    }

    int index;
    for (index = 0; index < 255; index++) {
        if (char_count[input_char] > 0) {
            int char_index;
            //Can be optimized by building a format string and using fprintf
            for (char_index = 0; char_index < char_count[input_char]; char_index++) {
                fputc(char_count[input_char], output_file);
            }
        }
    }
    fclose(output_file);
    fclose(input_file);

    return 0;
}


Safely pruning merged topic branches locally

The final line has no effect:

trap error SIGHUP SIGINT SIGTERM

As the program is about to exit, we're exceedingly unlikely to receive any of those signals between this point and the end of the program.

It's much more usual to set the trap handler as soon as you've defined the error function.

Similarly, the exit trap

trap statistics EXIT

is the same as simply

statistics

when we're about to exit.  I suggest that this line is moved to before Step 1, too.


One prevailing pattern is stateless components. You will most likely have components that require state, but it is easier to follow the flow of data (and write tests) if your components rely solely on props. The stateless pattern is somewhat similar to yours (in that they are both mutating state in the parent), but instead of proxying calls to setState on the top level component AND having to re-implement setState in each component, child components just call the methods passed from the top level to mutate the state and then receive the new data in the form of props.

From React Docs:

  In an ideal world, most of your components would be stateless
  functions because in the future we’ll also be able to make performance
  optimizations specific to these components by avoiding unnecessary
  checks and memory allocations. This is the recommended pattern, when
  possible.

Here is your example using stateless components (except for the top level component):

const { Component } = React;

const MainList = (props) => {
   const {children} = props;
   return (

{children}

   );
}

const MainListContent = (props) => {
   const {title, items} = props;
   return (

{title}

{
            items.map((item, index) => (

 props.onSelectItem(item.name)}
                   style={{cursor: 'pointer', fontWeight: item.selected ? 'bold' : 'normal'}}
               >{item.name}

              ))
        }

   );
}

class UserList extends Component {
  constructor(props) {
    super(props);
    this.state = {
        items: props.items.map(item => ({
            selected: false,
            name: item
        }))
    }
  }
  onSelectItem(itemName) {
    let { items } = this.state;
    this.setState({
        items: items.map(item => {
            if (item.name === itemName) {
                item.selected = !item.selected;
            }
            return item;
        })
    });
  }
  render() {
    const { items } = this.state;
   return (
      <MainList>
        <MainListContent ref={ref => { this.mainListContent = ref; }} onSelectItem={this.onSelectItem.bind(this)} title="Users" items={items} />

count: {items.filter(item => item.selected).length}

      </MainList>
    )
  }
}

const Root = props => (
  <UserList items={['foo', 'bar', 'baz']}></UserList>
);

ReactDOM.render(
  <Root />,
  document.getElementById('root')
);


Do you see any flaws in these prepared statements to avoid SQL injection?

Your code does not have an SQL injection vulnerability because you are using placeholders instead of interpolating the variables. The way you interface with the database is laudable.

Other aspects of your code can be improved:

The variables $gdb, $statement, $rs, and $e are globals, which is not acceptable within a larger system. Enclose your code with a function to make them locals.

Otherwise, you could accidentally overwrite variables from other parts in your code (e.g. when you include this snippet). Consider what happens if $gdb is already assigned: You try to clean up your usage by assigning null when you are finished, but the other code now suddenly has its contents for $gdb deleted.
You do not seem to be using any intendation. Indent your code properly so that it can be understood easily.
You use the literal ¡ inside a string, and print it directly to the output. As this is a non-ASCII character, this can get problematic depending on the encoding of your source code and the character encoding in the HTTP header and the HTML document.
HTML markup is a kind of code as well – it too wants to be indented :)

But now something important:

  Do not use md5 to hash passwords!

MD5 is extremely weak, and an increasing number of attacks are being discovered. Do not use it for anything in new systems.
It is meant for checksums (e.g. when comparing files), not for hashing passwords. Such a checksum is designed that a subtle change in the input changes the output of the hash function drastically. It is not designed to irreversibly scramble a secret.
It is far to easy to calculate the original password from a given hash, e.g. using rainbow tables. You do not even use a salt to defend against this (but even with a salt, an MD5-hashed password can be cracked within reasonable time).

You should be using a key-stretching algorithm like bcrypt. I already wrote a rant about secure password hashing in another answer which I would ask you to consult for a better hashing solution.


Calculate fractions of positive, negative and zeros

Using the predicates in your case could be expensive for big list since you use 3 meaning 3 complete iteration on the list.

Here is a small update of you code (I can't use the Java 8 API since I only have the Java 6 at the office ...) to do the same check but without predicate (or if else)

    Scanner scan = new Scanner(System.in);
    int size = scan.nextInt();
    scan.nextLine();

    int[] sum = new int[3];

    String s = scan.nextLine();
    String[] array = s.split(" ");

    double total = array.length;
    for(String d : array ){ //Here, you shoud use your list instead of my array
        sum[Double.compare(Double.parseDouble(d), 0) + 1]++;
        //compare will return -1 | 0 | 1, adding one to increment the correct cell in the array.
    }

    DecimalFormat df = new DecimalFormat("#.000000");
    System.out.println(df.format(sum[2]/total));
    System.out.println(df.format(sum[0]/total));
    System.out.println(df.format(sum[1]/total));

PS : I could update the code to match your List but to prevent any typo, I prefer to show you the logic I used with the API I can use.


I am going to critique your Response class. Firstly, I think that code should handle the common cases really well, and, hopefully, success happens often.

I would create a constant SUCCESS instance to indicate the success, and all other instances are fails. As a consequence, I would not have the withComment method. How about:

public final class Response {

    public static final Response SUCCESS = new Response();

    private final String  comment;

    private Response() {
        this.comment = null;
    }

    public Response (String comment) {
        this.comment = Objects.requireNonNull(comment, "Fail responses require a non-null comment");
    }

    public String comment() {
        return comment;
    }

    public boolean isSuccessful() {
        return this == SUCCESS;
    }

}

With the above class, any constructed Response is automatically a fail... only the static SUCCESS instance is a success.

Your use code then becomes:

public Response sendFirstInquiryEmail(long itemId) {

    Item item = itemService.findById(itemId);

    if (item == null) {
        return new Response("Can't find item");
    }

    if (State.NEW != item.getState()) {
        return new Response("Can't send first inquiry to customer for items not in 'NEW' state");
    }

    if (!item.hasNumber()) {
        return new Response("Can't find ticket in OTRS");
    }

    if (!item.isActive()) {
        return new Response("Item is not active anymore");
    }

    if (!item.isReady()) {
        return new Response("Item is not finalized, first inquiry can be send only for processed items");
    }

    send(item);

    return Response.SUCCESS;

}

As for all those conditions that are tested in the cascading if blocks? Well, there's not much you can do about that. They are guard conditions. Your only option is to perhaps incorporate the cascade somewhere else, but all that does is shift the logic.

I would live with it. It is clear, flows logically, and so on.


Instead of calculating all the function returns and then checking which one the user input why not just run the function after checking the users input.

For example instead of

add = addition(val1, val2)
if sym == "+"
    puts add

Why not

if sym == "+"
    puts addition(val1, val2)


First of all, I'd always avoid side-effects. That is, don't modify an object that was passed in; return a new object instead. So no !-methods.

Second, I'd reduce the method to only handle the Sizes array itself. Don't call the method unless there's something to process. That means checking AssetType and data['Sizes'].any? elsewhere.

Third, the name of the method is non-descriptive, in my opinion. It doesn't get anything, since it modifies what you give it, and "parsed asset data" is so generic that it doesn't tell me what the method actually does. Obviously it's something to do with t-shirts and their sizes and descriptions, so that should probably feature in the name.

Then you're left with something like:

def get_unique_tshirt_sizes(sizes) # or some other name
  sizes
    .select { |size| size.key?('TeeShirtSize') && size.key?('Description') }
    .uniq { |size| size['Description'] }
end

This method operates only on the sizes array, and it returns a new array rather than destructively updating an existing one.

You might use it like so:

if data['AssetType'] == 'Image' && data['Sizes'].any?
  sizes = get_unique_tshirts_sizes(data['Sizes'])
end


Speed up counting sort algorithm in Ruby

arr.count(j) scans the array, so it takes linear time. Doing it once for each element of arr.uniq takes quadratic time. Doing it 100 times doesn't help either. :)

The arr.uniq.each loop is unnecessary, though (as is the call to uniq). The problem is to count the entries less than i, and you can express that directly:

counter = arr.count {|n| n <= i}

This takes linear time, so it should be much faster.

For another speedup, you can solve the whole problem with only one pass over the input, not 100. As the problem description hints, you'll need an auxiliary array to store the counts.

By the way, the first four lines can be replaced by one, using one of Ruby's convenient utilities:

input = $stdin.readlines

The whole program can be simplified to two lines.


What is a safe way to lock a thread in a single-threaded application?

Is this a safe way to locking a thread?

Yes, it's the recommended way: see for example std::lock_guard

However:

I don't see why the destructor is virtual
You should probably disable/prevent the copy constructor and assignment operator
The constructor should probably take a reference (which can't be null) not a pointer
Try to ensure (though you're probably doing this already) that the destructor will not throw an exception

  Will the thread become unlocked if an exception occurred within Foo() and the catch block catches the exception?

It will unlock when CProcessCritSec is destroys, which happens as soon as it goes out of scope, which happens whenever you leave the try statement (before you enter any catch statement).


One array solution
The following algorithm is an improvement on the two array system stated bellow it.  Basically, we only need the context of the old previous value (as well as the next value, which goes unmodified), so we copy this value.  From there we can set the new end to 1 then start over.  This cuts down on the memory overhead.  I think you'll see minimal computational improvements as yours was already pretty efficient, but this one takes less memory.  I suspect there will be a performance increase where you are dealing with pretty large arrays.
import java.util.Arrays;

class Pascal{

     public static void main(String []args) {
        int toNthLine = 1000;
        int[] row = new int[toNthLine+1];
        int counter = 0;
        int previous;
        row[0] = 1;
        for (int i = 0; i < toNthLine; i++) {
            previous = 1;
            for (int j = 0; row[j+1] != 0; j++) {
                int temp = row[j+1];
                row[j+1] = previous + row[j+1];
                previous = temp;
                if (row[j+1] % 2 == 0)counter++;
            }
            row[i] = 1;
        }
        System.out.println(counter);
     }
}


Determining winning line in TicTacToe game

First off, considering the small number of lines and items in a line, your (and my following) optimizations are probably not really worth it. That said, as you have noticed, your loops run through all all items, even when not necessary, and that would be bad in more complex situations.
Generally your code tends to be a bit too complex/verbose. For example, isLineCompleted would be much simpler using a regular for loop and early exit:
private boolean isLineCompleted(Predicate<Integer> predicate) {
    for (int i = 0; i < size; i++) {
         if (predicate.test(i)) {
             return true;
         }
    }
    return false;
}

By extracting the checks loop into a separate method, the same pattern could be used there.
Or Java's Stream has the .anyMatch() method, which simplifies it even more:
return checks.stream().anyMatch(this::isLineCompleted);

Using a IntStream allows isLineCompleted to do simular using .allMatch():
private boolean isLineCompleted(Predicate<Integer> predicate) {
    return IntStream.range(0, size).allMatch(predicate);
}

One final point: The value B in the Cell enum is badly named considering you need to add the comment "blank cell". Call it BLANK instead. Also it would seem more logical to put it first in the enum, where it would have the cardinal value 0. Or you may even want to drop it all together and just use null.


Tiny Encryption Algorithm implementation in C

Good formatting and layout.

Aside from bug, good code.

Bug?

I'd expect v[1] + delta, v[0] + delta per Tiny Encryption Algorithm.

// Reference code
// for (i=0; i < 32; i++) {                       /* basic cycle start */
//     sum += delta;
//     v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
//     v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
// }

  for (int i = 1; i <= 32; i++) {
    //            v--- ???
    v[0] += (v[1] * delta) ^ ((v[1] << 4) + k[0]) ^ ((v[1] >> 5) + k[1]);
    v[1] += (v[0] * delta) ^ ((v[0] << 4) + k[2]) ^ ((v[0] >> 5) + k[3]);
    delta += BASE_DELTA;
  }

Questionable sample code.

*key = key_val; only sets the first element of key[4],   Certainly the below functionality was desired.

// *key = key_val;
key[0] = key_val >> 0;
key[1] = key_val >> 32;
key[2] = key_val >> 64;
key[3] = key_val >> 96;

Use standard types

Use standard types from #include <stdint.h> like uint32_t instead of u_int32_t.  They are better known and more portable.

Minor

const

Use const as able to convey code's intent.

// void encrypt(u_int32_t* v, u_int32_t* k) {
void encrypt(u_int32_t* v, const u_int32_t* k) {

// void encryptFile(const char file_to_encrypt_path[], u_int32_t key[4]) {
void encryptFile(const char file_to_encrypt_path[], const u_int32_t key[4]) {

Make constants unsigned

Make constants unsigned for unsigned variables by adding u.

// #define BASE_DELTA 0x9e3779b9
#define BASE_DELTA 0x9e3779b9u

Unneeded *1

Perhaps there is some reason for this, - I do not see it.

// u_int32_t delta = BASE_DELTA * 1;
u_int32_t delta = BASE_DELTA;

Debug code?

Clearing the block serves little aside from cleaner debug.  Don't use a type unrelated to the variable.

// memset(block, 0x0, sizeof(u_int64_t));
memset(block, 0x0, sizeof block);

0 base

Starting from 0 is more C-ish, yet I have no real issue with OP's code.

// for (int i = 1; i <= 32; i++) {
for (int i = 0; i < 32; i++) {

Avoid naked magic numbers

TEA uses 64 rounds, nice to self-document that in code

#define TEA_ROUNDS 64
for (int i = 0; i < TEA_ROUNDS/2; i++) {

open() test, close()?

Missing tests if open() success.
Missing close(), x2, in encryptFile().

Advanced

restrict

Use restrict (C99) to let encrypt() know that v, k do not overlap.  This allows for some optimizations.

// void encrypt(u_int32_t* v, u_int32_t* k) {
void encrypt(u_int32_t* restrict v, const u_int32_t* restrict k) {

Out of range constant.

0x7A24432646294A404E635266556A586E is out of range of most compilers, even when __uint128_t exists.

Portable code would use a different way to set the key as well and a different type.  Good that it work for you.


Welcome to code review, and good job for your first program I suppose.

Style

Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules,
functions, classes, and methods. As you can see, even for a
relatively simple function, documenting using comments quickly makes
it unpleasant and difficult to read. So, to solve this, the docstring
was introduced. You should include docstrings to the functions you
created indicating what they return and some type hints if necessary.

def app(user_name):
    """Print user name."""

def create():
    """Create new account."""

Descriptive variable names: The name app(user_name) can be changed to print_username() since it's a good practice to create
descriptive variable names which improve readability for you and for
other people using your code. Same goes for create() that can be
create_account()
PEP0008 The official Python style guide https://www.python.org/dev/peps/pep-0008/ I suggest you check this, will help you write more pythonic code.
Blank lines: Your functions contain many blank lines and according to PEP0008 you should use blank lines sparingly:
Surround top-level function and class definitions with two blank
lines. Method definitions inside a class are surrounded by a single
blank line. Extra blank lines may be used (sparingly) to separate
groups of related functions. Blank lines may be omitted between a
bunch of related one-liners (e.g. a set of dummy implementations).

Code

The code is a bit long and can be shortened. Storing all usernames and passwords and everything else in the same file I think is a bad idea and is very unreliable because all things would be mixed up and you don't know which is what, I suggest you create a .txt file for each user and make the file name same as the user name so the program checks the folder and if the user is not found, it prompts the user accordingly.  And still this is not the best way to do it however it is better than mixing all things up.

exists = os.path.exists("C:/Users/Tom/Desktop/test/login_project/account_info.txt")

this line should be cleaned up or replaced by input() (If i'm using your code it's very obvious that the path will not exist and the condition if not exists: will always evaluate to True.

info_list = [user_name, password, email]

The variable user_name is referenced before assignment, you should define your variables at the top of the function body to avoid such problems.

unused variable(line 103) you should clean such things up upon completion.

main_choice = ""

Bug:
This appears after creating a new account and trying to login.
 - Error: [0] account(s) found in database

These are unecessary variables:

creating_username = True
creating_password = True

followed by while creating_username: and while_creating_password:

which can be written:

while True:
    # block

and same goes to entering_info = True and main_choosing = True in other functions.

else:
    creating_username = False

can be replaced with break in the following way:

else:
    break

instead of manually closing the file you just opened, you may use with & as context managers that automatically carry the opening and closing activities for you in the following way and the file will be closed automatically.

f = open("account_info.txt", "a+")
f.write(f"{info_list}\r\n")
f.close()

can be written:

with open('account_info.txt', 'a+') as data:
    # do things

line 69: the file was opened twice (I think you forgot to clean this up)

f = open("account_info.txt", "r")

file_contents = f.read()

f = open("account_info.txt", "r")
list_ = [char for char in f.readlines() if char != "\n"]

Descriptive variable names: I think this is the second time I mention this: a code is designed to be interpreted by machines and to be read and understood by human beings, try as much as you can to avoid ambiguous variable/method/function names.

for i in list_:
for y in list_:
counter_one = 1
counter_two = 1

what is i? what is y? what is counter_one what does it count? what is counter_two?

print("\nWelcome.\n")
choosing()

if __name__ == '__main__': guard to be used at the end of your script, allows your module to be imported by other modules without running the whole script.

This should be placed at the end of your script like the following:

if __name__ == '__main__':
    print('\nWelcome.\n')
    choosing()

I tried to simplify your program and here's what I came up with (And still this is not the proper way to do it in the real world, it's just for the sake of the example) and you might modify it if you want it to keep running and keep asking for input or whatever structure you want, you might consider this as an assignment:

import os

def create_account(path):
    """Create and save username to a Usernames folder."""
    if 'Usernames' not in os.listdir(path):
        os.mkdir('Usernames')
    os.chdir('Usernames')
    new_username = input('Enter new user name: ')
    if new_username + '.txt' in os.listdir(path + 'Usernames'):
        raise ValueError(f'Username {new_username} already exists.')
    new_password = input('Enter new password: ')
    confirm_pass = input('Confirm password: ')
    while new_password != confirm_pass:
        print('Passwords do not match!')
        new_password = input('Enter new password: ')
        confirm_pass = input('Confirm password: ')
    with open(new_username + '.txt', 'w') as new_user:
        new_user.write(new_username + ' ')
        new_user.write(new_password)
    print(f'Account created successfully.')

def login(path):
    """Login using user name and password."""
    if 'Usernames' in os.listdir(path):
        os.chdir('Usernames')
        username = input('Enter Username or q to quit: ')
        while username + '.txt' not in os.listdir(path + 'Usernames') and username != 'q':
            print(f'Username {username} does not exist.')
            username = input('Enter Username or q to quit: ')
        if username == 'q':
            exit(0)
        password = input('Enter password: ')
        if username + '.txt' in os.listdir(path + 'Usernames'):
            user, valid_pass = open(username + '.txt').read().rstrip().split()
            while password != valid_pass:
                print('Invalid password.')
                password = input('Enter password: ')
            print('Login successful.')
    else:
        print('Database not found!')
        exit(1)

def start_login(path):
    """Run login interactively."""
    print('Welcome to my program.')
    user_mode = input('Enter L for login or C for creating a new account or Q to exit.').lower()
    while user_mode not in 'lcq':
        print('Invalid command')
        user_mode = input('Enter L for login or C for creating a new account or Q to exit.').lower()
    if user_mode == 'l':
        login(path)
    if user_mode == 'c':
        create_account(path)
    if user_mode == 'q':
        print('Thank you for using my program')
        exit(0)

if __name__ == '__main__':
    database_path = input('Enter database path: ').rstrip()
    while not os.path.exists(database_path):
        print('Invalid path')
        database_path = input('Enter database path: ').rstrip()
    start_login(database_path)


First of all, let me say well done on the progress made from your first question to now!

Code Review is for reviewing code

As you seem to be seeking advice "about how to implement" an idea (i.e. streams), I think you may be better off asking on Programmers.SE, since that is a more appropriate place for questions about "software architecture and design" and "algorithm and data structure concepts".
Code Review is "not for questions about broken code, hypothetical code, or non-existent code, as such questions will be closed as off-topic." (taken from this help page).

I can see that you have code already, and are seeking to improve it (in a way that doesn't add any functionality) - so I consider your question to be on-topic.  Although your desire to learn about other ways of implementing it entirely may not be best placed on this site.

A Quick Review

Remove old code
You have included the (now unused) code for parseElegant (version 1).  While I can understand you not wanting to erase this, you have already linked to your previous question (which contains the old code).  Including version 1 here just adds ~24 lines for reviewers to have to scroll through.

Can't you just use strip?
The wordBeautify function (which you are seeking to make redundant/remove) seems to be VERY similar to the Python built-in string.strip method?

Consider the following code:

test="{:foo }"
(x,y)=wordBeautify(test,0,len(test)-1)
a=test[x:y]
b=test.strip(' "{,:}')

Result:  a and b both work out to be "foo"!

Use better variable names!
At present, your parseElegant2 function takes an argument called str1.  While it is obvious that this means something along the lines of the first string - it is not actually particularly helpful in knowing what that variable represents.

Something more like json, text_candidate, or candidate may be better - as it expresses that this is a long text containing json, or something that is a candidate to be processed into JSON.

You have a similar issue in wordBeautify, with word1.  This could just be named word, or similar.

Return is better than print
I've noticed that in your function you are not return'ing any values.  Instead you are just print'ing to the standard output (STDOUT).
Is this your goal? Or will your program eventually need to construct some kind of data structure (such as a dict) of the JSON values?

I would recommend refactoring your code to return a data structure, and have your function write the JSON values into that data structure.

A word on string stream processing

As @ferada commented, I think you should "consider using a stream, looking only at the (single) next character at a time and then build a state machine around it.", however your current program is not doing this.

Instead, your loop is going through the indices of the string.  And is (at present), also calling your wordBeautify function to do the same (with indices).

Rather than using for i in range(len(str1)):, as you currently are - I would recommend that you loop through the characters themselves (one at a time, as @ferada suggested).  Thus, your loop may look more like: for c in str1:

This way, you are essentially forced into only looking at the current character. (i.e. you are unable to increment/decrement any number value to go forwards or backwards in the string.)

Constructing a state machine

From the Wikipedia article about Finite-state machines:

  A finite-state machine (FSM) or simply state machine, is a mathematical model of computation used to design computer programs.  It is conceived as an abstract machine that can be in one of any finite number of states.  The machine is in only one state at a time, called the current state. It can change from one state to another when triggered, this is called a transition.  A particular state machine is defined by a list of its states, and the triggering condition for each transition.
   (Emphasis mine)

You can read the article for more background information, but essentially your are seeking to construct a state machine.  As you can read in the last sentence (that I've bolded), this requires:

a list of states
the trigger conditions for each state transition

What are the states?

Luckily, the official JSON website (JSON.org) actually gives us these exact things!
In the form of railroad diagrams.  Specifically, they tell us that:

  An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

  (source: json.org)

So we know that STRING is a state, for example.  They also tell us how we get into (and out of) the STRING state:

  A string is a sequence of zero or more Unicode characters, wrapped in double quotes...

  (source: json.org)

So we know that a STRING state is triggered when we encounter a " (quote) character. (And that it ends the same way.)
Note:  For now, let's ignore the backslash (\) escape style string components.

We also are told what a VALUE might be as well:

  A value can be a string in double quotes, or a number, or true or false or null...

  (source: json.org)

This gives us another state, namely NUMBER - since a value can be a number.

Some limitations (Let's not reinvent the whole wheel)

We already know that you only want to deal with "flat JSON (no hierarchy) for keys and values".
So, we'll forget about OBJECT and ARRAY in the diagram above. ;-)

Let's also (just to make it easy), ignore the fact that a value can be true, false, or null.  (i.e. it is either a string or a number).

The states so far

So far, we have been able to use the official JSON.org website diagrams to determine we have the following two states:

STRING
NUMBER

We also know that a string is triggered by the condition: c=='"' (where c is our stream's current character).

But how is a NUMBER triggered?
Well the JSON.org website has a rather complicated way of detecting numbers (which takes into account negative numbers, scientific notation, etc).  but for these purposes let's just say that a NUMBER is triggered by a sequence of 1 or more of the following characters: 0123456789. (the decimal point is included).

Other transitions

If we look back at the first railroad diagram:

We can see that the COLON (:) and COMMA (,) characters are also transitions between states..

Putting it all together

If we combine all of these states and transitions, plus the idea of a character (rather than index) loop, and the other improvements I've mentioned - we can produce a single function which is capable of processing a JSON string "all at once":

def parseElegant3(candidate):
    READY=0
    STRING=1
    NUMBER=3
    COLON=-1
    COMMA=-2

    search={'"':STRING,  ':':COLON,  ',':COMMA,  STRING:'"',  COMMA:','}
    NOP=" {\t}\r\n"
    stringIgnore='{,:}'
    numbers='0123456789.'

    result={}
    if not len(candidate):
        return result
    accumulator=""
    mostRecentKey=None

    state=READY
    for c in candidate:
        newState=state
        if state is READY:
            if c in NOP:continue
            if c in numbers:
                newState=NUMBER
            if c in search.keys():
                newState=search[c]
        if newState is COLON:
            newState=READY
            if len(accumulator):
                accumulator=accumulator.strip()
                result[accumulator]=None
                mostRecentKey=accumulator
                accumulator=""
            else:
                state=READY
                continue
        elif newState is COMMA:
            newState=READY
        elif newState is NUMBER and not state is NUMBER:
            accumulator+=c
        if state is STRING and newState is STRING:
            if c in stringIgnore:continue
            if c==search[STRING]:
                newState=READY
                if not mostRecentKey is None:
                    result[mostRecentKey]=accumulator
                    accumulator=""
                    mostRecentKey=None
            else:
                accumulator+=c
        elif state is NUMBER:
            if c in numbers:
                accumulator+=c
            else:
                if c in NOP:continue
                assert c == search[COMMA]
                try:
                    result[mostRecentKey]=int(accumulator)
                except ValueError:
                    result[mostRecentKey]=float(accumulator)
                accumulator=""
                mostRecentKey=None
                newState=READY
        state=newState
    return result

JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": "home green"}'

parseElegant3(JSONString)


Method to separate a list of ports to scan

Comments

You have too many of them. Stick to comments that clarify the intent behind code instead of documenting the syntax.

When I see

List<int> listOfPorts = new List<int>();

I know already that it's a list of integers, intended to represent the ports. Comments should explain why you do what you do, for example:

// List of ints instead of strings so we can perform arithmetic logic

Whitespace

This is more personal but your code feels very spread out. You don't have to leave a space between every line of code (although I'll admit that the braces are  a major part of it).

Braces

If you omit braces, you will guaranteed end up with a logical error one day. What if you decide to add something else to this code snippet but aren't paying 100% attention?

else
    listOfPorts.Add(Convert.ToInt32(portList[i]));

This will be a pain to debug.

For situations like this it is more forgiving, but honestly is there such a difference between

if (item <= 65536)
 listOfPorts.Add(item);

and

if (item <= 65536) {
     listOfPorts.Add(item);
}

Exceptions

You have an empty catch block. That's no bueno, there should be some sort of feedback to the user that tells him what went wrong (at the very least there should be logging in place).

Abstraction

Your return statement is List<int>. Is this a conscious design choice? You might want to read up on the reasoning why I prefer IEnumerable<int>.

Naming

Two variables are respectively portList and listOfPorts. First of all: remove the underlying datastructure from the name.

In a way this can also be seen as enforcing encapsulation: it allows you to change the implementation to, for example, a Dictionary without suddenly having a discrepancy between the implementation and the variable name.

More descriptive names could be input/inputPorts/unparsedPorts and ports/parsedPorts/resultPorts, etc.

Input boundaries

I don't see any boundary checks to verify the following things:

No negative numbers
No positive numbers outside the range of ports
A range should only consist of 2 values

Loop clarity

I consider

int max = range[range.length - 1];
// ...
j <= max

to be easier to read than

j <= range[range.length - 1]

This is a minor gripe, but it can be confusing given how "<= length - 1" is usually interpreted in the condition section of a for loop (which usually gets refactored to "< length").

Duplicates

When you don't want duplicates, a List<T> is not your preferred datastructure. Instead, use a Set<T> like HashSet<T>. This will automatically take care of it for you.

If you combine it with your sorting at the end you can use a SortedSet<T> instead:

  A SortedSet<T> object maintains a sorted order without affecting performance as elements are inserted and deleted. Duplicate elements are not allowed.

Complexity

You're doing a lot of things with a lot of lists of ports (better naming would have come in handy here!).

This is what you do:

Create list (A) of input ports
Parse A into another list (B)
Create new list that holds unique values from B
Clear B
Add all ports that adhere to a boundary check to list B
Sort B

That's a lot of stuff that we can refactor.

First of all: put that boundary check earlier in your code. Once a port is added to our result list of ports, it is a valid port. We don't want to copy everything to a new list just to add that boundary check (and you need more than that!).

In fact, now it's already a lot easier: by using the SortedSet<T> you will already do the sorting and duplicate removal so that's not needed either.

Best part: SortedSet<T> implements IEnumberable<T> so you can simply return your set as-is.


Check existence of matching key,value pair

I would say that hasOwnProperty is not necessary in this case. If you want to make it O(n) you probably have to first convert one of the arrays into a hash of colors so that you can improve lookup speed. Something like:

var a = [{color:'blue'},{color:'green'}, {color:'brown'}, {color:'black'}];
var b = [{color:'white'},{color:'yellow'}, {color:'black'}, {color:'blue'}];
var aColors = a.reduce( function(obj, hash) { obj[hash.color] = true; return obj }, {} );

var expectedOutput = [];
for(var i=0; i<b.length; i++) {
 if (aColors[ b[i].color ] )
  expectedOutput.push( b[i] );
}

console.log(expectedOutput);


Find number of divisors for integer and sum of integers

The first function can be sped up by just iterating up to sqrt(myno) and adding 2 instead of 1 to divsrs when k divides myno unless k is the square root of myno (in which case you would only add 1).

The second function already takes constant, but you can get rid of the multiplication and division, by simply returning cur_no + idx and using cur_no < ULLONG_MAX - idx to check whether there'd be an overflow.

Now a couple of style notes on the code:

First of all, it seems strange to me to pass the file handle to the functions, if they don't actually write to (or read from) the file. I see that you did so you could close the file before exiting the program in case of an overflow. I would rather recommend that you return an error value when an overflow occurs and then close the file and exit in the calling code.

Further your while(1) loop in find_no_of_divisors is actually a pretty plain for-loop and should be written as one. No need for complicated control flow for something so simple.

Lastly I would not recommend dropping (some) vowels from variable names like you do in divsrs - that just leads to typos.


Here's my approach:

function solution(n) {
    var maxZeros = 0;
    while(n !== 0 && n % 2 === 0) {
        n >>>= 1;
    }
    for(var curr=0; n !== 0; n>>>=1) {
        if(n % 2 === 0) {
            curr++;
        } else {
            curr = 0;
        }
        maxZeros = Math.max(maxZeros, curr);
    }
    return maxZeros;
}

Some notable differences from your solution:

Number isn't converted to binary string.  This is half for optimization purposes and half for lack of necessity.
Approach to handling the "zero gap must be bound by 1s" requisite.  The first 1 is automatically handled because it wouldn't be zero if there were still a 1 to handle.  However the lower 1 bound is simply handled by shifting until the first 1 is in the lowest digit, eliminating the need to add flags or extra handling.
Notice that no memory is required to hold gap information.  It is irrelevant as you can save only the information required as you move along.
Value n is checked against being 0 as opposed to being greater than zero just because a negative number should not be disregarded just because it is negative.

Hope that helps!  If you have any questions, just ask!


Better way to write generic method to convert List> to T[][]

Since you are creating new instance of arrays in your second loop, you don't need to know the size of the "inner list". Your "outer array" has to be as big as the "outer list". In a second phase, you instanciate the "inner arrays".

There's a simple way do this:

public <T> T[][] multiListToArray(final List<List<T>> listOfList, final Class<T> classz) {
    final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);

    for (int i = 0; i < listOfList.size(); i++) {
        array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
    }

    return array;
}

More over, as you can see in the code above, you can provide a 0-length array to toArray(T[]) method.

This piece of code:

final List<List<String>> test = new ArrayList<List<String>>();
test.add(new ArrayList<String>(Arrays.asList("a", "b", "c")));
test.add(new ArrayList<String>(Arrays.asList("d", "e", "f", "g")));
test.add(new ArrayList<String>(Arrays.asList("h", "i")));

for (final String[] innerArray : multiListToArray(test, String.class)) {
    System.out.println(Arrays.toString(innerArray));
}

Will produce this output:

  [a, b, c]
  [d, e, f, g]
  [h, i]

EDIT: There is an Ideone example.

EDIT 2: Code and Ideone updated to comply with OP needs.


Find the highest occurring digit in the prime numbers present between L and R (both inclusive)

In the code:

if (index != 0){
    System.out.println(index);
 }else{
    System.out.println(-1);
}

Using a ternary reduces clutter and improves readibility:

System.out.println(index == 0 ? -1 : index);


Python Solution for Project Euler #2 (Fibonacci Sums)

I would use separately Fibonacci generator

def even_fib(limit):
    a, b = 0, 1
    while a < limit:
        if not a % 2:
            yield a
        a, b = b, a + b

And sum function to calculate sum of items

print sum(even_fib(4000000))


You can find approach you are looking for in the logging cookbook and logging howto: Default logging module provides nice configuration feature.

So your code will be like this:

simpleExample.py (main):

import os
import logging
import logging.config
logging.config.fileConfig(os.path.join(os.path.dirname(__file__),
                          'logging.conf')
import util

# create logger
logger = logging.getLogger("simpleExample")

# 'application' code
logger.info('starting now')

util.p()

logger.critical('quitting!')

util.py

import logging
logger = logging.getLogger("simpleExample.Utils")

def p():
    for x in range(10):
        logger.warn('.')

And all the magic of logging configuration will be avalible in config file:
logging.cfg:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=`

You can use any handlers you want, and you can change levels, formats etc and you don't have to change your code.


Determine whether input-output pairs represent something that could be a proper math function

Your monadic helper functions are all one-offs and even if they were well-named (no worries, naming just gets harder as you get more experienced, there's a reason Adam was told to do it), I'd still think it better to inline them. Then the main ends up cluttered with pointfreed binds and I turned that into a do block.

(I did reorder the monadic effects a little, moving the output of each answer in front of the reading of the next question, but I found that sacrifice worthy.)

I'm not sure you need to try your hand at error-handling in tuplefy - a badly formated input file should be as likely to have a typo in its number of words in a line as in its stated number of pairs in a function.

listToMultiMap - (k, v) is no different from the other elements of vs, so you could go listToMultiMap = toMap M.empty. toMap is folding left, bad style. You can fold right like:

toMap [] = []
toMap ((k0, v0):ys) = case M.lookup k0 m of
  Nothing  -> M.insert k0 [v0]     $ toMap ys
  Just v0s -> M.insert k0 (v0:v0s) $ toMap ys

and won't need to carry a parameter into the recursive calls. And of course this can be written in terms of foldr:

listToMultiMap = foldr foo M.empty where
  foo (k0, v0) m = case M.lookup k0 m of
    Nothing  -> M.insert k0 [v0]     m
    Just v0s -> M.insert k0 (v0:v0s) m

And we could reduce the duplication in the last two lines there, but then again this whole thing is already handled by Data.Maps fromListWith.

import System.IO (readLn, getLine)
import Control.Monad (replicateM)
import qualified Data.Map.Strict as M
import Data.Bool (bool)

noDuplicates :: Ord a => [a] -> Bool
noDuplicates = all (==1) . M.fromListWith (+) . map (,1)
--           = all ((==1) . length) . M.fromListWith (++) . map (,["Why are you looking at the ordinate?"])
--           = and . M.fromListWith (\_ _ -> False) . map (,True)

main :: IO ()
main = do
  functioncount <- readLn
  replicateM functioncount $ do
    paircount <- readLn
    abscissae <- replicateM paircount $ read . head . words <$> getLine
    putStrLn $ bool "NO" "YES" $ noDuplicates abscissae

It is unfortunate for pointfreedom that the first parameter of replicateM indeed should be Int.  There must be a better way than flip. Perhaps a new infix operator, semantically id, that has highest precedence to the left, and lowest to the right, to simulate enclosing brackets around its entire right side and disappearing?


Should I hide or show this implementation?

Never lie in your code. If you say: addFrame, I expect that passing Frame should be absolutely fine. The first function you have to provide as this class' interface is addFrame(Frame const&). Then, if you firmly believe that having the (IntRect, uint) overload is really useful when writing real client code, add this overload. But (Frame const&) should go first (I mean when you think whether or not).

BTW, I'm not sure what the Frame is, but you should consider passing it by constant reference - that's idiomatic.


It is common practice to shorten statements like

if stay == True:

down to

if stay:

This'll make your code easier to read (more English-like).