Solution to Dummy Packet Assembler (Task from r/dailyprogrammer)

I think this code is very straightforward and easy to read. Good job!

Some nitpicks are,

You have a few PEP8 violations none all that concerning.

Should add a second white line between imports and your functions
Line too long, at your print statement
Continuation line under-indented for visual indent
printf style formatting is recommended against

Code suggestions

I would use a namedtuple instead of a dictionary, since it is much cleaner looking and easier to use. When to use a namedtuple!

Using the above suggestions and adhering PEP8 I get the following.

from re import split
from collections import namedtuple

def get_messages():
    Message = namedtuple('Message', 'idx num length message')
    messages = []

    while True:
        try:
            recv = split(r'\s+', input())
            messages.append(Message(recv[0], recv[1], recv[2], ' '.join(recv[3:])))
        except EOFError:
            return messages

def print_messages(messages):
    for message in messages:
        print("{}  {} {} {}"
            .format(message.idx, message.num, message.length, message.message))

def main():
    messages = sorted(get_messages(), key=lambda x: (x.idx, x.num))
    print_messages(messages)

if __name__ == '__main__':
    main()


In this case, poly is probably too much trouble. You can just calculate the polynomial yourself with rho^seq.int(0, t-1). Altogether that gives

toeplitz(rho^seq.int(0, t-1))


Using Javascript FileWriter with minimal use of closures

I think that you will always need some closures, but you can limit what they carry.
This was your example:

...
fileWriter.onwriteend=onFileWrite;
...

function onFileWrite=function(e) {
    finishedRequest(filename);  //filename needs to be retrieved from somewhere...
    if (onSuccess!==undefined) onSuccess(filename);
}

I guess that your intention was to define a function for each case and then assign it.
So your example transforms into this (I'm just reorganizing your code and fixing a function declaration).

var onFileWrite = function(e) {
    finishedRequest(filename);  //filename needs to be retrieved from somewhere...
    if (onSuccess!==undefined) onSuccess(filename);
}

...
fileWriter.onwriteend=onFileWrite;
...

This is actually an optimization because you can reuse things, the problem now is how do we get the filename. Well you can write a function that gets the filename and return a new function that only has the filename in its closure and nothing else. Like this:

var onFileWrite = function(filename) {
    return function(e) {
        finishedRequest(filename);
        if (onSuccess!==undefined) onSuccess(filename);
    }
}

...
fileWriter.onwriteend=onFileWrite(filename);
...

Note that this way you just pass what you need, variables, functions but always controlling the closure "size".

Hope it helps you, good luck with the game!


Showing popup according to the header nav link

this.hide = function () {

    this.show = false;

  }

  this.showIt = function () {

    this.show = true;

  }

You have extraneous lines everywhere, and extraneous space everywhere, trim it down.

this.hide   = function(){ this.show = false; }
this.showIt = function(){ this.show = true;  }

On the other hand, here, you're missing space (but also have extra space):

  this.setCategory = function ( category ) {

     return this.showPath = category+'.html'
                                   ^^^
  }

should be:

this.setCategory = function(category){ this.showPath = category + '.html'; }

The return is redundant, as the value goes nowhere in showCategory.

     element.on('click', '.edit', function () {
        modalService.showIt();
        modalService.showCategory('edit');
     });

     element.on('click', '.service', function () {
       modalService.showIt();
       modalService.showCategory('service');

This is redundant, pass the .service / .edit in as a variable.


JavaScript mixins - extending and super methods

The main things is that your system is much more verbose and harder to understand than simply hard-coding all the calls to superclass methods:

function A(a) {
    this.a = a;
}
A.prototype = {
    methodA: function () {
        console.log("a: "+this.a);
    }
};

function B(a) {
    this.b = a+1;
}
B.prototype = {
    methodB: function () {
        console.log("b: "+this.b);
    }
};

function Obj(a) {
    A.call(this, a);
    B.call(this, a);
    this.z = a-2;
}
// Using underscore.js extend() to mix in methods from A and B
Obj.prototype = _({
    methodZ: function () {
        console.log("z: "+this.z);
    }
}).extend(A.prototype, B.prototype);

var o = new Obj(7);
o.methodA();
o.methodB();
o.methodZ();

Instead you should have some sort of factory method that creates new classes for you, setting up the mixins behind the scenes. For example:

var Foo = createClass({
    mixins: [ClassA, ClassB],
    someMethod: function() { ... }
});

I suggest you study some existing libraries that implement their own JavaScript class systems. There are lots of nuances of the JS object model that you need to be aware of. I strongly suggest you don't use your own home-grown class-system for production, but instead adopt some already bettle-tested implementation. But writing you own is a good way to learn more deeply about JavaScript.


Creating nodes for linked list in a while loop in C

The technique you're trying to accomplish in building your ordered linked list is called forward-chaining. A pointer-to-pointer makes the task trivial for building a simple linked list while retaining its input order. Error checking memory allocations not-withstanding, it is done something like this:

struct node *root = NULL, **pp = &root;
char buf[MAXBUF] = {0};
size_t size = 0;

while (fgets(buf, MAXBUF, f) != NULL)
{
    *pp = calloc(1, sizeof(**pp));
    strncpy((*pp)->data, buf, MAXBUF-1);
    pp = &(*pp)->next;
    ++size;
}
*pp = NULL; // terminate the last node

How It Works

The parts of this that mandate further elaboration follow this general algorithm:

Utilize a pointer-to-pointer to always hold the address of the pointer that will be populated with the address of the next node to add. The initial value of this pointer-to-pointer is the address of the root pointer: &root.
Acquire a new node, storing its address in *pp, where pp is the pointer-to-pointer from (1)
Once the node is finished being configured, change the address stored in pp to be the address of the next member pointer held within the node just added. This step sets up the target location where the next node will be added if needed.
When finished processing input, the last-node-added's next member pointer has its address currently held in pp. If no nodes were added to the list, then pp still holds the address of root. To terminate the list, this pointer must be set to NULL.

So on to the code:

struct node *root = NULL, **pp = &root

The above line declares the root pointer, initialized to NULL (optional, but I hate indeterminate pointers anywhere in-code), and a pointer-to-pointer that holds the address of root. From there...

*pp = malloc(sizeof(**pp));

This allocates a new node, storing its address at whatever pointer is currently being addressed by the pointer-to-pointer pp. On the initial pass that pointer is the root pointer. On subsequent passes it will always hold the address of the `next member within the last-node-added on a prior iteration.  But it always holds the address of pointer that is to receive the next new node.

After the current node is finished being configured copy, then this is done:

pp = &(*pp)->next;

This stores the address of the just-added-node's next member in the pointer-to-pointer. When we loop around for the next iteration, this is where we will hang the next new node. Finally, after the loop finishes, this is done:

*pp = NULL;

This sets the pointer pointed-to by pp to NULL. Now think about what pointer that is:

If no items were populated in the list, then pp still holds the address of root and this will reestablish root as NULL; exactly what you want if the list is empty.
If any nodes were read, then pp will hold the address of the last added-node's next pointer, which should set to NULL to terminate the linked list. Again, exactly what this code does.

Addendum: Printing the list

Per request, printing the list after this is simply:

struct node *ptr = root;
while (ptr)
{
    printf("data: %s\n", ptr->data);
    ptr = ptr->next;
}

For C99 and later,

for (struct node *ptr = root; ptr; ptr = ptr->next)
    printf("data: %s\n", ptr->data);


I like how the Functions have simplified the enum, but, you have put logic in the implementation class that belongs in the enum....

The code:

private static final List<String> OPERATORS_LIST = Arrays.stream(Operator.values())
        .map(Operator::getSymbol)
        .collect(Collectors.toList());

private static final Map<String, Operator> STRING_TO_OPERATOR_MAPPING = Arrays.stream(Operator.values())
        .collect(Collectors.toMap(op -> op.getSymbol(), op -> op));

should be part of the Operator enum.... and there should be a static method on the enum:

public static Operator operatorFor(String op) {
    return STRING_TO_OPERATOR_MAPPING.get(op);
}

Then, your calling class would have the code:

private void processElement(final String element) {
    Objects.requireNonNull(element);
    Operator op = Operator.operatorFor(element);
    if (op != null) {
        processOperator(op);
    }
    else {
        processNumber(Double.parseDouble(element));
    }
}

Also, you should be trapping the NumberFormatException closer to where it is thrown....

        processNumber(Double.parseDouble(element));

should be:

try {
    processNumber(Double.parseDouble(element));
} catch (NumberFormatException nfe) {
    throw new CalculationFailedException("Unable to parse value " + element + " as a double.", nfe);
}

That way, you can identify which value failed to parse.


C++ Implementation of a Python-like memoization decorator

Only #include public headers from the STL
You should not #include <bits/stdc++.h>. It is a non-standard header that is not guaranteed to exist or work as you expect it to. If you do this regularly, please unlearn this, and instead #include the proper header files. You only need two for your memoizer:
#include <map>
#include <functional>

No need for trailing return types
I see you specify trailing return types for several of the functions and lambdas you define, but I do not think they are not necessary here. The compiler can automatically deduce them, and while returning a lambda with an auto return type is not the same as when the return type is explicitly set to a std::function as mentioned by HTNW, the caller can always do this conversion themselves if necessary, and indeed that is what happens when you write dp = memoize(...) inside minDifficulty().
Consider rewriting it as a class
Instead of writing memoize() as a function that returns a mutable lambda function, I would just go for the less exciting way of writing a class. The main reason is that more people will be familiar with it, and if you ever want to add functionality to the memoizer, a class makes that much easier. Here is how it could look:
template <typename RetType, typename... ArgTypes>
class memoize {
    std::function<RetType(ArgTypes...)> func;
    std::map<std::tuple<ArgTypes...>, RetType> memo;
public:
    memoize(std::function<RetType(ArgTypes...)> func): func(func) {}
    auto operator()(ArgTypes... args) {
        auto key = std::make_tuple(args...);
        if (auto it = memo.find(key); it != memo.end()) {
            return it->second;
        }
        auto [it, emplaced] = memo.emplace(key, func(args...));
        return it->second;
    };
};

This is actually a complete drop-in replacement for the lambda, even this line will still work:
dp = memoize(dp);

Use in production code
Your memoizer could be used in production code, sure! However, apart from coding challenges I've found the number of cases where I would ever need this to be vanishingly small. Either things need to be remembered much longer than the lifetime of a program, in which case a proper database is used, or all the values you could probably want are precomputed once and included with the binary, or the algorithm I am implementing would be just as easy to implement by reading/writing to a container directly instead of using a memoizer function.
A std::map or std::unordered_map is also not always the most efficient way to store things, often a std::vector is much more efficient if the function just gets a single integer argument. And your memoizer also doesn't handle the case where some parameters to the function are not part of the key to be memoized, although you could work around that by using std::bind() or some other form of currying.
In short, there's nothing wrong with it as far as I can see, but I think there won't be very many occasions where you would need it.


Using C++ to check if string s is subsequence of string t

using namespace std is considered bad practice.  Also, in C++, you should #include <string> rather than #include <string.h>.

The Solution class is an unnecessary complication.  You would be better off with just an isSubsequence() function.

In your first function, returnVal is never used.  Compiling with warnings enabled should alert you to the dead code.

The memory management rule is simple: every new must be paired with exactly one delete, and every new something[] must be paired with exactly one delete[].  Since the first solution calls new[] twice with no delete[], you have a memory leak.  Your friend is right: you should take advantage of the string class, because the whole point of the string class is to take care of memory management for you.  The second solution is definitely better.

The function signature is not ideal.  Having string parameters will cause each string to be needlessly copied when the function is called.  You should write instead:

bool isSubsequence(const std::string &s, const std::string &t) {
    …
}

std::string::size() returns std::string::size_type, so strictly speaking, you should use std::string::size_type instead of int.  (Or, if using c++11, just use auto.)


Is it a bad programming practice to declare variable in a loop?

There are a few things to consider here. First we have to consider if the position will matter to the compiler, which depends on the language. VB6 will scope that variable to the function (or sub in this case), so it doesn't matter too much there. In VB.NET, the variable will be scoped to the containing block (in this case the loop), so declaring inside of the loop would let us reuse that same variable name in some other block.

In terms of maintainability, there are two good reasons to put the declaration as close as possible to the first use of the variable. One, it improves readability. Two, it simplifies future refactoring -- imagine that you wanted to move that loop to its own function, that's easier if the variable is right there with the loop.

short answer: In VB6 I think it's best to declare just before the loop. This is mostly so that nobody thinks that the variable will be re-initialized every time the loop runs.


I figured out a solution that improves on time complexity:
So here's the thing: the solution is actually a rearrangement of the matrix, meaning O(r^2) should be possible: visit each cell of the matrix once, determinig its location in the solution.

and it's straightforward: find the heads of the anti-diagonals, and for each one, find all its members.
finding the heads: iterate over the first row, then (when you reached end of row) iterate over the last column.
for each cell in above mentioned iteration, start gathering anti-diagonal members by advancing one row down, one column left, until either one goes beyond matrix' bounds.

few notes on the posted code:

define the variables with interface types: List<List<Integer>> ans = new ArrayList<>(); this includes method arguments and return value.  This will allow you to change concrete implementation with minimal changes.
use short form if (without braces) judiciously. it makes the code less clear and is prone to errors. Some ppl will say do not use this at all.  when I use it, I put the condition and action in the same line:
if( ((i + j) == count)) temp.add(A.get(i).get(j));
I think in these types of questions, where input is known and does not change, arrays are bettter suited then Collections, since they offer more concise syntax: A[i][j] is more clear then A.get(i).get(j)
naming conventions: variables start with lower case.


I was going to put this as a comment, but could not show formatted code, so this will have to be an answer.

If you ever want to adapt your script to records "all" events, you could use something like this:

var Events = Object.keys(window).reduce(function(events, prop){
        if( prop.substring(0,2) === 'on' ){
            events.push(prop.slice(2));
        }
        return events;
    }, []);

    Events.forEach(function(event){
        window.addEventListener(event, function(e){
            console.log(event + " fired");
        })
    })

You would definitely want to debounce your event recordings, otherwise you will eat up a lot of the event loop.

There are other events, in the browser, but these are almost all of them, for a complete list checkout MDN Events and MDN Event - Web APIs for more details.


Simpson's method for numerically computing the integration of a function

There is no reason to allocate the double[] x array. It is better to compute the argument as you go: initialize double x = a; and increment it x += delta_x; in the loop body.
if in the loop is usually a performance killer. Consider incrementing j by 2:

    for (int j = 1; j < n; j += 2)
    {
        sum += 2 * Function(x);
        x += delta_x;
        sum += 4 * Function(x);
        x += delta_x;
    }

Now depending on the parity of n the very last addition could be wrong, and you need to compensate for it.
Function shall not be a Simpson's method. The Simpson shall not care what it integrates. Change the signature of Compute to accept the callable.
The choice of \$\dfrac{1}{1 + x^5}\$ for an integrand looks strange. It is hard to verify that the result is correct. I recommend to test against some more friendly integrands first.


The Consumer

The nested try-catch blocks look weird and useless. Since purgeVarnishBeforePcsRequest and getLatestStateOfResource throw exceptions, they may be caught in the outer catch block.

try {
  pcsConnector.purgeVarnishBeforePcsRequest( level, idUrl );
  response = connector.getLatestStateOfResource( urlRequest );
  // .....
  return MessageResult.ACK;
} catch (Exception e) {
  // logger
  return MessageResult.NACK_REQUEUE;
}

By the way, catching of Exception type might be a bad coding practice, but I'd not discuss it here because the context is not enough to judge.

invalidateVarnishCache

The only purpose of the try-catch block in the original code is to trace the IOException using a hypothetical commented logger and then re-throw it. I doubt that the block itself is useful, because exactly the same exception is re-thrown and must be handled somewhere among the callers and even probably also logged by them. Wouldn't it be redundant?

Concerning the IllegalStateException, the problem is that it is a RuntimeException and the caller can miss to handle it properly, with hardly predictable consequences.

I don't know what is the range of response statuses that this sort of proxy can return, but your implementation does not make distinction between 4xx and 5xx codes, which may lead either to a client-side error (your request is invalid, 4xx) or to a server-side error (5xx), which is semantically close to an I/O exception. For the latter, I can suggest to wrap the response message into a IOexception and re-throw it. For the former, it's still up to you to decide how to handle it, probably just logging is enough.


Some observations:

Try not to define methods inside the Ball constructor, it uses more memory since a new function is created for each ball instance. Rather create them using ES2016 classes (if available) or defining them on the prototype.
Rather than defining getX, getY, etc, methods rather create properties (again using ES2016 syntax if possible or otherwise defineProperty)
I would add draw and checkCollision methods to the Ball class and move the code there.
I would add a class and objects for the walls. This has the advantage that they can draw themselves in the same way as a Ball (The main program just becomes a loop asking every object to draw itself) and that you can generalize collision detection as just being between two objects without worrying about their types. As you add different objects to your code this keeps things much simpler.


Check if is it possible to get to a point that is presented by a number

General remarks

This

using namespace std;

is considered bad practice, see for example Why is “using namespace std” considered bad practice? on Stack Overflow.

Consistent indenting and spacing increases the legibility of the code.

Use curly braces for if/else blocks even if they consist only of a single statement.

Enable all compiler warnings and fix them, such as

std::cout<<x1<<" "<<y1;
// Variable 'x1' may be uninitialized when used here
// Variable 'y1' may be uninitialized when used here

Choose better variable names:

bool flag = false;

does not indicate what the flag is used for.

Testing boolean values: This may be opinion-based, but I prefer

if (!flag) { ... }

over

if (flag == false) { ... }

The return statement in main() is optional, and can be omitted.

Program structure

Separating the actual computation from the I/O makes the main method short, increases the clarity of the program, and allows you to add unit tests easily. In addition, you can “early return” from the function if a solution is found, so that the flag, x1, y1 variables becomes obsolete.

As of C++17 you can return an optional which contains a value (the solution as a pair) or not.

With these suggestions, the program could look like this:

#include <iostream>
#include <optional>

std::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            if (x * i + j * y == n) {
                // Return solution:
                return std::make_optional(std::make_pair(i, j));
            }
        }
    }
    // No solution found:
    return std::nullopt;
}

int main()
{
    int n, x, y;
    std::cin >> n >> x >> y;

    auto solution = solveSteps(x, y, n);
    if (solution) {
        std::cout << solution->first << " " << solution->second << "\n";
    } else {
        std::cout << "-1\n";
    }
}

Increasing the performance

First you can increase i and j in steps of x and y, respectively. That reduces the number of iterations and save the multiplications:

std::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {
    for (int i = 0; i <= n; i += x) {
        for (int j = 0; j <= n; j += y) {
            if (i + j == n) {
                // Return solution:
                return std::make_optional(std::make_pair(i/x, j/y));
            }
        }
    }
    // No solution found:
    return std::nullopt;
}

The next improvement is to get rid of the inner loop: After moving  i steps of width  x you only have to check if the remaining distance is a multiple of y:

std::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {
    for (int i = 0; i <= n; i += x) {
        if ((n - i) % y == 0) {
            // Return solution:
            return std::make_optional(std::make_pair(i/x, (n-i)/y));
        }
    }
    // No solution found:
    return std::nullopt;
}

Another improvement would be to check if y > x. In that case it is more efficient to iterate in steps of width  y and check if the remaining distance is a multiple of x.

Mathematics

Some final remarks on how this can be solved mathematically, with links for further reading.

What you are looking for is solution \$ (i, j) \$ to the equation
$$
 n = i x + j y
$$
with non-negative integers \$ i, j \$. This is related to Bézout's identity. In particular, a solution can only exist if  \$ n  \$ is a multiple of the greatest common divisor  \$ \gcd(x, y)  \$, which is efficiently determined with the euclidean algorithm. In that case it is easy to check if a solution with non-negative numbers exists, compare e.g. Finding positive Bézout coefficients on Mathematics Stack Exchange.


Better way to load Mysql query in PHP Array

Regardless of how well you know the mysql_* functions, you shouldn't use them. There are counterparts within PDO. See this answer on stackoverflow for why.

This is how you'd do that in PDO:

$db = new PDO("mysql:localhost;dbname=database", $user, $password);

// set the default for ->fetch() and ->fetchAll() to associative array
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// throw an exception instead of an error on fail
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $sql = "(select sum(p) / sum(w) * 100) as present from attendance group by month";

    // make sure you have php5-mysqlnd installed.
    // (MySQL native driver. It makes upgrading PHP easy as there's no library conflicts).
    // You can also work with different versions of MySQL without errors.
    $names = $db->query($sql)->fetchAll();

    // array_column will take an associative array and a key and flatten it into an array
    return array_column($names, "present");
} catch (PDOException $e) {
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

For error-handling, you should really use exceptions. Otherwise, check the value of $db->errorInfo()


Showing form on btn click - preventDefault of submit btn, then remove listener

Event delegation can be used to improve efficiency. Instead of adding a click handler to every single element with the class download, an event handler could be added to the entire document or a sub-element that contains all elements with class download.

document.addEventListener('click', e => {
  let node = e.target;
  do {
    if (node.classList.contains('download') && !node.classList.contains('is-open')) {
      e.preventDefault();
      const btn = node.querySelector('.btn');

      btn.classList.remove('is-style-outline');
      btn.classList.add('is-style-default');

      node.classList.add('is-open');
      break;
    }
    node = node.parentNode;
  } while (node && node.classList !== undefined);
});

In the example above, the click handler inspects the target element to see if it or a parent node has the class download and if such an element doesn't have class is-open before modifying class names for the elements.

I noticed that I wasn't able to click on the div element with class download without clicking the button, despite the container element having space on the sides of the button, and in the original code the click event is bubbled up from the button to the div. Instead of needing to use the do while loop to go up the DOM chain, the click handler could check to see if the target element has class name btn and in that case if it has an ancestor up three levels that matches the specified class names then modify the class names.

document.addEventListener('click', e => {
  const node = e.target;
  if (node.classList.contains('btn')) {
    if (node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode) {
      const ancestorDiv = node.parentNode.parentNode.parentNode;
      if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {
        e.preventDefault();

        node.classList.remove('is-style-outline');
        node.classList.add('is-style-default');

        ancestorDiv.classList.add('is-open');
      }
    }
  }
});

Because the code above contains multiple 'if' statements that lead to multiple indentation levels, the logic could be switched to return early instead:

document.addEventListener('click', e => {
  const node = e.target;
  if (!node.classList.contains('btn')) {
    return;
  }
  if (!(node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode)) {
    return;
  }
  const ancestorDiv = node.parentNode.parentNode.parentNode;
  if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {
    e.preventDefault();

    node.classList.remove('is-style-outline');
    node.classList.add('is-style-default');

    ancestorDiv.classList.add('is-open');
  }
});

I presume the classes is-style-outline and is-style-default are styled by a library (e.g. wordpress) but the styles could be incorporated based on whether the container div (i.e. with class download) contains class is-open, in the same way the inputs are displayed depending on those class names.

Indentation in this code is fairly uniform, though one CSS ruleset (i.e. .download.is-open .inputs) contains rules indented by four spaces instead of two


Process CSV files that follow the first nonempty one

If we reformulate this as trying to extract the header + body of the first non-empty file and the body of all subsequent files this comes to mind:

aggregated_file = ''
for file in list_of_files:
    if aggregated_file:
        aggregated_file += extract_body(file)
    else:
        aggregated_file += extract_header_and_body(file)


Recreating binary counter for arbitrary length arrays

No check for end of array
incByte() doesn't check if i >= 0.  So if all bytes are 0xff, it will happily start reading/writing to state[-1].
Simplification
Actually, I would remove the recursion.  If byte is of size 1 byte, you could also simplify the check for overflow past 0xff:
void incByte(byte *state, int i)
{
    do {
        if (++state[i] != 0)
            return;
        i--;
    } while (i >= 0);
}


Validating that a Java program has two equal-length arguments

I took your code and rewrote it a bit, so that it satisfies my personal requirements for production-ready code.

if (args.length < 2) {
    System.err.println("usage: Task <arg1> <arg2>");
    System.exit(1);
}

I removed the throw new Exception since passing the wrong number of arguments is not a programming error but a wrong invocation of the program. Only programming errors should print a stack trace. Instead of saying "Need 2 string arguments" I am following the "usage:" pattern that has been successfully established by Unix programs. Since you didn't provide any context in your question, the best variable names I could come up with are <arg1> <arg2>. If your task were to copy a file, the usage line should better be usage: Copy <source> <target>, of course.

} catch (IllegalArgumentException e) {
    System.err.println(e.getMessage());
    System.exit(1);
}

I added the System.exit since it was missing. If the program fails, it must report this via System.exit or by throwing an exception from the main function.

private static int processResult(String inputOne, String inputTwo) {
    if (inputOne.length() != inputTwo.length()) {
        throw new IllegalArgumentException("Strings must be the same length");
    }

There's no need to have a separate function for checking the lengths of the strings. Using IntelliJ it was quite simple to inline the method call to lengthsEqual (I just pressed Ctrl+Alt+N) and to remove the redundant call to Integer.compare (which was already marked in dark gray, so I just had to press Alt+Enter there).

It's unfortunate that the exception message says "String must be the same length". This message does not tell which strings are meant, and since that message is printed to System.err later, it should be worded with the same care as the usage message.

I disagree with bag's answer, especially the part that commercial code needs to be extensible. It doesn't. It needs to be easy to read, and it needs to clearly tell its intention. If the business requires that the two strings be equal (for whatever reason), the code should say exactly this, and the code should match the wording of the original requirement as closely as possible, so that later changes to the requirements can be programmed as easily as possible.


Append an annual total to all Excel files

You are onto a good start, since you already use some functions already; yes they do look like callable objects, but functions in general are referred as such to disambiguate from that more involved construct.

As you noted, you have a number of duplicate code that can be shortened into a single function that take different arguments.  Before doing that, let's take one of the for loops and find out what could be improved first.

The show_results function should take in a parameter, but we can fix this later

Calling os.chdir haphazardly just to list some files is a bit overkill.  I am guessing you want to allow the singular i variable be opened without having to use absolute paths, but doing so can be dangerous if this code is executed in a multi-threaded context (say you want to process multiple files at once), as a thread changing the working directory will change them for all, thus potentially breaking code running on other threads.

Fortunately, Python offers a much better way to glob these files from a path, using a module incidentally named glob.  Now the loop is simply

# insert these into the imports
from os.path import join
from glob import glob

for path in glob(join('path_to_excel_files'. '*.xlsx')):

The reason why we use os.path.join is for cross-platform compatibility.  Also try to avoid single letter names if there is a more expressive name available.

Lastly, the sum call in each loop could be done once after all the values have been gathered rather than every loop as the result would not matter at all.

To simplify code, look for parts that are common, and from that parts that take values that define the specific usage.  From the three for loops we can see that it's just simply sheet identifier within the workbook, the cell identifier from the sheet.  This is what it might look like (please note that I don't have the library installed, nor your Excel files, so I can't exactly test the following)

def process_workbooks_in_dir(excel_root, sheet_id, cell_id):
    values = []
    for path in glob(join(excel_root, '*.xlsx')):
        workbook = openpyxl.load_workbook(path, data_only=True)
        sheet = workbook[sheet_id]
        value = sheet[cell_id].value
        values.append(value)

    return values

Note that sum can be called later to sum up the list of values returned, this function now simply process the list of excel files within the provided base path, and the load_workbook function will be given the absolute path of each excel files for the processing to be done.  To use this, the following may be done.

my_list_2015 = process_workbooks_in_dir('path_to_excel_files', 'Blatt1', 'L46')
my_list_2016 = process_workbooks_in_dir('path_to_excel_files', 'Blatt1', 'L46')
my_list_2017 = process_workbooks_in_dir('path_to_excel_files', 'Zusammen', 'C11')

my_list_total_2015 = sum(my_list_2015)
my_list_total_2016 = sum(my_list_2016)
my_list_total_2017 = sum(my_list_2017)

Of course, verify that all this still working as intended.  You may note that the 2015 and 2016 lists are using the same parameters - this is now much more visible with the repeated code moved out of the way to show how these parameters can become accidentally (or intentionally) repeated in the remaining code.

While this is basically done, we can still do better with more advanced techniques.

As there is significant overhead with opening and closing files (especially for a complicated file format such as excel spreadsheets), it would be great if this is done only once for all the operations required.  Let's explore for way to streamline the flow better so that this can be done.  Note that the actual act of opening/closing files can be decoupled from the usage of the workbook, and that the workbook can be passed as a parameter.  Let's move that workbook usage logic to a separate function:

def read_value_from_workbook(workbook, sheet_id, cell_id):
    sheet = workbook[sheet_id]
    return sheet[cell_id].value

Now this is a much more simple function, but we still need the other bits such as opening the files, specify how to get the data through this function and to store it.

def process_workbooks_by_spec(excel_root, specification):
    results = {}
    # predefine the results with the year lists as required
    for year, sheet_id, cell_id in specification:
        results[year] = []

    # for the actual work
    for path in glob(join(excel_root, '*.xlsx')):
        workbook = openpyxl.load_workbook(path, data_only=True)
        for year, sheet_id, cell_id in specification:
            value = read_value_from_workbook(workbook, sheet_id, cell_id)
            results[year].append(value)

    return results

Note that Python can unpack tuples into multiple variables so we can have a list of tuples put into friendly variable names within the for loop to assign the year, sheet_id and cell_id for usage.  Also another thing that can simplify/eliminate the initial assignment loop is to use collections.defaultdict, which would reduce the code to simply this:

from collections import defaultdict

def process_workbooks_by_spec(excel_root, specification):
    results = defaultdict(list)
    for path in glob(join(excel_root, '*.xlsx')):
        workbook = openpyxl.load_workbook(path, data_only=True)
        for year, sheet_id, cell_id in specification:
            value = read_value_from_workbook(workbook, sheet_id, cell_id)
            results[year].append(value)

    return results

This is now much more efficient in terms of overall execution.  All the required operation needed to extract data can be passed in as a single list that might look something like this:

spec = [
    ('2015', 'Blatt1', 'L46'),
    ('2016', 'Blatt1', 'L46'),
    ('2017', 'Zusammen', 'C11'),
]

Note that the top level loop still provide the path to the files, which then open the workbook, then the inner loop unpacks the specification and pass the ids along with the workbook to the inner function, extract the required data and append that to results dictionary under the respective key (by year).

As this is relatively simple, the inner loop remain as is within that function, however for much more complicated business logic, it is wise to consider moving the inner loop outside to a separate function so that the logic is contained in a more concise way.

Now to use it:

results = process_workbooks_by_spec('path_to_excel_files', spec)

Accessing results['2015'] should now return the list of values extracted, and one can simply pass the results into a function that will process this.  Consider modifying show_results to this:

def show_results(results):
    for year, values in sorted(results.items()):
        result = sum(values)
        print("-" * 14 + str(year) + "-" * 14)
        print("Total Sum Netto %s: %.2f" % (year, result))
        print("Total Sum Brutto %s: %s" % (year, brutto_total(result)))

Now rather than relying on some global value outside of the function and some hard-coded value defined at the module, this only take in the results dictionary produced by the process_workbooks_by_spec function and iterate through every item and produce an output.  Of course, the sum is done at the time of calculation and if this is undesirable, it can be moved as part of the results as another dictionary, but this is up to you.

I would also not prematurely have some math processing function to return something that is not a number, so brutto_total should return the number as is, and format it later to keep the summary string consistent.  Putting it all together

from os.path import join
from glob import glob
from collections import defaultdict
import openpyxl

def brutto_total(netto):
    return netto + netto * 0.2

def read_value_from_workbook(workbook, sheet_id, cell_id):
    sheet = workbook[sheet_id]
    return sheet[cell_id].value

def process_workbooks_by_spec(excel_root, specification):
    results = defaultdict(list)
    for path in glob(join(excel_root, '*.xlsx')):
        workbook = openpyxl.load_workbook(path, data_only=True)
        for year, sheet_id, cell_id in specification:
            value = read_value_from_workbook(workbook, sheet_id, cell_id)
            results[year].append(value)

    return results

def show_results(results):
    for year, values in sorted(results.items()):
        result = sum(values)
        print("-" * 14 + year + "-" * 14)
        print("Total Sum Netto %s: %.2f" % (year, result))
        print("Total Sum Brutto %s: %.2f" % (year, brutto_total(result)))

spec = [
    ('2015', 'Blatt1', 'L46'),
    ('2016', 'Blatt1', 'L46'),
    ('2017', 'Zusammen', 'C11'),
]

results = process_workbooks_by_spec('path_to_excel_files', spec)
show_results(results)

This is how I might have done this (also reminder: I don't have your files and library installed, but this complete version at least pass the syntax check); hopefully this shows how you might be able to make use of the rich standard library functions that are available in Python to simplify certain tasks, and to also think about how one might break a program down and restructure it into a more clear, reusable form.


Javascript: Mapping combinations of input and possible suffix arrays leads to repetitive if statements

this.values = [] will never be used.  It is unnecessary.

setValues($event: string) {
    //this.values = []; //unnecessary
    this.values = Object.values(this.substantiveFormGroup.value); // the user choices from the form group saved to an array
    this.setDeclination(this.values);
  }

The code's logic will always set a value for this.declination, so it makes sense to just assign it at the top, so you know that this.declination will always be overwritten and by default should be initialized to an empty array.  It also allows the code to be shorter.
If there will be more than two conditions, you should probably have them in a list anyways.  This way of organizing still benefits, and the use of an array list and destructuring with for of loop expresses the code's use of conditions to check for and suffixes to use in an organized list in one place, as well as shortening the code significantly and making it more concise.
The result is that it can be more simply read as an iteration on a list of conditions to process.
Brevity and DRY naturally occurs when it is distilled this way.

setDeclination(values) {
    this.declination = [];
    for (const [condition, suffixes] of [
     [this.conditionOne, this.conditionOneSuffixes],
     [this.conditionTwo, this.conditionTwoSuffixes]
    ])
       if(condition.every(i => values.includes(i))) {
         const inputValue = this.substantiveFormGroup.get("input").value;
         this.declination = suffixes.map(suffix => inputValue + suffix));
         break;
       }
 }

I have made some modifications to the formatting and the declaration of variables to control line length and make the code more concise, and it should be mostly self-explanatory.


Your service looks perfectly fine to me. As far as the Clock component goes, I can only recommend one thing.

When getClock().subscribe(...) is executed, a reference to the subscription is being returned back. Ideally, the reference should be kept as long as the component is alive. On component destruction, the subscription should be released by invoking subscription.unsubscribe().

@Component({
  selector: 'clock',
  templateUrl: './clock.component.html',
  styleUrls: ['./clock.component.css']
})
export class Clock implements OnInit, OnDestroy {

  private _clockSubscription: Subscription;
  time: Date;

  constructor(private clockService: ClockService) { }

  ngOnInit(): void {
    this._clockSubscription = this.clockService.getClock().subscribe(time => this.time = time);
  }

  ngOnDestroy(): void {
    this._clockSubscription.unsubscribe();
  }

}

P.S. As a minor side note, I want to mention that some devs like to explicitly mention the OnInit/OnDestroy/... interfaces in the class' implements clause. I am not sure whether it's very helpful or a big deal, but at least the compiler will complain if the ngOnInit is missing while class declares that OnInit is implemented.


Finding all integers in an array with odd occurrence

You don't really need to keep track of how many times you've seen each integer, only whether you've seen it an odd number of times. So start with your data structure (map, hash table, dictionary, whatever) being empty, which correctly reflects the state that you have seen no numbers an odd number of times. Now for each number x in the array, if x is in the map then remove it (now you've seen it an even number of times) otherwise add it.


Minimal substring with all characters contained in string

I know this is old, but I will write some remarks anyways, hope you will find it useful.

This code lacks knowledge of usual language shortcuts, eg. (if x nil y) is equivalent to (unless x y). Similarly, (setq x (1+ x)) is the same as (incf x), (setq x y) (setq z q) is the same as (setq x y z q) inside (implicit) progn. (puthash c (1- (gethash c ht 0)) ht) is the same as (decf (gethash c ht 0)).
Language offers specialized data-structure for working with characters--char-table.
It is better to express algorithmic code in terms it is easy for humans to interpret (i.e. leave the low-level details of implementation to helper functions, while giving helpers meaningful names. For example add-to-hash isn't particularly better than puthash. Perhaps better partitioning of your code would involve functions like unique-characters-of, generate-candidate etc.

Finally, and most importantly, your code doesn't really solve the problem, try this for instance:

(find-min-substring "aaaaabacbaaaaac") ; => "acbaaaa"

Below is an alternative solution.  It is very straight-forward (probably inefficient), but (hopefully) correct:

(defun string-cost (s)
  (cl-loop
   with mask = (make-vector 128 0)
   for c across s do
   (setf (aref mask c) 1)
   finally (cl-return (cl-reduce '+ mask))))

(defun generate-candidates (s)
  (list (substring s 0 (1- (length s)))
        (substring s 1)))

(defun choose-candidate (a b min-cost)
  (let ((a-candidate (min-common-substring a min-cost))
        (b-candidate (min-common-substring b min-cost)))
    (if (< (length a-candidate) (length b-candidate))
        a-candidate
      b-candidate)))

(defun min-common-substring (s &optional min-cost)
  (unless min-cost (setf min-cost (string-cost s)))
  (cl-destructuring-bind (a b)
      (generate-candidates s)
    (let ((a-cost (string-cost a))
          (b-cost (string-cost b)))
      (cond
       ((and (>= a-cost min-cost)
             (>= b-cost min-cost))
        (choose-candidate a b min-cost))
       ((>= a-cost min-cost)
        (min-common-substring a min-cost))
       ((>= b-cost min-cost)
        (min-common-substring b min-cost))
       (t s)))))

Where more involved, but slightly more efficient version of string-cost could look like this:

(defun string-cost (s)
  (cl-loop
   with mask = (make-char-table t 0)
   for c across s do
   (set-char-table-range mask c 1)
   finally
   (cl-return
    (let ((cost 0))
      (map-char-table
       #'(lambda (k v)
           (when (and (/= v 0) (consp k))
             (setf v (- (cdr k) (1- (car k)))))
           (incf cost v))
       mask)
      cost))))


Your code has a problem. Candidate A can loose region 1, but win region 3.
Where with your code they can only win region 3 if they win region 2 and 1.
This is as they are independent, and so you should random in each check.
You want to move your chances outside the loop into an array.
You can simplify your ifs into one comprehension.
Candidate a wins if they have more than half the regions, you don't need to calculate the amount of regions candidate b wins.

And so you could change your code to the following:

from random import random

AMOUNT = 10000
region_chances = [87, 65, 17]
region_chances = [1 - n / 100 for n in region_chances]
regions = len(region_chances)
candidate_a_won = sum(
    sum(random() >= chance for chance in region_chances) * 2 > regions
    for _ in range(AMOUNT)
)
candidate_b_won = AMOUNT - candidate_a_won
print('Candidate A won elections {} times, candidate B won elections {} times'.format(candidate_a_won, candidate_b_won))

If you want to extend on the above then it'll be hard if you decide to have more than two candidates, or even amounts of states.
But as this is a challenge, I don't think you need to worry about these situations.


Throwing exceptions when validation fails

You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.

You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:

try
{
    // some code
}
catch (Exception exception)
{
    // handle the [validation?] exception
}

The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:

try
{
    // some code
}
catch (ValidationException exception)
{
    // handle the validation exception
}

And any exception thrown that is not a ValidationException, will bubble up the stack.

That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?


Math game with 'hard' and easy questions

A few notes touching upon encapsulation and responsibilities:

    def __init__(self):

        print("Welcome to the Official Math Game of SkillsUSA!\nYou will have at least five relatively simple questions,\nand up to ten difficult ones.\nGood luck!")
        time.sleep(5)
        x = 3
        while x != 0:
            print("Starting in ",x,"...")
            time.sleep(1)
            x -= 1

the initialization method of a class should be responsible to get the object into a workable state. It's supposed to initialize any required fields and then stop there.

This one here doesn't. Whenever some code creates a "new instance" of Math_game you'll get this welcome message, your thread will be locked up for 8 seconds, all this is stuff you don't want to have in your initializer. Only after that you get to the actually interesting stuff, namely initializing your fields.

Additionally this method is missing a docstring (that seems to be rather unconventional on __init__ methods, thanks to Gareth Rees) and instead has some non-parsable comments, which are suited to explain the code to python beginners (like I am one :D). You might prefer to add the docstring on class-level as suggested by Gareth.

That being said, your "cheesy intro" should be a separate method, taking a few parameters.

Next thing is: whenever a module gets imported in python, code in there is executed. This includes your current code. You definitely shouldn't do that.

The simple and idiomatic fix for that is:

if __name__ == '__main__':

For more information on this construct, read up at stackoverflow

Overall your class could use more "API documentation". As of now if I wanted to use this from somewhere else, as a minigame or something, I'd have to jump through some hoops (with the problematic __init__ only being the first). This includes the less convenient name prob. This method takes two arguments and if I didn't have the source code, I'd have no clue what they were.

The first step to fixing this is getting a proper docstring in there. The next thing is to extract some responsibilities to clarify your design.

You should not return the solution when generating the problem. Instead you should store it somewhere in the class instead, so it can be checked properly with isCorrect.

While we're there: Your naming is sometimes a little off. You're violating the official conventions in a few places isCorrect being one of them. Methods, as well as variables and fields are supposed to be named in snake_case, Classes are supposed to be named in CapWords (without underscores)...

There's also tools that check the PEP-8 conventions for you, one of them being the IDE pycharm. Make use of these tools to simplify your life when coding ;)


This is mostly a personal issue. But, in my opinion, there are 2 issues that are going wrong in your approach.

Making your objects reusable (The main issue in the DRY principle)

In my design, I want to have say 3 designs for boxes. Then, I spend sometime designing them. (that is, creating the style in the CSS). Then, when creating the HTML, I reuse that designs.

In your system, every time that I create a box in HTML, I have to re-design the box

<div class="box round gray darkshadow redtext">

At best, you will end copy-pasting the box from the previous page.
At worst, your web won't have a consistent look.

Hardcoding your style in the HTML

What should your CSS provide you ? The power to change your gray web, that is no longer fancy, to a blue one, without modifying your HTML. But, if your elements have a class that is gray, you will end with:

.gray {
    background-color: blue;
}

That, of course, will work; but won't give you an easy time understanding what is going on


Centered finite difference approximation for edge enhancement

I'm not yet very comfortable with Python style and so on, so I'm going to focus only on speeding up the code.

First of all, the indexing

img[x] extracts a line from the image. Then img[x][y] extracts a pixel from that line. In contrast, img[x,y] directly extracts a single pixel from the image. Thus, we can rewrite your indexing expressions reduces the amount of work to be done:

pdfx[x,y] = (img[x, y + stepsize] - img[x, y - stepsize]) / (2*stepsize) # partial with relation to x
pdfy[x,y] = (img[x + stepsize, y] - img[x - stepsize, y]) / (2*stepsize) # partial with relation to y

Let's time the difference:

import timeit
timeit.timeit("imgs = findiff(sample_img, 1)", number=30, globals=globals())

The original code gives 3.46 seconds, the code with changed indexing gives 2.37 seconds. That is a significant difference!

Next, let's remove the double loop

You should always leverage the vectorized operations in Numpy. In this case it is not difficult. The lines of code become longer, but with practice one immediately sees what is being computed. This is the modified function:

def findiff(image, stepsize):
    # Padding to handle the boundaries when incrementing with step size
    padded_img = np.pad(image, pad_width=stepsize, mode='constant', constant_values=0)
    img = padded_img.astype(float)
    pdfx = (img[stepsize:-stepsize, 2*stepsize:] - img[stepsize:-stepsize, 0:-2*stepsize]) / (2*stepsize) # partial with relation to x
    pdfy = (img[2*stepsize:, stepsize:-stepsize] - img[0:-2*stepsize, stepsize:-stepsize]) / (2*stepsize) # partial with relation to x
    img_lst = []
    img_lst.append(pdfx)
    img_lst.append(pdfy)
    return img_lst

Note the computation of pdfx and pdfy. Here we do exactly the same computations as before, but we extract an array containing all the elements that appear on the left hand side of the minus operator as you go through the original loop, and another array containing all the right hand side elements. Note that img[stepsize:-stepsize, stepsize:-stepsize] is the original image before padding (since we add stepsize pixels to each side). On the LHS we want to index pixels stepsize elements to the right, that is img[stepsize:-stepsize, (stepsize:-stepsize)+stepsize] == img[stepsize:-stepsize, 2*stepsize:]. On the RHS we want to index pixels stepsize elements to the left which we obtain in a similar way.

The modified function runs in 0.021 seconds. That is two orders of magnitude faster than the loop code!

Note that the output images now are of the same size as the input image, not of the size of the padded input image as before. This is more useful in general. But if it is desired to output images with padding then it is possible to instead do:

pdfx = np.zeros(shape=(M, N))
pdfx[stepsize:-stepsize, stepsize:-stepsize] = ...

Another change in the code above is the use of pad_width=stepsize in the call to np.pad, so that the indexing works correctly for step sizes larger than 1.


It looks fine to me and it does the job. I would only consider changing a couple things:

Decouple it from the platform dependent clock_gettime. This piece of code could be useful on any platform that supports time queries with millisecond precision (basically anything nowadays). If you encapsulate that aspect a little more, it can be easily ported to say, Windows using the QueryPerformance*() WinAPI functions. That clockid_t parameter in the constructor is the only bit leaking a platform specific object to the user, which you can easily remove or replace by a portable typedef/constant.
Support a generic output stream instead of hardcoding std::cout. Also very simple to do, just add an extra std::ostream& member an take an extra parameter in the constructor, which can be defaulted to std::cout.
Unless you want the stream to be flushed after printing a timing, replace endl with a \n. Flushing the stream might have performance implication if you are doing a lot of instrumentation in the code.
Not of consequence in this case, since this class is meant to be a stack-lived variable, however, I'll note it anyways as a general guideline: Avoid declaring booleans and variables smaller than the native word size in the middle of a class. e.g.:

timespec start_,end_;
std::string name_;
bool active_;        // <--- Not the best place for it
clockid_t clock_id_;

On most compilers/platforms, a boolean is the size of a byte, which in that case will introduce padding if declared in the middle of other member variables of different sizes. A good rule of thumb is to always place the small fields, like bools, chars and the like at the very end of the member data declarations, so any padding added by the compiler stays minimal and at the end. Again, not of importance in you code, just thought it would be interesting to mention for future reference.


Adding a few tests

Before performing any chance, it can be a good idea to add a few tests. This is especially relevant if we plan to perform optimisations as we'll be able to measure times. In that, case, it is also great when we are able to generate arbitrarily large inputs to infer the complexity of the solution (or at least be able to compare 2 solutions).

Here is what I wrote:

import time

start = time.time()
for i in range(2):
    # Examples provided
    assert Solution().kSimilarity("ab", "ba") == 1
    assert Solution().kSimilarity("abc", "bca") == 2
    assert Solution().kSimilarity("abac", "baca") == 2
    assert Solution().kSimilarity("aabc", "abca") == 2
    # Arbitrary examples
    assert Solution().kSimilarity("abcdefg", "gabdcef") == 5
    assert Solution().kSimilarity("abcbcdefg", "gcbabdcef") == 6
    # Big examples inspired from smaller ones
    n = 10
    assert Solution().kSimilarity("ab" * n, "ba" * n) == 1 * n
    assert Solution().kSimilarity("abc" * n, "bca" * n) == 2 * n
    assert Solution().kSimilarity("abac" * n, "baca" * n) == 2 * n
    assert Solution().kSimilarity("aabc" * n, "abca" * n) == 2 * n
    assert Solution().kSimilarity("abcdefg" * n, "gabdcef" * n) == 5 * n
print(time.time() - start)

Playing with the different values of n below, we can see that the Solution becomes very slow very quickly (I stopped at n = 4).

The timing suggest an exponential complexity.

Maybe there's something we can do about it with a different algorithm. We'll see this at the end but in the meantime, let's try to improve the already existing code.

Code review

The code looks good and uses great ideas that I've seen in other places.

A few details can be improved.

I'd call find_first_mismatch directly from find_candidates.

Actually, you could also merge the 2 functions to have a single loop and avoid messing with indices.

With a simple rewriting we get something equivalent which could be considered less elegant but is slightly faster:

def find_candidates(self, A, B):
    mismatch = None
    for i, (a, b) in enumerate(zip(A, B)):
        if a != b:
            if mismatch is None:
                mismatch = i
            elif a == B[mismatch]:
                yield Solution.swap(A, mismatch, i)

Another optimisation could be to avoid converting A to list many times by inlining the code for swap. This is not great as far as code organisation goes but...

def find_candidates(self, A, B):
    mismatch = None
    chars = list(A)
    for i, (a, b) in enumerate(zip(A, B)):
        if a != b:
            if mismatch is None:
                mismatch = i
            elif a == B[mismatch]:
                # Swap, yield and revert swap
                chars[i], chars[mismatch] = chars[mismatch], chars[i]
                yield "".join(chars)
                chars[i], chars[mismatch] = chars[mismatch], chars[i]

Renaming and reusing known values, we'd get:

def find_candidates(self, A, B):
    mismatch = None
    A_lst = list(A)
    for i, (a, b) in enumerate(zip(A, B)):
        if a != b:
            if mismatch is None:
                mismatch = i
            elif a == B[mismatch]:
                # Swap, yield and revert swap
                c = A_lst[mismatch]
                A_lst[i], A_lst[mismatch] = c, a
                yield "".join(A_lst)
                A_lst[i], A_lst[mismatch] = a, c

Instead of having q via different ways (len, pop, appendleft), we could just use list and iterate over it while filling another list that will be used at next iteration. We'd get something like:

    q = [A]
    distance = 0
    seen = set([A])
    while q:
        new_q = []
        for current in q:
            if current == B:
                # print("Return:", distance)
                return distance
            for candidate in self.find_candidates(current, B):
                if candidate not in seen:
                    seen.add(candidate)
                    new_q.append(candidate)
        q = new_q
        distance += 1

Instead of maintaining distance at each iteration, you could use itertools.count.

At this stage, the code looks like:

    def find_candidates(self, A, B):
        mismatch = None
        A_lst = list(A)
        for i, (a, b) in enumerate(zip(A, B)):
            if a != b:
                if mismatch is None:
                    mismatch = i
                elif a == B[mismatch]:
                    # Swap, yield and revert swap
                    c = A_lst[mismatch]
                    A_lst[i], A_lst[mismatch] = c, a
                    yield "".join(A_lst)
                    A_lst[i], A_lst[mismatch] = a, c

    def kSimilarity(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: int
        """
        # print("kSimilarity:", A, B)
        q = [A]
        seen = set([A])
        for distance in itertools.count():
            new_q = []
            for current in q:
                if current == B:
                    return distance
                for candidate in self.find_candidates(current, B):
                    if candidate not in seen:
                        seen.add(candidate)
                        new_q.append(candidate)
            q = new_q

Different algorithm

Generating so many intermediate strings is expensive and not so efficient.

An observation is that whenever we have elements so that: x1 should become x2, x2 should become x3, ..., xn should become x1, there is a trivial manipulation involving n - 1 swaps which put n elements in their correct position. It is easy to see that things can't get more efficient that this.

Now, the initial problem can be rewritten in a different problem where we want to find such cycles in our original strings.

This can be done by reorganising data from our strings into a graph and writing the proper loop to visit nodes to find cycles.

class Solution:
    def kSimilarity(self, A: str, B: str) -> int:
        # Building a graph where c1 -> c2 means we want to change c1 for c2
        # The problem becomes a graph problem: finding cycles
        changes = dict()
        for i, (c1, c2) in enumerate(zip(A, B)):
            if c1 != c2:
                changes.setdefault(c1, []).append(c2)
        ret = 0
        while changes:
            # Find cycle
            visited = []
            node = next(iter(changes))
            while node not in visited:
                visited.append(node)
                node = changes[node][0]
            # Cycle is found - starting from node
            beg = visited.index(node)
            loop = visited[beg:]
            # print("Loop:", loop)
            ret += len(loop) - 1
            # Remove corresponding elements
            for c1, c2 in zip(loop, loop[1:] + [loop[0]]):
                l = changes[c1]
                l.remove(c2)
                if not l:
                    del changes[c1]
        # print("Return:", ret)
        return ret

It seems like this behaves in a linear time or something that look similar enough.
I was able to run the tests above with n = 3000 in very small time.

Note: things are not as good as expected. Trying to run the code on the leetcode tool, a test case is not handled properly

assert Solution().kSimilarity("aabbccddee", "cdacbeebad") == 6  # Returns 7

I guess I based the algorithm on a wrong assumption. It seems like the cycles can't be chosen randomly as I assumed.

For instance, in that case, we should choose:

[bc] + [de] + [bad] + [cea] (with cost 6)

over combinations like

[acb] + [ade] + [cebd] (with cost 7) or
[acedb] + [ade] + [bc] (with cost 7)

At the end of the day, we want to maximise the number of cycles: the final cost will be number of characters in the wrong space - number of cycles.

I have no clue how to handle this...


As stated in the comments, this is not a good example for OO programming, because it can be solved with just a function. Sometimes you can still use classes to separate different functionality, but in Python this is not really required nor generally practiced (compared to e.g. Java where all code must be in a class - if we discount default methods in interfaces, static code blocks and such).

Now you've put designated two variables as fields, while they should be local to the function. There is no need at all to use them as fields. This won't directly show up as a problem, but if you'd e.g. call the method check_for_palindrome in a concurrent fashion, you'd be in trouble, because the loop field will now be used by two different threads at once. letter_count on the other hand is secure, but only because it is simply not used.

Only create fields for variable values that are intrinsic to the class (or are references that tie the class to another of which it is dependent). For instance, you might want to configure the checker to check for upper or lowercase, or maybe even mixed case. That kind of field would be logical for a palindrome checker class. All in all, you should try and minimize the variables that make up the state and thus number & complexity of the fields for a particular class.

As you've already found out yourself, PalindromeChecker would be a better name for the class, as it doesn't search for palindromes, at least not at the moment. If you've got a method for a class, you don't need to repeat everything, just PalindromeChecker.check would be sufficient. I don't know why the input is called base, just input seems sufficient (edit: word would probably even be a better name).

When it comes to functionality of a class, it is important to distinguish human interaction with actual output. I'd never create a checker that would return a string as response. In this case I'd expect a bool output instead. Then the program that uses the checker can create a user response if the result is True or False. At least didn't print out the result, which would have been the action of most starting developers.

Finally, in the call to the class instance, you're trying to do too much at once:

print(palindrome_checker.check_for_palindrome(input("Enter your palindrome: ").lower()))

First assign the result to a variable and then print it out. Separate the input. You'll thank yourself if you have to startup a debugger and step through your program.


Binary multiplication on elliptic curves in C++

n = mod(n, m);  // the %-operator doesn't return a non-negative integer in every case so I wrote a function

I would find a comment explaining m more useful than a comment explaining why you made a mod function, because everyone ends up writing a mod function which behaves sensibly.

I don't know much about elliptic curves, but I have worked with finite fields. Are you sure it makes sense to take n mod m as though they were integers? The only makes sense to me if m is also the characteristic (i.e. if it's a field of prime order).

    unsigned int mask = 1 << (sizeof (n) - 1);  // more flexible and platform independent than 1 << 31
    for (; mask; mask >>= 1)

Why loop down? If you loop up then you get the platform-independence for free, and also you loop fewer times when n is small. Obviously the loop invariant would change, but it would be closer to school long multiplication and so might also be more maintainable.

    for (; n; n >>= 1)
    {
        if (n & 1)
            r = add(r, p);
        p = add(p, p);
    }


As N.B. mentioned in their comment - why are you implementing a module method if we already have lazy loading via autoloading? I've even written a class that you can simply attach and not have to worry about loading your classes. Now, there are better autoloaders out there - like Symphony's ClassLoader/autoload.php. Anyways, here's your code, with my LazyLoader class handling the loading of methods (untested code).

/LazyLoader.php

/**
 * LazyLoader
 * A fast, strict lazy loader (time ~ 0.0001)
 *
 * Class name must match File name.
 * If class has namespace, must be called via namespace.
 *
 * @author Juan L. Sanchez <juanleonardosanchez.com>
 * @license MIT
 * @version 1.2.0
 * @internal 06.26.2013
 */

Namespace LazyLoader;

class LazyLoader{
    public static $dirRoot;

    public static function autoload($class_name){
        $file = dirname(__FILE__) .
                (strlen(self::$dirRoot) > 0 ? self::$dirRoot : "") .
                '/' . array_pop(explode("\\", $class_name)) . '.php';

        file_exists($file) ? require_once($file) : "";
    }

    public static function SetBaseDirectory($directory_root){
        self::$dirRoot = substr($directory_root, -1) == "\\" ?
                         substr($directory_root, 0, -1) : "";
    }

    public static function Register(){
        return spl_autoload_register(__NAMESPACE__ .'\LazyLoader::autoload');
    }
}

$LazyLoader = new LazyLoader;
$LazyLoader->SetBaseDirectory("Classes"); # Optional
$LazyLoader->Register();

/Context.php

<?php
module('sys/ProtoContext');

class Context extends ProtoContext {

    protected function getAuth() {
        return new MyAuth();
    }

    protected function getUsersDao() {
        return new MysqlDao('users');
    }

    protected function getRolesDao() {
        return new MysqlDao('roles');
    }

    /*
     * 5-10 more similar methods 'getSomethingDao'
     * each including MysqlDao via method 'module'
     */

    protected function getLinksCViewDao() {
        return new MysqlDao('linksc_view');
    }

}

The directory structure of the above code would look something like:

/LazyLoader.php
/Context.php
/Classes/MyAuth.php
/Classes/ProtoContext.php
/Classes/MysqlDao.php


James Heald said:

  I was told I'm using factories wrong, but I'm not so sure.

The people telling you that are technically correct. A "factory" is an object or method whose sole purpose for existence is to create other objects. Factories are generally used when you want to create a concrete sub type, but return either an interface or a common parent type.

From Wikipedia: Factory (object-oriented programming)

  In class-based programming, a factory is an abstraction of a constructor of a class, while in prototype-based programming a factory is an abstraction of a prototype object. A constructor is concrete in that it creates objects as instances of a single class, and by a specified process (class instantiation), while a factory can create objects by instantiating various classes, or by using other allocation schemes such as an object pool. A prototype object is concrete in that it is used to create objects by being cloned, while a factory can create objects by cloning various prototypes, or by other allocation schemes.

Your apiFactory object is technically returning "new" objects, but since it is making web service calls, you've actually created a "service object".

More info: AngularJS Services.

Really the problem is the name "apiFactory" because the apiFactory variable itself is not a factory. It is a service. A more appropriate name might be ChatService.

The function that returns apiFactory is actually the factory, whereas apiFactory is actually the service.


GIS feature labeling and removal of None or Empty fields

You can consolidate the body of this quite a bit.  First, I'd make list[i*2] and list[i*2+1] into variables, probably

first_element = list[i*2]
second_element = list[i*2+1]

Then you can clean up the if statements as well

if first_element and first_element.strip() and second_element and second_element.strip():

However, that makes it clear that what you're doing is the same for both.  I'd write a little helper function

def validate_element(element):
    return element and element.strip()

if validate_element(first_element) and validate_element(second_element):

You should also use a format string and string.join instead of concatenation

lines = ["{} Top".format([Elevation]]

for i in range(len(list)/2):
    first_element = list[i*2]
    second_element = list[i*2+1]
    if validate_element(first_element) and validate_element(second_element):
        lines.append("({}:{})".format(first_element, second_element))

return '\n'.join(lines)

You could probably turn this into a list comprehension if you wanted to, but that probably isn't worth the effort and ugliness that would ensue.

Your names in general are pretty bad - list is especially horrific because you're now masking a builtin function - you can no longer use the list constructor.  Try to use descriptive names to actually describe what the values represent.


#include <stdio.h>

This function doesn't use anything from <stdio.h>, so don't waste the compiler's time by including it.

   void copy(const int *origin, int *location, int n){

I would put the destination argument first, to be consistent with Standard Library functions such as memcpy.  And change n to be a size_t, so it will work with any array.

   int i;
   for(i=0;i<n;i++){

We can reduce the scope of i, by declaring it in the control expression: for (int i = 0;  i < n;  ++i).

     location[i]=origin[i];

We ought to tell the compiler (with restrict) that the arrays don't overlap.

I think it's simpler just to forward to memcpy():
#include <string.h>
void copy(int *restrict dest, int const *restrict origin, size_t count)
{
    memcpy(dest, origin, sizeof *dest * count);
}

But that's so simple that I don't think we want a separate function for it (particularly with such a broad name).


Dividing an arbitrary dollar amount into the fewest bills and coins

The computed property minBills modifies the value property, which would
be unexpected to the caller:

let cash = Cash(value: 50.0)
print(cash.minBills!) // [1, 0, 0, 0, 0, 0, 0, 0, 0]  OK!
print(cash.minBills!) // [0, 0, 0, 0, 0, 0, 0, 0, 0]  What?

Better make value a constant property:

let value: Double

and create a mutable copy only for the computation.

let bills = [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01]

can be made a type property

static let bills = [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01]

because it is the same for each instance.

But why do you need a class at all? This could be just a (free) function

func minimumBills(for value: Double, withDenominations: [Double]) -> [Int]?

instead. Or, if you plan to add more functionality to the Cash type,
consider defining it as a struct unless the reference semantics of a class
are explicitly needed.

Another possible design would be to define a CoinSystem type with
“factory methods” for known coin systems:

public struct CoinSystem {
    let denominations: [Double]

    public init(denominations: [Double]) {
        self.denominations = denominations
    }

    public func optimalBills(for value: Double) -> [Int]? {
        // ... computation here ...
    }

    public static var usDollar = CoinSystem(denominations:
        [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01])
}

This would be used as

let usCoins = CoinSystem.usDollar
let optimal = usCoins.optimalBills(for: 12.34)

and allows adding more coin systems easily.

Now let us consider the “main code,” i.e. the computation of

public var minBills:[Int]?

tempArray and tempValue are bad variable names because they do not
indicate what the variable stands for. Also tempValue is only needed
inside the scope of the for-loop.

Returning early on error conditions simplifies the code and saves one
indentation level:

if value < 0 { return nil }

or

guard value >= 0 else { return nil }

Iterating of the bills array is better done with

for bill in bills {
    // ...
}

instead of subscripting.

Summarizing these suggestions, the code could look like this:

public struct CoinSystem {
    let denominations: [Double]

    public init(denominations: [Double]) {
        self.denominations = denominations
    }

    public func optimalBills(for value: Double) -> [Int]? {
        guard value >= 0 else { return nil }

        var remainingValue = value
        var result = [Int]()
        for denomination in denominations {
            let count = Int(remainingValue/denomination)
            remainingValue -= Double(count) * denomination
            result.append(count)
        }

        return result
    }

    public static var usDollar = CoinSystem(denominations:
        [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01])
}

You said

  .... outside of an occasional error I'm having with computing pennies ...

That is to be expected, because Double is  binary floating point number,
and cannot represent all (decimal) fractions exactly. Good resources for
this topic are

What Every Computer Scientist Should Know About Floating-Point Arithmetic
Is floating point math broken? on Stack Overflow.

Possible remedies are

Work with integers only (representing cents, or whatever the lowest
possible denomination is).
Use the Decimal
type to represent the monetary values.

Finally: What you are solving is the Change-making problem,
and your approach is the “greedy method:” Always pick the largest denomination
which is not greater than the remaining amount.
This gives the optimal result for so-called “canonical coin systems,”
like the one used in the US, but not necessarily for arbitrary coin systems.

The general problem can be solved with dynamic programming, and you'll find
further information in the above referenced Wikipedia page.


You have a major security vulnerability.

As in, serious enough that if I knew your web address, I could delete your entire database.

Near the top of your code, you set $cid to the raw value of $_POST["cid"]. That's bad. You need to escape this data before you put it anywhere near a database.

As of rit now, if I send a POST request to this page with the cid parameter set to ; DROP DATABASE Inventory; --, your entire database is gone. That string will be put into the $cid variable, and then when you execute these lines:

$query = "SELECT id FROM Handouts WHERE name='$name' AND cid=$cid";
$result = mysqli_query($sql, $query);

the following query will be executed on your database:

SELECT id FROM Handouts WHERE name='' AND cid=; DROP DATABASE Inventory; --

The first query will throw a syntax error, the second will delete your database, and any subsequent queries are commented out.

You need to fix this before you do anything else.


Convert seconds to hours, minutes and seconds

// Inital Time in seconds
        BigDecimal actualTime = new BigDecimal(5404);

Why store this in a BigDecimal?  First, you aren't including a fractional part.  Second, it's just not that big.  The thirty-one bits of an int is enough for almost seventy years worth of seconds.  Sixty-three bits (long) is enough for over two hundred billion years of seconds.  You're only producing hours as output.  If you need more than twenty bits, you should probably add at least days if not weeks.

        BigDecimal seconds = new BigDecimal(60);

This seems like a constant, which you would probably define outside the function.

         private final static int SECONDS_PER_MINUTE = 60;

I also find the name misleading.  When I see seconds, I don't think that there are sixty seconds in a minute.  I think that this is the seconds portion of the time.

Don't put everything in main

You have more logic in your main method than you should.  Part of what makes the other solution better is that it only has two lines in its main method.  As a general rule, you want to put all your programming logic in other methods.  The main method should just handle input, output, and calling the methods that do the real work.

Why do floating point operations?

        // dividing original time to get time in mintues
        BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING);

        // to get value of seconds from minutes
        double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue());

You don't need floating point operations here.  You're essentially approximating fast integer operations with slower floating point operations.

        int seconds = actualTime;
        int minutes = seconds / SECONDS_PER_MINUTE;
        seconds %= SECONDS_PER_MINUTE;

This also gets rid of all the extraneous doubleValue() and Math.floor calls.

Note that the use of doubleValue reinforces the point that you don't need BigDecimal.  If all your values fit into a double without loss of precision, why put them into a BigDecimal?

This may work.  But I would be worried that the rounding would sometimes cause the wrong value.  Particularly since two decimal digits make a repeating fractional part in binary.  Perhaps there's no value that makes this not work, but why take that chance?

Don't repurpose constants by value

        // dividing minutes by 60 to get actual time in hours
        BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING);

This is just horrible.  It would be better to just say 60 than reuse seconds to mean the number of minutes in an hour.

Eek

        // suppose time is 1.30 , below code is to get the 30 minutes

If the hours are 1.30, then that .30 is not 30 minutes.  It's 18 minutes.

        double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue);

        // converting value in units of Time since it is always measured wrt 60
        minutes = convertDateinTimeUnit(minutes);

and

    static double convertDateinTimeUnit(double value) {
        double valueInTimeUnit = 60 * value / 100;
        return valueInTimeUnit * 100;

    }

Other than potentially odd rounding effects, the net effect of this method is to multiply value by 60.  I'm not sure what you think is happening here, but you are just multiplying by sixty (with some loss of precision).

A side issue is that this only works for seconds and minutes expressed as fractions of minutes and hours respectively.  I'm not sure why you mention "Date" at all.

The camelCase standard has you capitalizing every word after the first, so this would more normally be written convertDateInTimeUnit.

Use Math.floor to truncate

        // suppose time is 1.30 below code is get 1 value
        String str = new Double(hoursdecimalValue).toString();
        str = str.substring(0, str.indexOf('.'));
        double v = Double.valueOf(str);

You could have just said

        double hours = Math.floor(hoursDecimalValue.doubleValue());

and saved the extra overhead of converting to and from a string.  Especially since you were already using Math.floor to calculate this value.

You're essentially reinventing

        int hours = minutes / MINUTES_PER_HOUR;
        minutes %= MINUTES_PER_HOUR;

Only you're using a lot more code that only approximates these values.  If you want the integer mathematics behavior, why not just work with integers?

Binary division

When you store .1 as a binary value, it gets store as a series of bits.  Decimal 10 is 1010 in binary.  So

$$1 / 1010_2 = .0001100110011...$$

Since it repeats, it means that it may not convert back perfectly.  For example, if you round to four binary digits, it is .0001 or .0010 (depending on whether you round down or up).  The first of those is one sixteenth and the latter is one eighth.  If you round to five binary digits, it is .00011, which is exactly 3/32.

Anyway, take .1 and .2, convert to binary rounded to four digits (round up if the next digit is a 1), and then add them.  So .0010 + .0011 = .0101, which is 5/16 or .3125.  You're already off by an eightieth.  You could be off less with more digits, but you'll still be off by some small amount.

When you do all your roundabout math operations, these errors are building (and occasionally dropping).  I would be concerned that you will occasionally get the wrong answer if you pick a value where it builds errors more than it drops them.


Converts data in a HashMap to a custom object

As dustytrash already mentioned in a comment, it would be much more sensible to simply use the Response object as the map key and be done.

If this is not possible due to unknown external constraints, move the translation to and from String into the Response object.

class Response {
    public static Response fromString(String s) {
        // ... do the parsing here
    }

    @Override
    public String toString() {
        // generate "98U|6765" or whatever
        // debatable: maybe don't use the overridden toString for the technical representation
    }
}

This encapsulates the nitty-gritty details of conversion in the class itself.

The converson then boils down to

map.keySet().stream()
    .map(Response::fromString)
    .collect(Collectors.toList());


Typically localization might be achieved through storing localization in configuration files (perhaps in JSON) which would be deployed along with the application. The appropriate config would be loaded into memory based on localization setting such that main app code code just references a string identifier.

This would be in contrast to your approach of loading all translations into javascript variables in memory, which could get memory intensive if you have a large number of strings.

So you might take a look at a plug-in like this which takes this general approach.


A LinkedHashSet would be simpler:

When the size reaches the limit, simply remove the first entry, no need to iterate
When adding an entry, if it already exists, you'd have to reinsert it to update the order: remove and then add
No more need to worry about the time of insert

Another advantage of this method is that the entries will be naturally ordered. In your current solution they are unordered, which could appear odd to users. This is not a big advantage though, because you could easily sort before returning the collection.


Optimize simple C++ function to minimize copying

A few things about your code that you could improve:

There is an error in powerset: while it works fine with your test case, you specifically try to return an std::vector<int> when size is 0 while you should be returning an std::vector<T>.
You don't even need the dummy vector. You can take advantage of uniform initialization and brace initialization in a return statement to simply write this:

return { {} };

Using s.size() == 0 in a condition is fine, but the idiomatic way to do it would be to use s.empty(). While it does not make a big difference for std::vector, some implementations of std::list still implement a \$O(n)\$ size while empty will always be \$O(1)\$ (C++11 requires std::list::size to be \$O(1)\$ but not all implementations are up-to-date). Using empty will be better if you ever need to change the kind of collection you use.
Since pss won't be used after the last for loop of powerset, you can safely move the elements out of it instead of copying them:

for(auto&& i : pss) {
  // Add a set with v added for each set
  i.push_back(v);
  ps.push_back(std::move(i));
}

The vectors in pss will be moved into ps, but left in a valid state, so you don't have to fear errors or undefined behaviour.
Every time you call powerset, you copy a full std::vector while you only need to read the elements. Instead of a vector, you could pass iterators so that you don't have to endlessly copy vectors that you only need to read:

template<typename T>
vector<vector<T>> powerset(typename vector<T>::iterator first, typename vector<T>::iterator last)
{
  // Return the powerset containing the empty set
  if(std::distance(first, last) == 0) {
    return { {} };
  }

  --last;
  T v = *last;

  // Recursively generate powerset for s setminus v
  vector<vector<T>> pss = powerset<T>(first, last);
  // This is the basis for the current powerset set
  vector<vector<T>> ps = pss;

  for(auto&& i : pss) {
    // Add a set with v added for each set
    i.push_back(v);
    ps.push_back(std::move(i));
  }

  return ps;
}

This is not the prettiest in the world, but it works, and you should even be able to generalize the agorithm so that it takes any BidirectionalIterator instead of mere std::vector<T>::iterator.


Addressing the duplication, it seems that both conditions are processed the same with the exception of format. You could either provide an inline conditional (ternary statement) to determine the format to use or pass the codeID to a function and return the respective format. At that point the if/else narrows in context and is only applied at the building of strLabel/strLabelPct2.

The function usage would be more extensible if the need for code modifications were to arise, as such, it would be my preference.

Function:

var applyFormatting = function(codeID, data) {
  if (codeID == 1 || codeID == 32 || codeID == 28 || codeID == 33 || codeID == 10) {
    return  $.formatNumber(data, { format: '#,###', locale: "us" });
  }
  return $.formatNumber(data, { format: '#,###.0', locale: "us" }) + "%";
  };

for (var i = 0; i < gl2.length; i++) {
  var g2 = globals.featureLayers[2].graphics[i];

  var affectedValue = applyFormatting(codeID, findFips(g2));

  var strLabel2 = g2.attributes.NAME + ":" + affectedValue;
  var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font);
  textSymbol2.setColor(new dojo.Color([0, 0, 0]));
  var pt2 = g2.geometry.getExtent().getCenter();
  var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2);

  //add label to the map
  globals.map.graphics.add(labelPointGraphic2);
}

Ternary:

 var codesThatAffectLabel = [1, 32, 28, 33, 10];

 for (var i = 0; i < gl2.length; i++) {
  var g2 = globals.featureLayers[2].graphics[i];
  var data = findFips(g2);

  var affectedValue = (-1 != codesThatAffectLabel.indexOf(codeID))
                    ? $.formatNumber(data, { format: '#,###', locale: "us" })
                    : $.formatNumber(data, { format: '#,###.0', locale: "us" }) + "%";

  var strLabel2 = g2.attributes.NAME + ":" + affectedValue;
  var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font);
  textSymbol2.setColor(new dojo.Color([0, 0, 0]));
  var pt2 = g2.geometry.getExtent().getCenter();
  var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2);

  //add label to the map
  globals.map.graphics.add(labelPointGraphic2);
}


Invoking thread for each item in list simultaneously and returning value in Java

Consider following point:

For Request.send() is thread safe as it does not used any sharing resource of Request class.
As per provided code single(singleton) object will be created as per default spring configuration.
You must shutdown ExecutorService once no more thread need to be add.


General Advise
Online coding challenges may not be timed as far as how long it takes to write them. Take the time to write better code rather than rushing through it. Don't make assumptions about the size of data or the run time that is allowed, on line research may be incorrect about this, because times won't be posted.

Big O Calculation
Does the Big O Calculation include the call to sort() if not, then that can be part of the timing problem.

Use Functions
The program is too complex and needs to be broken into functions. One function gets the array of numbers of input. Another function should do the calculation. The main() function should just control the program.

Declare Variables as Needed
There is a list of variables at the very beginning, this is more C like than C++. If the program is broken into functions this large list of variables at the top is not needed.

Meaningful Variable Names
The variable size is a good name, although the type might be size_t rather than int. The other variable names might be more meaningful if the were declared where they were needed.

Missing Includes
The code is missing some necessary include files:

#include <vector>
#include <iostream>
#include <algorithm>

std::sort()
The call to sort is missing the third argument, which should be the comparison to use in the sort.


Let me start by saying that there's nothing wrong with your approach, and almost nothing wrong with your implementation. Just two things I would like to remark.

Use of super.

Because of your use of super, you actively prevent subclassing. In Python 2.7, you're supposed to spell the name out long:

current = super(Array, self)

Consider this:

class Brray(Array): pass
b = Brray([[[1,2,3],[4,5,6]],
           [[0,1,2],[9,8,7]]])
print b[1, 0, 2]

This gives us

TypeError: 'int' object is not iterable

By using super(Array, self) instead, everything is fine again.

Subclassing list

You're subclassing list, which causes a = Array(...) to make a shallow copy of the supplied iterable. I myself would prefer composition:

class Array(object):
    def __init__(self, wrapped):
        self._wrapped = wrapped
    def __getitem__(self, indices):
        current = self._wrapped
        for index in indices:
            current = current[index]
        return current

(This is also aided by the fact that I don't like calling 'dunder' (double under) methods directly.


Determining the least-accurately known physical constants

I think the biggest problem here is that you're trying to do too much in a single line.  It seems obscure because it is obscure.  If I were looking at this outside of a Code Review setting, I would think that someone had purposefully obfuscated it or condensed it for some character count restriction.

Consider breaking apart your lines in order to make your code more legible.  Whoever looks over or has to maintain your code in the future (even if it's just you) will be incredibly grateful for it.

I was going to try and break this down into a legitimate block of code, but I have absolutely no idea what your various variables are supposed to represent.  What does the v list hold (e.g., what is v[0]? what is v[2]?).  But let's take your last line of code, which is at least somewhat comprehensible:

print(constants[constants['rel_unc'] > 0][['name', 'rel_unc']][-10:])

You're doing like four things here.  You're comparing to produce a bool, extracting an element of a list, performing a string slice operation, and printing a value.  Again, it seems obscure because it is obscure.

I can't even begin to trace out what you're trying to do in your first line of code, unfortunately, or I would.

I have a story which demonstrates the point.  On one of my more recent projects at work, a contractor had produced some code with several nested ternary conditions.  It looked something like this, in one line of JavaScript:

var_1 ? long_complex_variable_1 : var_2 ? long_complex_variable_2 :
    var_3 === var_4 ? (var_5 ? long_complex_variable_3 : long_complex_variable_4) :
    long_complex_variable_5

It took me awhile to figure out exactly what he was trying to accomplish.  When I asked him about it later, he said he thought he was being very clever and doing something good for the code by being "short and succinct".

But it's not clever, and it's far from helpful.  It's just frustrating for the people who have to maintain your code later.