Applying multiple php FilterIterator instances in a cascading fashion

Edit

One suggestion is to make your helper class more dynamic. As it currently stands it is heavily tied to each filter class so you could not reuse it in another project. For example, imagine a new project that deals with selling cars. Your Select helper class only knows about orders, services, providers. You'd have to rewrite it to know about cars, prices, colours etc.

To get around this, you can define a filter property which holds a list of filters. Then, when calling get(), loop over the filters and apply each one. The benefit here is that the helper class is now
unaware of any filter implementations and can be used in any project.

<?php

/*************************************************/
/******************** FILTERS ********************/
/*************************************************/
class Order extends FilterIterator
{
    private $_value = null;

    public function __construct(Iterator $iterator, $value)
    {
        $this->_value = $value;
        parent::__construct($iterator);
    }

    public function accept()
    {
        return $this->current()->order === $this->_value;
    }
}

class Future extends FilterIterator
{
    public function __construct(Iterator $iterator)
    {
        parent::__construct($iterator);
    }

    public function accept()
    {
        return $this->current()->date > new DateTime();
    }
}

class Date extends FilterIterator
{
    private $_value = null;

    public function __construct(Iterator $iterator, $value)
    {
        $this->_value = $value;
        parent::__construct($iterator);
    }

    public function accept()
    {
        return $this->current()->date === $this->_value;
    }
}

/*************************************************/
/*************** COLLECTION HELPER ***************/
/*************************************************/
class Helper
{
    private $_items = [];
    private $_filters = [];

    public function __construct(array $items)
    {
        $this->_items = (new ArrayObject($items))->getIterator();
    }

    public function filter($filter, $value = null)
    {
        $this->_filters[] = [$filter => $value];

        return $this;
    }

    public function get()
    {
        foreach ($this->_filters as $filter) {
            foreach ($filter as $name => $value) {

                if ($value) {
                    $this->_items = new $name($this->_items, $value);
                } else {
                    $this->_items = new $name($this->_items);
                }
            }
        }

        return iterator_to_array($this->_items);
    }
}

/*************************************************/
/****************** TEST CASES *******************/
/*************************************************/
class Reservation
{
    public $order = null;
    public $date = null;
    public $status = null;

    public function __construct($order, $date, $status)
    {
        $this->order = $order;
        $this->date = $date;
        $this->status = $status;
    }
}

$reservations = new Helper([
    new Reservation(123, new DateTime('+1Day'), 'Active'),
    new Reservation(512, new DateTime('+2Month'), 'Active'),
    new Reservation(456, new DateTime('-6Hour'), 'Pending'),
    new Reservation(789, new DateTime('-17Day'), 'Cancelled'),
    new Reservation(264, new DateTime('+1Hour'), 'Pending'),
    new Reservation(151, new DateTime('+1Year'), 'Active'),
]);

$filtered = $reservations
    ->filter('Future')
    ->filter('Order', 151)
    ->get();

var_dump($filtered);

Final note - I played around with the implementation for a while and found FilterIterators to be rather cumbersome because I had to write a single filter class for each permutation of a property. For example, in a reservation system you'd need the following filters: ByOrder, ByOrderNotEqualTo, ByDate, ByFuture, ByPast, By6MonthsFromNow, ByStatus, ByStatusNotEqualTo, ByCustomerId, etc.

One solution is to add a where method to your helper class which would accept a comparison operator. Again, I point you to Laravel's implementation and a document highlighting its usage. Food for thought.

EndEdit

If you're looking for a simple method, take a look at Laravel's implementation of their Collection::filter which calls Arr::filter. It provides a clean, chainable way to pass a callback to array_filter.

Below, is a basic demonstration on how to use it. I've implemented it using ArrayObject but you can use any iterable class. The filter calls will be slightly longer to type out than your implementation since you must define a callback function each time, but it makes the source much cleaner since you don't have to define a separate filter class for every property.

http://sandbox.onlinephpfunctions.com/code/cea564648d52c702e112d9775d1afe76f41fc810

<?php

class Collection extends ArrayObject
{
    public function filter(callable $callback = null)
    {
        if ($callback) {
            // This will return a new Collection object with the filtered results.
            // Late static binding -  You **could use either `static`
            // or `self` here since both will resolve to Collection.
            // Going with `static` in case you want to extend this class.
            // See - https://stackoverflow.com/q/5197300/296555
            return new static (array_filter($this->getArrayCopy(), $callback, ARRAY_FILTER_USE_BOTH));
        }

        return new static (array_filter($this->getArrayCopy()));
    }
}

class Reservation
{
    public $order = null;
    public $date = null;
    public $status = null;

    public function __construct($order, $date, $status)
    {
        $this->order = $order;
        $this->date = $date;
        $this->status = $status;
    }
}

$reservations = new Collection([
    new Reservation(123, new DateTime('+1Day'), 'Active'),
    new Reservation(512, new DateTime('+2Month'), 'Active'),
    new Reservation(456, new DateTime('-6Hour'), 'Pending'),
    new Reservation(789, new DateTime('-17Day'), 'Cancelled'),
    new Reservation(264, new DateTime('+1Hour'), 'Pending'),
    new Reservation(151, new DateTime('+1Year'), 'Active'),
]);

$filtered = $reservations
    // Active reservations
    ->filter(function ($value, $key) {
        return $value->status === 'Active';
    })
    // In the future
    ->filter(function ($value, $key) {
        return $value->date > new DateTime();
    });

var_dump($filtered);

Finally, here's a decent package that took this idea a step further and implements most array functions so you can chain them.


Two things stick out to me:

First, Python has an official style-guide, PEP8. It recommends consistently using 4 spaces as indentation (you use a mix of two and four). It also recommends using lower_case_with_underscores for names.

Second, the sets module has been deprecated. You can just use the built-in set, instead of sets.Set.

import random

def monty_sim(n):
    k = 0
    for i in range(n):
        s = set([1, 2, 3])
        doors_to_switch = set([1, 2, 3])
        car_door = random.randint(1, 3)
        chosen_door = random.randint(1, 3)
        doors_to_switch.remove(chosen_door)
        if chosen_door != car_door:
            s.remove(chosen_door)
        s.remove(car_door)

        monty_door = random.sample(s, 1)[0]
        doors_to_switch.remove(monty_door)
        newdoor = random.sample(doors_to_switch, 1)[0]
        if newdoor == car_door:
            k += 1
      return float(k) / float(n)

if __name__ == "__main__":
    print monty_sim(10000)

This even comes with a nice speed-boost for free!

In [2]: %timeit montysim(10000)
10 loops, best of 3: 109 ms per loop

In [4]: %timeit monty_sim(10000)
10 loops, best of 3: 54 ms per loop


Multi or n-armed bandit reinforcement learning in R

There were quite a few things wrong with your implementation:

In both the if and else parts, choice ended up being a numeric (a non-integer, e.g. 0.6532) when it should be an integer. The problem was that a) you where using max instead of which.max inside bestArm and b) randomly picking a value from arms instead of its index.
Inside the else part, you were using k and rwd without setting them.
your computation of the running mean was not using weights as the python implementation does
This won't have a significant impact, but I think the python implementation had an issue: the observed mean rewards av should be initialized to zero, not one.

Here are other improvements I would suggest:

The if/else should be limited to the picking of the choice index. Everything else should be moved after the if/else as to not repeat code. This was a problem from the original python implementation you pointed to.
Instead of writing a script, you should write a function. It is a good way to isolate the inputs and outputs of your program, it gives you an easy way to test with different input parameters, to share your code, etc.
use spaces to make your code easier on the eyes. Spaces also avoid ambiguous situations for people who are not experts in R's syntax rules; for example, when someone sees a<-b, is it assigning b to a, or is it asking if a is less than -b? Maybe another way to convince you is to make you notice that R's compiled code does contain spaces (run print(lapply) for example); it shows that R's authors agreed that code readability was more important than compactness.
If you are slowly building a vector (runMean) and know in advance its final length, initialize it with that exact length: runMean <- rep(NA, iter). Otherwise, at each iteration R will have to create a longer object and this will significantly slow down your code for any large number of iterations.

So the code could look like this:

n.armed.bandit.sim <- function(iter = 500, n = 10, eps = 0.1, max.reward = 100) {

  arms <- runif(n)
  av <- rep(0, n)
  counts <- rep(0L, n)

  reward  <- function(prob) sum(runif(max.reward) < prob)
  bestArm <- which.max

  runMean <- rep(NA, iter)
  for (i in seq_len(iter)) {
    choice <- if(runif(1) > eps) bestArm(av) else sample(n, 1)
    counts[choice] <- counts[choice] + 1L
    k <- counts[choice]
    rwd <- reward(arms[choice])
    old_avg <- av[choice]
    new_avg <- old_avg + (1 / k) * (rwd - old_avg)
    av[choice] <- new_avg
    runMean[i] <- weighted.mean(av, counts / sum(counts))
  }
  plot(runMean)
}


Concise Function Body

The function body of an arrow function can be concise.

For instance can getMatrixColumns shorten to

export const getMatrixColumns = (a: number[][]) => a[0].length;

Method Name

The method names getMatrixColumns and getMatrixRows let me expect that the the methods return a number[] instead of a number.

A better fit are getMatrixColumnLength and getMatrixRowLength.

Redundant Method Names

Each method name expect dotProduct contains some how the word matrix.

It is sufficient if the methods are grouped in a Matrix module and have names like:

// in matrix.js

export const columnLenghtOf = (a: number[][]) =>
    a[0].length;

export const rowLengthOf = (a: number[][]) =>
    a.length;

export const areValid = (a: number[][], b: number[][]) =>
    columnLenghtOf(a) === columnLenghtOf(b);

/* ... */

Type Alias

Matrix could be a type alias for number[][]:

// in matrix.js

type Matrix = number[][]

export const columnLenghtOf = (a: Matrix) =>
    a[0].length;
```


jQuery toggle class and content on click of link

$('.hidden-content').hide(); can be moved to CSS. This will be better UX and user will not see any flickr on the screen if page take long time to load and thus hide the element by JavaScript.

.hidden-content {
    display: none;
}

To check if an element have a class, hasClass() can be used instead of is().

The methods can be chained $i.removeClass("angle-down").addClass("angle-up"); but there is better way to do this.

To toggle the class on an element, toggleClass() can be used. This also accepts callback function.

$('selector').toggleClass(function() {
    return $(this).children().hasClass('angle-down') ? 'angle-up' : 'angle-down';
});

toggleClass also accepts list of classes separated by space. If the element have already applied one of the class from it, toggleClass will remove it and add other classes. Now, the code will become,

$('selector').toggleClass('fa-angle-down fa-angle-up');

Demo:

Note that in Demo, I've added Font-Awesome to demonstrate the functionality.

$(document).ready(function() {
  $(".hidden-content-reveal").click(function() {
    $(this).children().toggleClass('fa-angle-down fa-angle-up');

    $(this).next('.hidden-content').slideToggle();
    return false;
  });
});
.hidden-content {
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Nulla facilisi. Cras non egestas lectus. Duis malesuada eleifend neque, eget tincidunt elit convallis sed.Nulla facilisi. Cras non egestas lectus.


Substitution of different occurrences of a string with changing patterns

import json

def fixup(pairs):
   return pairs

decoded = json.loads(bad_json, object_pairs_hook = fixup)

object_pairs_hook is a more recent addition. If you have an older version of python you may not have it. The resulting python object will contain lists of pairs (including duplicates) rather then dictionaries.


I have created the following function and class to test your code with:-

function node_load($load)
{
    return new node();
}

class node
{
    public $type = 'bogus';
    public $title = 'Node title ';
}

Let's take a look at your code step by step, so we can work out what is wrong with it.

First let's see what happens if we var_dump the output of node_load():-

$node = node_load(1);
var_dump($node);

Output:-

object(node)[35]
  public 'type' => string 'bogus' (length=5)
  public 'title' => string 'Node title ' (length=11)

That looks about right, so let's see what happens if we put it in an if statement.

if($node = node_load(1)){
        var_dump($node);
    }

Output:-

object(node)[36]
  public 'type' => string 'bogus' (length=5)
  public 'title' => string 'Node title ' (length=11)

There doesn't seem to be any problem there either. So, lets try the compound if statement you have:-

if($node = node_load(1) && $node->type = 'bogus' ){
    var_dump($node);
}

Output:-

boolean true

Hmm, what's happened here? Well if you take a look at how logical operators work, you'll see that the result of a logical statement like node_load(1) && $node->type = 'bogus' is a boolean true or false, which you've just assigned to the variable $node. You've lost the object that was previously referenced by that variable. Hence when you try to do:-

print $node->title . 'is bogus';

you will get a "Warning: Attempt to assign property of non-object " as $node is now a boolean and not the object you were expecting.

That seems to me to be a pretty good reason for not assigning variable in an if statement as you are doing. Assign before the if statement and then test:-

$node = node_load(30);
if ('bogus' === $node->type) {
    print $node->title . 'is bogus';
}

Output:-

  Node title is bogus

Which is what is wanted. I'm sure you'll agree the re-factored code is much easier to read and as an added bonus, it works!

You may notice that I have reversed the normal order of the comparison, using 'bogus' === $node->type rather than $node->type === 'bogus'. This will raise an exception if you type '=' instead of '==' or '===' by mistake and make debugging much easier. It is a good habit to get into, as is using strict type comparisons with '===' rather than loose comparisons with '=='.

I might add that doing little step by step tests like this is a good way of working out what code actually does and reinforces the concepts of programming in your mind. I always do it when I come across functions/concepts that are new to me.


Getting a value from an Excel sheet column

Don't be afraid of having more variables. I suspect that the value in range has a different contextual meaning when it is used in the first if clause vs the inside of the while loop. If this is the case, make two different variables with names that describe what the contextual meaning is for the specific variable. The type system will help you know the variable is a Range. A name like price or id (it all depends on what you are using it for) will make the code easier to read.

Building on what @Malachi said: You don't need to define your variables at the beginning and assign them a default value.

string A1 = String.Empty, Val = String.Empty;
char[] value = null;
range = readSheet.get_Range(cell, Missing.Value);
A1 = range.Text.ToString();
value = A1.ToCharArray();

//is the same as

range = readSheet.get_Range(cell, Missing.Value);
string A1 = range.Text.ToString();
char[] value = A1.ToCharArray();


Preventing SQL Injection

  A lot suggest using mysql_real_escape_string

Some people do suggest this, but it's a bad suggestion. The only proper defense against SQL injection are prepared statements.

Escaping is at best a second-best solution in case you cannot use prepared statements for some reason.

  But that isn't an option, since it's depreciated now.

mysql_ is deprecated, and has been for quite some time. mysqli_ however is not, and it does offer mysqli_real_escape_string. Still, prepared statements are the way to go.

The good news is that you use prepared statements, and use them correctly, so you are defending against SQL injection exactly as you should be.

Your additional Filters

That being said, your additional filters are not helping, and are in fact adding a false sense of additional security:

Replacing  with _ doesn't really prevent anything. Pretty much all attacks I can imagine would likely still be possible, depending on the concrete situation. For SQL injection, you could eg use comments (/**/) instead of spaces.
your regex checks if there is any word character given. So ' and 1=1-- would pass through it, as a is a word character.

But as I said, your code is secure against SQL Injection, so you don't need additional protection. Still, input filtering as defense in depth is a good idea (just not the way you were filtering), although I would do it in a centralized place and a bit more structured. See eg here.

As you mention XSS: As you are not echoing anything variable, you do not need to worry about XSS at the moment.

Misc

your indentation is off, making your code hard to read (it's eg hard to see what the last else closes).
your spacing is also off, as is your positioning of brackets.
you never use $pname.
it's not clear to me why you sometimes die and sometimes echo.
you can make your queries more readable by separating keywords and variables by case. So for example, keywords could be all uppercase, variables all lowercase.

Given all of this, your code could look something like this:

require 'connection.php';
if(!isset($_GET['pname'])) {
    return "
Error
";
}

$query="SELECT schema_name FROM information_schema.schemata WHERE schema_name = :pname;";
$query_params = array(
    ':pname' => $_GET['pname']
);

$prep = $conn->prepare($query);
$result = $prep->execute($query_params) or die("failed!");
$row = $prep->fetch();

if($row) {
    echo "Exists" ;
} else {
    echo "doesn't" ;
}


c++17 compatible std::bind_front alternative

Are there some cases in std::bind_front that I missed?

There are several significant differences between std::bind_front's behavior and your implementations.

First, your implementation unconditionally returns a value. But what if the callable in question returned a reference? The behavior is just incorrect.

Second, std::bind_front is SFINAE-friendly but yours is not. That is, I can check to see if I can invoke the result with a certain set of arguments. Here is a silly example demonstrating this:

auto f = [](int i, int j) { return i + j; };
auto g = std::bind_front(f, 1);
auto g2 = your::bind_front(f, 1);

// this is ok, static assertion doesn't trigger
static_assert(!std::is_invocable_v<decltype(g), int, int>);

// this is a compile error
static_assert(!std::is_invocable_v<decltype(g2), int, int>);

Basically, asking the question "Can I call you with two ints?" leads to an instantiation failure outside of the immediate context, and will always be a hard error.

You can fix this and the reference issue described above by specified the correct return type instead of auto:

template <class... Args>
inline std::invoke_result_t<F&, A, Args...> operator()(Args&&... a) { ... }

Third, you're capturing your arguments differently. Consider:

std::string s = "Hello";
auto f = [](std::string const& s, int i) { return s[i]; }

auto g = std::bind_front(f, s);
auto g2 = your::bind_front(f, s);
s = "Goodbye";

assert(g(0) == 'H'); // ok
assert(g2(0) == 'H'); // fails

std::bind_front owns everything. You keep references to all the lvalues. The way the standard library works is if you want to capture by reference, you use std::ref.

Basically, this:

template <class F, class A>
auto bind_front(F &&func, A &&arg){
    return _bind_obj<F, A>(
        std::forward<F>(func),
        std::forward<A>(arg)
    );
}

should be:

template <class F, class A>
auto bind_front(F &&func, A &&arg){
    return _bind_obj<std::decay_t<F>, std::decay_t<A>>(
        std::forward<F>(func),
        std::forward<A>(arg)
    );
}

Fourth, your result is only invocable on a non-const object. But if the callable I'm bind_front()-ing has a const operator(), I should be able to invoke it as const too right?

The same can be said for ref-qualifiers: if I have a function object with &- and &&-qualified overloads, bind_front should respect that.

The solution is actually to write four overloads of operator():

template <class... Args>
inline std::invoke_result_t<F&, A, Args...> operator()(Args&&... a) &;

template <class... Args>
inline std::invoke_result_t<F const&, A, Args...> operator()(Args&&... a) const&;

template <class... Args>
inline std::invoke_result_t<F, A, Args...> operator()(Args&&... a) &&;

template <class... Args>
inline std::invoke_result_t<F const, A, Args...> operator()(Args&&... a) const &&;

Note that I'm also adjusting the type of F in the type trait, and be sure to move the callable in the rvalue cases.


Does my Linklist implementation have memory leaks?

It does not appear to be leaking memory (except on exit). However, there are a number of things you can do to improve this code.

Fix the formatting

Code that has poor formatting is hard to read, understand, and maintain.  For that reason, you should strive to have nicely formatted code.  In this case, that means fixing indentation and inserting whitespace.  For instance, instead of this:

cout<<"Number not in list"<<endl<<endl<<endl;

write this:

cout << "Number not in list" << endl << endl << endl;

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Separate I/O from core routines

It's often better to have input and output operation in a single place (or a few select places) rather than having them scattered in several places.  For this reason, I'd recommend having the search, insert and del routines simply be responsible for their corresponding linked list function and not print anything.  Printing can be done instead in the calling routine if needed.

Use object orientation

Because you're writing in C++, it would make sense to have the methods that operate on a class (such as node) be member functions rather than separate functions.  Objects and classes are one of the main strengths of C++ and something you should learn soon if you haven't already.  Encapsulate related code in objects where it makes sense to do so.

Eliminate global variables

Eliminating global variables will make your code more readable and maintainable, both of which are important characteristics of well-written code.  Global variables introduce messy linkages that are difficult to spot and error-prone.  Global variables can be altered by literally any code, making it difficult to understand how they're being used, and making it all too easy to inadvertently create an inconsistent state. See "how bad are global variables?" for more. The variable first should instead be passed explicitly to each routine that needs it, or you can use an object as mentioned in the previous suggestion.

Return something useful from functions

All of your functions currently return void, but the code could be improved by making some of them return a bool indicating success or failure.  For instance, del could return false if the number is not in the list or true if it was found and deleted.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Use for instead of while where appropriate

In almost every place in the code that uses a while loop, it would be much more idiomatic C++ if a for loop were used instead. For example, the print routine is currently this:

void print()
{
    node *next = first;

    while (next != NULL) {
        cout << next->n << " ";
        next = next->point;
    }
    cout << endl << endl << endl;
    return;
}

It would be better written like this:

void print(node *head)
{
    for ( ; head != nullptr; head = head->point) {
        std::cout << head->n << " ";
    }
    std::cout << "\n\n\n";
}

Note that the head parameter is being passed in rather than using a global variable, and that the namespace is explicitly used. Also, note that I've used the string literal "\n\n\n" instead of three repetitions of std::endl. This is more efficient because it doesn't force the buffer to be flushed repeatedly. Finally, I've removed the return because it is not needed for a void function.

Rethink the interface

It would be simpler and more logical for the search routine to return a pointer to the node or nullptr if it is not found.  Here's one way to write it:

node* search(node *head, int n)
{
    for ( ; head != nullptr && head->n != n; head = head->point ) {
    }
    return head;
}

Sanitize user input

Right now, if the user inputs anything that is not a number, the program stays in a loop forever. Instead of extracting an int, get a std::string and use std::stoi() to convert it to an integer.

Use helper routines

Right now, there is a lot of code duplication.  The search, insert and delete routines all search for the node first.  If you extracted this code into a helper routine to find the node before a match, returning a node *, you could reuse searchPrev within insert and delete instead of duplicating it in every function:

node* searchPrev(node *head, int n)
{
    for ( ; head && head->point && head->point->n < n; head = head->point ) {
    }
    return head;
}


Rubberduck VBA Parser, Episode V: The ANTLR Strikes Back

One would expect that a method of a parser which returns an IParseTree would be named Parse() instead of startRule() which is in addition violating the naming guidelines.

You should declare variables as near as possible to their usage. You could also omit the assignment of the call to Parse()

public INode Parse(string projectName, string componentName, string code)
{
    var walker = new ParseTreeWalker();
    var listener = new VBTreeListener(projectName, componentName);

    walker.Walk(listener, Parse(code));

    return listener.Root;
}

The VisualBasic6Parser.SubStmtContext.visibility() method is also not going conform with the naming guidelines.

  Is it a good idea to "walk" the tree like this?

It is hard to say something about something one can't see.

  It looks to me like VBParser is somewhat mixing abstraction levels... but is that much of an issue?

It is a little bit distracting to see inside a Parse() method of a VBParser class which implements an IRubberduckParser interface that a VisualBasic6Parser class is used. But I have no idea how to solve this and if this has to be solved.


Java generics with wildcard vs non generic List to deal with non generic data

@TorbenPutkonen already provided a great review, I just wanted to add something about usability.
Depending on your use case, returning a List<Object> means that you need to do the casting later. For example:
List<Object> result = flatten(myList);
for(Object o : result) {
    if(o instanceof String) {
        String myString = (String) o;
        // do something with the string
    }
    // etc...
}

If you know the type of the elements you can pass it to the method:
@SuppressWarnings("unchecked")
public <T> List<T> flatten(List<?> list, Class<T> itemType) {
    return list.stream()
            .filter(Objects::nonNull)
            .flatMap(i -> i instanceof List ? flatten((List<?>)i, itemType).stream() : Stream.of((T)i))
            .collect(Collectors.toList());
}

And then use it like:
List<String> result = flatten(myList, String.class);
for(String s : result) {
    // do something with the string
}

This is the version without streams:
@SuppressWarnings("unchecked")
public static <T> List<T> flatten(List<?> list, Class<T> itemType) {
    List<T> result = new ArrayList<>();
    for(Object o : list) {
        if(o instanceof List) {
            result.addAll(flatten((List<?>) o, itemType));
        }
        else if (o != null){
            result.add((T) o);
        }
    }
    return result;
}


You shouldn't create the database object on every function call. Read this answer (and its question) for an example of this.


To reduce the lines of code to copy/paste, you could create a helper method:
public static class Helper
{
    public static void EnsureIsInRange(short value, short min, short max)
    {
        if (value < min || max < value)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
    }
}

or more generic:
public static class Helper
{
    public static void EnsureIsInRange<T>(T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) != 1 || value.CompareTo(max) != -1)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
    }
}

// usage:
private short _index;
public short Index
{
    get => this._index;
    private set
    {
        Helper.EnsureIsInRange(value, 0, 8);
        this._index = value;
    }
}


Inserting and deleting elements in a list

Let's start with the code style, even though not asked explicitly.

It says C++, but apart from using a constructor on the struct  and using new/delete, that is pure C what you have written there.

Especially the C style input and output handling is overcomplicated, with regards to how much simpler the C++ interfaces are to use.

As for your implementation, you don't need a linked list. In fact, you don't need to store the input nor the output sequence at all, at least not for the algorithm itself.

Take a look at the problem carefully again, and try to think about how you can rephrase the operations, when do you need to consume input, and what the earliest point is, at which you can create output. Last but not least, how long do you even need to store each specific piece of information.

The first observation:
Whenever an operation has finished, the value at POS is no longer mutated, and no further insertions or deletions occur prior to POS.

The second observation:
During an operation at POS, no value other than POS has an effect on that operation. At most POS+1 is either removed or added in.

The third observation:
As all numbers are guaranteed to be natural numbers, even c - 1 > 0 must hold. Which means that in any case, POS+1 is always output in the same operation as which it is mutated in.

With that in mind, it's actually quite simple to solve this problem:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> input;
    int rounds = 0;
    bool even = false;

    // Collect the input
    std::cin >> rounds;
    int temp;
    while(std::cin >> temp) {
        input.push_back(temp);
    }

    even = (input.size() % 2) == 0;

    std::vector<int>::iterator it = input.begin();

    // Special handling for first element
    std::cout << *it;
    it++;

    for(int round = 0; round < rounds; round++) {
        // Number of steps to the right
        int steps = *it;
        if(even) {
            // Operation "R"
            // Skip one
            it++;
            // And pass through from input
            for(int i = 0; i < steps; i++, it++) {
                std::cout << " " << *it;
            }
        } else {
            // Operation "X"
            // Directly output `POS+1`
            std::cout <<  " " << *it - 1;
            // But pass through one less input in return
            for(int i = 0; i < steps - 1; i++, it++) {
                std::cout <<  " " << *it;
            }
        }
        even != even;
    }
    for(; it != input.end(); it++) {
        std::cout <<  " " << *it;
    }
}

It is unfortunately still necessary to store the entire input in memory, in order to count the elements. If it wasn't for that, you could just copy from input to output element wise.

But what's important: The data structure used is now a plain vector, which removes a lot of unnecessary stress on the memory system, as the storage method is a compact as it gets.

There are also no mutations to that data structure at all, it only serves to replay the input after counting all elements.


Checking if two floating point numbers are equal

Seems unlikely.  epsilon from std::numeric_limits is the smallest increment representable by the type (around the value 1).

You want to check for something "close to" equal, but you don't say what close to means for you. Assuming it to be a few multiples of epsilon, the following check would seem reasonable:

const int FEW = 10;
T diff = std::abs(lhs - rhs);
T epsilon = std::numeric_limits<T>::epsilon();

return diff < (epsilon * FEW);


A small emacs-lisp snippet for opening a register in another window

The first things which jump into my face are the broken indentation and a dangling parenthesis. Please fix them, otherwise the code is not very readable.

More to the point, I think it is better to replace the body with

(switch-to-buffer-other-window (register-buffer register-name))

and define

(defun register-buffer (register-name)
  (save-window-excursion
    (jump-to-register register-name)
    (current-buffer)))


Is there a more succinct way to write this Ruby function?

Functional approach:

def tags
  if cancelled?
    ["Cancelled"]
  else
    [("Filled" if filled?), ("In Progress" if in_progress?)].compact
  end
end

Ideas behind the snippet:

Don't perform imperative side-effects on arrays (unless performance is a problem, not the case here).
Use the pattern: array of "nilable" expressions + compact to build arrays with conditional elements.
Minimize the use of inline conditional statements, they make a function harder to understand. They are ok as guards (early exit of functions), but not here. Note that I do use inline ifs, but they are expressions, not statements; more orthodox -but also more verbose- would be (filled? ? "Filled" : nil).


PEP 8 says

You have minor issues with the code layout:

PEP 8 requires two empty lines before the class definition,
Modules os and math are not used,
In addValue the return statement is unnecessary,
PEP 8 proposes the method names in this_format; rename addValue to add_value.

Improving the code

I suggest you try to take use of a visitor pattern: in your traversal methods add new argument taking a function that is called with a current binary tree node. I had this in mind:

from __future__ import print_function

class BinaryTree:
    def __init__(self):
        self.__left = None
        self.__right = None
        self.__value = None

    def add_value(self, value):
        if self.__value is None:
            self.__value = value

        elif value > self.__value:
            if self.__right is None:
                self.__right = BinaryTree()
            self.__right.add_value(value)

        elif value < self.__value:
            if self.__left is None:
                self.__left = BinaryTree()
            self.__left.add_value(value)

    def pre_order_traverse(self, visitor_func=None):
        """
        Performs a pre-order traversal of the tree.
        Returns the list of elements
        """
        if self.__value is not None:
            # Visit the root node first
            if visitor_func:
                visitor_func(self.__value)
            # Then visit the left node if present
            if self.__left is not None:
                self.__left.pre_order_traverse(visitor_func)
            # Then visit the right node if present
            if self.__right is not None:
                self.__right.pre_order_traverse(visitor_func)

    def in_order_traverse(self, visitor_func=None):
        """
        Performs a in-order traversal of the tree.
        Returns the list of elements
        """
        if self.__value is not None:
            # Visit the left node first if present
            if self.__left is not None:
                self.__left.in_order_traverse(visitor_func)
            # Then visit the root node
            if visitor_func:
                visitor_func(self.__value)
            # Then visit the right node if present
            if self.__right is not None:
                self.__right.in_order_traverse(visitor_func)

    def post_order_traverse(self, visitor_func=None):
        """
        Performs a post-order traversal of the tree.
        Returns the list of elements
        """
        if self.__value is not None:
            # Visit the left node first if present
            if self.__left is not None:
                self.__left.post_order_traverse(visitor_func)
            # Then visit the right node if present
            if self.__right is not None:
                self.__right.post_order_traverse(visitor_func)
            # Then visit the root node
            if visitor_func:
                visitor_func(self.__value)

if __name__ == "__main__":
    binarytree = BinaryTree()
    binarytree.add_value(23)
    binarytree.add_value(15)
    binarytree.add_value(19)
    binarytree.add_value(8)
    binarytree.add_value(7)
    binarytree.add_value(42)
    binarytree.add_value(0)
    binarytree.add_value(1)

    def visitor1(value):
        print(value)

    class ElementVisitor:
        def __init__(self):
            self.elements = []

        def add(self, value):
            self.elements.append(value)

    ev = ElementVisitor()
    binarytree.pre_order_traverse(ev.add)
    print(ev.elements)

    print("")

    binarytree.in_order_traverse(visitor1)

    print("")

    binarytree.post_order_traverse(visitor1)

As you can see, above you can both print the nodes and collect them in a list; both by simply passing an appropriate function/object method.

Hope that helps.


Convert a type u16 number to a matrix (Vec> or array) of 4 x 4

One thing I'm going to do first is create an enum with only two values. This represents a binary value and is more memory-efficient than passing around a bunch of u8s. This way 16 Bits can be represented as 16 actual bits in memory (though this isn't guaranteed).

/// a single bit
#[derive(Clone, Copy, Debug)]
enum Bit {
    /// 1, high
    H1 = 1,
    /// 0, low
    L0 = 0,
}
use Bit::*; // allow us to just use `L0` and `H1` without the `Bit::` prefix

It is likely much faster to split a number into bits using numerical operators. There are a couple ways of doing it.

Iterating a mask

With this we increase our mask each time, building an array from it. The 15 - i is there because we want the MSB at index 0.

/// convert a number to 16 bits by sliding a mask across it
fn into_bits_mask(num: u16) -> [Bit; 16] {
    let mut out = [L0; 16];

    for i in 0..16 {
        out[15 - i] = if num & (1u16 << i) > 0 {
            H1
        } else {
            L0
        };
    }

    out
}

Shifting the number with a static mask

This is essentially the same thing, but we shift the number instead of the mask.

/// convert a number to 16 bits by right-shifting it
fn into_bits_shift(num: u16) -> [Bit; 16] {
    let mut out = [L0; 16];

    for i in 0..16 {
        out[15 - i] = if (num >> i) & 1u16 > 0 {
            H1
        } else {
            L0
        };
    }

    out
}

We can then modify these to output an array of 4 nibbles.

/// convert a number to 4 nibbles by sliding a mask across it
fn into_nibbles_mask(num: u16) -> [[Bit; 4]; 4] {
    let mut out = [[L0; 4]; 4];

    for i in 0..16 {
        let mask = 1u16 << (15 - i);
        out[i / 4][i % 4] = if num & mask > 0 {
            H1
        } else {
            L0
        };
    }

    out
}

/// convert a number to 4 nibbles by right-shifting it
fn into_nibbles_shift(num: u16) -> [[Bit; 4]; 4] {
    let mut out = [[L0; 4]; 4];

    for i in 0..16 {
        out[i /4][i % 4] = if (num >> (15 - i)) & 1u16 > 0 {
            H1
        } else {
            L0
        };
    }

    out
}

There is room for more optimization here, of course.

Here's a working example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=b010e34728d554e995e0de4ddb4b1eed

EDIT: I was asked about using iterators, so here's my most iterator-function styled method

/// convert a number to 4 nibbles using iterator methods
fn into_nibbles_iter(num: u16) -> Vec<Vec<Bit>> {
    // split into nibbles
    [num >> 12, num >> 8, num >> 4, num]
        .iter()
        .map(|nibble| {
            // mask off each bit
            [nibble & 8, nibble & 4, nibble & 2, nibble & 1]
                .iter()
                // convert to Bits
                .map(|b| if b > &0 { H1 } else { L0 })
                .collect()
        })
        .collect()
}

And here's a new playground link demonstrating it: https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=5ecda81379c3cab749709f551109adfb


Pure V State

There are two ways you can do this.

Pure

The first functional pure method first copies the array, then checks if the item to toggle exists then depending on that result adds or removes the item. Making sure that the added item is a copy, not a reference. It has no side effects but requires additional memory and CPU cycles.

const toggleItem = (itemDesc, items, prop = "name") => {
    items = [...items];
    const index = items.findIndex(item => itemDesc[prop] === item[prop]);
    index > -1 ? items.splice(index, 1) : items.push({...itemDesc});
    return items;
}

State

The second does not create a new array and keeps all references It is "functionally" impure and ensures that the changed state is available to all references to the original. It is considerably quicker and uses less memory.

const toggleItem = (itemDesc, items, prop = "name") => {
    const index = items.findIndex(item => itemDesc[prop] === item[prop]);
    index > -1 ? items.splice(index, 1) : items.push(itemDesc);
    return items;
}


Python use glob to search for files by extension

A few suggestions:

This doesn't need to be a one line function. Writing it on one line makes it much harder to understand and makes finding mistakes more difficult.
Use os.path.join to assemble your full pathname + wildcard + extension. That way, you don't need to worry about whether or not your pathname is given with or without a trailing /
If you're going to worry about a trailing / in your pathname, you should be equally worried about a preceding . in your extension.
glob.glob already returns a list with the matching files. I don't see any need for the complicated, nested list comprehensions you're using. Your function should essentially be a wrapper for calling glob.glob that simply makes combining the pathname + extension a little easier for the user.

That being said, here's how I might re-write this function:
import glob
import os

from typing import List

def find_files_with_extension(path_name: str, extension: str) -> List[str]:
    extension_wildcard = "*"

    if extension[0] != ".": # suggestion #3
        extension_wildcard += "."
    extension_wildcard += extension

    path_name_wildcard = os.path.join(path_name, "**", extension_wildcard) # suggestion #2

    return glob.glob(path_name_wildcard, recursive=True)


Creating a time-course dependent, correlation-based directed graph with Networkx

This is an awkward way of storing data. You have extremely similar variable names with similar methods of getting the data. You should put them in a list instead, and then you can get them with a list comprehension:

timepoint1_allCols=corr.filter(regex=r'(?i)_1h_', axis=0)
timepoint2_allCols=corr.filter(regex=r'(?i)_2h_', axis=0)
timepoint3_allCols=corr.filter(regex=r'(?i)_4h_', axis=0)
timepoint4_allCols=corr.filter(regex=r'(?i)_6h_', axis=0)

could be

timepoint_allCols = [corr.filter(regex=r'(?i)_{}h_'.format(hour), axis=0)
                     for hour in (1, 2, 4, 6)]

The same with your follow up variables. It's easier to understand and will avoid accidental typos leading you astray. Then it also makes looping over the three results easier:

for idx, row in timepoint_34.iterrows():
    for i,entry in enumerate(row):
        if entry > threshold:
            DG.add_edge(row.index[i], idx, weight=entry)

for idx, row in timepoint_23.iterrows():
    for i,entry in enumerate(row):
            if entry > threshold and DG.degree(row.index[i]):
                DG.add_edge(row.index[i], idx, weight=entry)

for idx, row in timepoint_12.iterrows():
    for i,entry in enumerate(row):
            if entry > threshold and DG.degree(row.index[i]):
                DG.add_edge(row.index[i], idx, weight=entry)

You do need to make some variations but I think it's better to not repeat yourself.

for num, timepoint in enumerate(timepoints[::-1]):
    for idx, row in timepoint.iterrows():
        for i, entry in enumerate(row):
            if entry > threshold and (num == 0 or DG.degree(row.index[i])):
                DG.add_edge(row.index[i], idx, weight=entry)

To explain some things, I'm looping backwards by using the slicing operator [::-1]. I'm also using enumerate along with num == 0 to check if it's your first timepoint so that you know whether or not to use the DG.degree(row.index[i]) test. This is a bit of a hacky solution, but as you're more familiar with the data and process, you could come up with a better and clearer test to determine if the test is necessary to run. The point is, that collapsing it into one loop (even if you need to test for one exception condition) is clearer and less code because the loops were so similar.


A couple of minor notes:

1) Add proper typing so that users of your code will be able to type-check their own code correctly.  I think this would look like:

from typing import Dict, List, TypeVar

_KT = TypeVar('_KT')
_VT = TypeVar('_VT')

class DoubleDict(Dict[_KT, _VT]):
    super().__init__(*args, **kwargs)
    self.values_dict: Dict[_VT, List[_KT]] = defaultdict(lambda: [])
    for key, value in self.items():
        self.values_dict[value] += [key]

... etc

2) I'd eliminate the index syntactic sugar, personally, because it makes it easier for the caller to forget that this isn't a one-to-one mapping in both directions.  Make them get the list and check to make sure that it's got the length they expect.

Alternatively, if you'd want it to be a one-to-one mapping in most cases, then enforce that in the setter and make it part of the class's contract.


Wheel based unbounded sieve of Eratosthenes in Python

I thought of two things that achieve a 27 % speedup and simplify wsieve a bit, at the expense of some precomputations.

Turning the wheel step by step from prime to prime seems wasteful. Instead of this code

while not cbase == p:
    cbase += wheel[ibase]
    ibase = (ibase+1) % wsize
j = ibase

you could do directly j = spoke_index[p % 210] having precomputed a suitable spoke_index dictionary with 48 entries. The variables cbase and ibase can be eliminated.
When a wheel is involved I find it hard to resist using itertools.cycle. Instead of this

i = 0
while True:
    c += wheel[i] ; i = (i+1) % wsize

you could do this

for step in cycle(wheel):
    c += step

The other uses of the wheel are more difficult to replace because there is no direct way to start the cycle at an arbitrary position. However, we can precompute all 48 rotations of wheels and put them in a dictionary for easy lookup.

My version of full solution. Instead of the index j I put a cyclic iterator in mults.

from itertools import cycle

CIRCUMFERENCE = 2*3*5*7
BASE_PRIMES = (2,3,5,7)
NEXT_PRIME = 11

def wheel(start):
    result = []
    i = start
    for j in range(i + 1, i + 1 + CIRCUMFERENCE):
        if all(j % k for k in BASE_PRIMES):
            result.append(j - i)
            i = j
    return result

def rotated_wheels():
    result = {}
    i = 1
    while i < CIRCUMFERENCE:
        result[i] = wheel(i)
        i = i + result[i][0]
    return result

def primes():
    yield from BASE_PRIMES
    yield from wsieve()

def wsieve(wheels=rotated_wheels()):
    yield NEXT_PRIME
    mults = {}
    ps = wsieve()
    p = next(ps)
    psq, c = p*p, p
    cwheel = cycle(wheels[c])
    for step in cwheel:
        c += step
        if c in mults:
            (mwheel, pbase) = mults.pop(c)
        elif c < psq:
            yield c
            continue
        else:          # (c==psq)
            mwheel = cycle(wheels[p % CIRCUMFERENCE])
            pbase = p
            p = next(ps) ; psq = p*p
        m = c
        for mstep in mwheel:
            m += pbase * mstep
            if m not in mults:
                break
        mults[m] = (mwheel, pbase)

Edited to use for instead of while.


Opening social media links in a new window

First of all, make sure you declare your variables using var:

  assigning a value to an undeclared variable implicitly declares it as
  a global variable (it is now a property of the global object)

Personally, I'd probably add a class to the links in question like shareLink then you could simply do:

$(".shareLink") to select all three links

Alternately, you could try selecting by id ending in _share assuming that quality is unique to these three links:

$("[id$='_share']")

I'd also suggest chaining so that your whole code would be something like this:

$("[id$='_share']").click(function(){
    var w = parseInt((screen.width - 600)/2)
    ,   h = parseInt((screen.height - 400)/2)
    ,   cwin = window.open($(this).attr('href'), 'closewin',
               'status=0,toolbar=0,location=0,menubar=0,directories=0,
               resizable=0,scrollbars=0,height=400,width=600');
    cwin.moveTo(w,h);
    return false;
  }).attr('title','opens in a new pop-up');

Finally, I'd review the documentation on Window.open to be sure you don't want to provide left or top parameters, instead of immediately moving the window, or even a different solution. Make sure you at least read the section on Usability issues


Setting color of specific keywords in a textview

First of all, some side notes:

In your keywordsgreen array, you're checking for very specific library names. But you also check for #include and #define. So what if I include <stdlib.h>? Your current code would search the text, find #include, turn it green, then search again, find <stdlib> and turn that green. But the whole line might as well be green. Instead, just look for the # symbol at the absolute start of the line (it would take a little more logic, of course). That way, you eliminate most of the keywordsgreen array.
Also, you're setting the text every single time you edit a single word. You don't need to do that. Just keep one SpannableString and pass that around, setting the textView to that all the way at the end of the function.
I don't think this should be that slow. It's not a very good solution, but even for a 300-line source file, I can't imagine it would take 5 seconds. Put all that in a new thread and see what happens.

Example:

Thread colorTextThread = new Thread(new Runnable(){
public void run(){
  //Put all that searching code in here
}//end of run
});
colorTextThread.start();

You put it on a new thread because the UI thread is super slow. Remember, though, if you want to change the textView on a separate thread, you have to use the runOnUiThread() function.

I'll add more later if no one tells you how to make the code faster. I've got to go at the moment, sorry.

EDIT:

After looking at your code again, I can't see a way to make it faster. The most important things you can do is to do the search on the "programText" variable you're passing to textView. That variable holds all the information you need, so you should manipulate that, and then pass it to textView.setText(). That way, you never have to call getText(), which means you can do all of your text processing on a separate thread. If it runs slow even on a separate thread, then yes, your code is very slow. Otherwise, problem solved for now.


Accounting for floating point error when rounding

Discovered this needs rework
Testing this with small numbers shows that for all practical purposes, this function is broken. I'd like roundupDiscount(Number.EPSILON) to be 0 (which could come about from subtracting two numbers meant to be equal, but differing by an error (similar to the classic (0.1 + 0.2) - 0.3)).
However for a number like Number.EPSILON its value, including significant digits, is 0.000000000000000222044604925031, and so the computed epsilon here being 10e-28 is way too small to have any effect. This function only really works when the integer part > 0
It can be corrected in this respect by clamping the magnitude at 0 but I think I'll have a battle to convince anyone this should go into our codebase ...
Updated implementation:
export const roundupDiscount = (discount: number) => {
    // Given that discount is "sensible", if it is equal to some integer x plus a
    // small positive error component, then it must return x. Otherwise it must
    // return Math.ceil(discount)

    if (discount < 0 || discount > Number.MAX_SAFE_INTEGER) return discount
    if (discount < Number.EPSILON) return 0

    const magnitude = Math.floor(Math.max(0, Math.log(discount) / Math.log(10)))
    const epsilon = Math.pow(10, magnitude - 12) // treat last 3-4 significant digits as error
    return Math.abs(Math.ceil(discount - epsilon)) // Math.abs to prevent -0
}

Test cases:
describe('roundupDiscount', () => {
    it('rounds the item discount correctly for numbers of differing magnitude', () => {
        let epsilon = Number.EPSILON; // machine epsilon - smallest positive number which, added to 1, will produce a value different from 1

        expect(roundupDiscount(1 + epsilon)).toBe(1)
        expect(roundupDiscount(1 + (10 * epsilon))).toBe(1)
        expect(roundupDiscount(1 + (100 * epsilon))).toBe(1)
        expect(roundupDiscount(1 + (1000 * epsilon))).toBe(1)
        expect(roundupDiscount(1 + (10000 * epsilon))).toBe(2) // "error" no longer small

        // test it handles large numbers ...
        const largeNum = 1000000000;
        const largeEpsilon = largeNum * epsilon;
        expect(roundupDiscount(largeNum + largeEpsilon)).toBe(largeNum)
        expect(roundupDiscount(largeNum + (10 * largeEpsilon))).toBe(largeNum)
        expect(roundupDiscount(largeNum + (100 * largeEpsilon))).toBe(largeNum)
        expect(roundupDiscount(largeNum + (1000 * largeEpsilon))).toBe(largeNum)
        expect(roundupDiscount(largeNum + (10000 * largeEpsilon))).toBe(largeNum + 1)

        // test it handles small numbers ...
        expect(roundupDiscount(epsilon)).toBe(0)
        expect(roundupDiscount(10 * epsilon)).toBe(0)
        expect(roundupDiscount(100 * epsilon)).toBe(0)
        expect(roundupDiscount(1000 * epsilon)).toBe(0)
        expect(roundupDiscount(10000 * epsilon)).toBe(1)
    })
})


Array whose values are the product of every other integer

For starters, you have very weird line breaks:

System.out
        .println(Arrays.toString(ProductOfAnArray
                .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7,
                        3, 2, 4 })));

That's not layout, that's obfuscation! When dealing with long method chains, it may be preferable to break before each method invocation:

someObject
  .thisIs()
  .aFluid()
  .interface();

but that's not the case here, and this layout does not increase readability. Instead, break after the opening paren of the argument list:

System.out.println(
    Arrays.toString(ProductOfAnArray.calcArray(new int[] {
        4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4
    }))
);

or something like that. Note that you could have written this as

System.out.println(
    Arrays.toString(ProductOfAnArray.calcArray(
        4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4
    ))
);

(i.e. without the explicit array) when declaring your function with varargs: calcArray(int... inp).

The next question is why you are returning an array – a List<BigInteger> would be more flexible – arrays have little use in modern Java (the usage of varargs implies arrays, and high-performance code may need them. But in all other cases, they are too inflexible – e.g. arrays and generics don't work together).

But why BigInteger? Yes, you don't want to overflow, but we can assume that your interviewers would be content with an int. If you want to allow larger numbers, the first step would be long. Big Integers are truly awkward to use and necessarily less performant that native types, so I would avoid them wherever possible.

Your code inside calcArray is unnecessarily clever. Let's look at this loop:

for (int i : inp) {
    if (i == 0) {
        cnt++;
        foundZero = true;
        if (cnt < 2)
            continue;
        else
            break;
    }
    multiple = multiple.multiply(BigInteger.valueOf(i));
}

Notice that foundZero is equivalent to cnt > 0, and that you aren't using braces around the bodies of the inner if/else. Your continue is rather confusing, and the following expresses the control flow much better:

for (int i : inp) {
    if (i != 0) {
        multiple = multiple.multiply(BigInteger.valueOf(i));
    }
    else {
        cnt++;
        if (cnt >= 2) {
            break;
        }
    }
}

This conditional in the next loop is also too complex, and could be simplified to

if (cnt < 2 && inp[i] == 0) {
    ans[i] = multiple;
} else {
    ans[i] = new BigInteger("0");
}

When applying these criticisms, the Simplest Thing That Could Work might be this:

public static List<Long> specialProduct(int... numbers) {
    long product = 1;
    int zeroesCount = 0;
    for (int n : numbers) {
        if (n != 0) {
            product *= n;
        }
        else {
            zeroesCount++;
        }
    }

    List<Long> output = new ArrayList<>(numbers.length);

    switch (zeroesCount) {
    case 0:
        // with no zeroes, we don't have to perform any checks
        for (int n : numbers) {
            output.add(product / n);
        }
        break;
    case 1:
        // with one zero, the all others will become zero too
        for (int n : numbers) {
            if (n == 0) {
                output.add(product);
            }
            else {
                output.add(0L);
            }
        }
        break;
    default:
        // two or more zeroes make everything zero
        for (int i = 0; i < numbers.length; i++) {
            output.add(0L);
        }
        break;
    }

    return output;
}

Oh, and naming! Have vocals become so precious that we must write cnt instead of count? Must we write ans instead of answer if you can actually write a long word like multiple? And what the heck is inp?

Your code is not bad, but it isn't good, and could certainly have been written better. The next time, maybe :)


Iterate through multiple elements based on their id in jQuery

Instead of IDs (like #0), use classes instead. (Numeric-indexed IDs are quite a code smell anyway.) Or, if you can't remove the IDs entirely, just add classes to those elements. For example, adding the class of subtotal-container to each of those elements with IDs.
To make things clearer, I'd also recommend calling the function something like calculateTotal instead of total - it's more precise and also avoids possibly-confusing shadowing:
function calculateTotal() {
  const total = [...$('.subtotal-container .cart-subtotal')]
    .map(subtotalElm =>
  Number(subtotalElm.textContent.replace('€', '')))
    .reduce((a, b) => a + b, 0);
  $('.cart-total-price').text(total + '€');
}

Though, at this point, you may as well remove the dependency on jQuery entirely if you wished, it's not really accomplishing anything useful:
const total = [...document.querySelectorAll('.subtotal-container .cart-subtotal')]
  .map(subtotalElm => Number(subtotalElm.textContent.replace('€', '')))
  .reduce((a, b) => a + b, 0);
document.querySelector('.cart-total-price').textContent = total + '€';

With jQuery, keep in mind that
$('someSelector').find('someOtherSelector')

is equivalent to
$('someSelector someOtherSelector')

via the descendant selector.


Lists are not for random access. As far as I know, Vectors are the modern way to have fixed-length random-access listlikes. They will allow you to do the traversing updates you want in one pass.

import qualified Data.Vector as V
counts = V.toList . V.accum (+) (V.replicate 200 0) . map (,1)

first_gt doesn't need a manual implementation:

import Safe
first_gt e = findIndexJust (> e)

And just for fun, this should only traverse the counts result once. (Requires that indices is sorted, though.)

import Control.Monad.Trans.State
solve heights = scanl1 (+) . map length . splitsOnFoo . map (subtract 1) where
  splitsOnFoo = evalState $ traverse (state . span . (<)) $ scanl1 (+) $ counts heights


Nested object to hierarchical object list

var sublayers = data.Where(i => i.ParentId == layer1.Id && i.ParentId !=0);

you should let the operators some room to breathe. Adding a space after = makes your code more readable.

Bug alert

In the above query you are filtering for i.ParentId != 0 and later on you have the condition && layer.ParentId ==0 so your hierarchy wil remain empty.

var enumerable = sublayers as Layer[] ?? sublayers.ToArray();

This makes me just wonder. What sense does it have to convert the IEnumerable<Layer> to an array if the next thing you do is iterating over the items by using a foreach loop ?

var layer1 = layer;

this isn't necessary at all, it is sufficient to use the layer inside linq expression.

You should always use braces {} for single command if statements to make your code less error prone. If you decide to no use them, please don't come back whining that you have a bug you can't find (humour btw.).

Integrating the mentioned points will lead to

public IList<Layer> GetLayers()
{
    IList<Layer> data = Db.GetLayers();

    IList<Layer> hierarcy = new List<Layer>();

    foreach (var layer in data)
    {

        var sublayers = data.Where(i => i.ParentId == layer.Id && i.ParentId != 0);

        if (sublayers.Any())
        {
            hierarcy.Add(layer);
        }
        foreach (var sublayer in sublayers)
        {
            layer.ChildLayers.Add(sublayer);
        }
    }

    return hierarcy;
}

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public IList<Layer> ChildLayers { get; set; }

    public Layer()
    {
        ChildLayers = new List<Layer>();
    }
}

You shouldn't expose the ChildLayers property setter to the public. If someone comes along setting it to null you would be lost.

You should just change it to

public IList<Layer> ChildLayers { get; private set; }

Otherwise using autoimplemented properties, as long as you don't need validation in the setters , is the way to go.


Simplify

I find the logic a bit complicated. It could be simpler:

Loop from -A to +A, let's call the loop variable n
Take the absolute value of n
Generate the values in the row:

Loop from -A to +A, let's call the loop variable m
Use the maximum of abs(n) + 1 and abs(m) + 1

Like this:

def pretty_print(num):
    def print_line(n):
        low = abs(n)
        print(' '.join(str(max(low + 1, abs(i) + 1)) for i in range(-num + 1, num)))

    for i in range(-num + 1, num):
        print_line(i)

Testing

Doctests are awesome, I recommend to use them.
Here's the complete solution with doctests,
you can run this with python -mdoctest pretty_print.py:

#!/usr/bin/env python

def pretty_print(num):
    """
    >>> pretty_print(1)
    1

    >>> pretty_print(2)
    2 2 2
    2 1 2
    2 2 2

    >>> pretty_print(6)
    6 6 6 6 6 6 6 6 6 6 6
    6 5 5 5 5 5 5 5 5 5 6
    6 5 4 4 4 4 4 4 4 5 6
    6 5 4 3 3 3 3 3 4 5 6
    6 5 4 3 2 2 2 3 4 5 6
    6 5 4 3 2 1 2 3 4 5 6
    6 5 4 3 2 2 2 3 4 5 6
    6 5 4 3 3 3 3 3 4 5 6
    6 5 4 4 4 4 4 4 4 5 6
    6 5 5 5 5 5 5 5 5 5 6
    6 6 6 6 6 6 6 6 6 6 6
    """

    def print_line(n):
        low = abs(n)
        print(' '.join(str(max(low + 1, abs(i) + 1)) for i in range(-num + 1, num)))

    for i in range(-num + 1, num):
        print_line(i)

pretty_print(6)

Style

There are some minor style issues with the posted code.
I suggest to follow the PEP8 guidelines.


C like Cpp code to do strncpy and copy a string to a buffer which is not long enough

Since you have written it for practice (as indicated in your comment), and strncpy has been implemented in various platforms in rather similar manner, I assume that you want comment on the function behavior itself and not specifically whether it conforms to the strncpy POSIX function.

I am aware that the second function strlcpy handles many of the criticisms below, but there is no indication in your question that you have considered these.

My first problem with the strncpy is that it allows no indication of failure or indication of any behavior even though there is a possibility of a few different behaviors that the user may be interested in.

The first n characters may not contain a \0
Did we truncate at n? or was the src small enough?
How many characters were copied?

We are using the return value by returning the dest even though this information is no different from the parameter that was passed in.

Secondly, if the buffer was small enough, the function is zeroing out the remainder of the memory. This seems to be a wasteful effort. Perhaps it is enough to just null terminate the string?

int strncpy(char *dest, const char *src, size_t n) {
    size_t i = 0;
    while ((i++ < n) && (*dest++ = *src++));
    if (i < n) {
        *dest = 0;
        return i;
    }
    return -1;
}


First of all, free references will be invalidated each time mPool resizes. Which will lead to all sorts of undefined behavior.

Resizing pool is not a great idea in terms of performance, too. Better have constant size chunks, and add more chunks if needed.

Such a pool implies your user is no more able to get benefits of RAII, which can be a huge loss.

For your question about static methods. It is not a bad practice per se, but your user will no longer be allowed to use different pools for the same type. If you want to make a static method, you better have strong argument to do so.

Overall, consider to use containers+allocators instead of pool.


Console.log challenge change all of the links on a search results page so that they do not go anywhere?

Refactoring is commonly seen as "moving out repeating code into reusable functions". But it can also easily mean "moving code that's only ever used once back to where it's being used". Although the book led you to writing individual functions, you don't have to split all this code up.

Also, if you're just turning a NodeList into an array just to use array.forEach(), then this conversion is unnecessary. NodeList already comes with a forEach method (unless you still care about IE).

Your code could be as short as:

document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', event => event.preventDefault())
})


Tokenizing texts from Gutenberg archive for analysis

This is the ideal place for a class. Each book is its own object with its own method of returning its tokens. I would make a method tokens, which I would make a property that fills itself on the first call to it.

Something like this:

from urllib import request
import nltk

class Book(object):
    def __init__(self, title, url, start=0, end=-1):
        self.title = title
        self.url = url
        self.start = start
        self.end = end
        self._raw = None
        self._tokens = None
        # self.words = None
        # self.words2tokens = None
        # self.pos = None

    def __str__(self):
        return self.title

    @property
    def raw(self):
        if self._raw is None:
            response = request.urlopen(self.url)
            draft = response.read().decode('utf8')
            self._raw = draft[self.start:self.end]
        return self._raw

    @property
    def tokens(self):
        if self._tokens is None:
            self._tokens = nltk.word_tokenize(self.raw)
        return self._tokens

if __name__ == "__main__":
    books = [Book('Moby Dick', 'http://www.gutenberg.org/files/2701/2701-0.txt', 28876, 28876 + 500),
             Book('Great Expectations', 'http://www.gutenberg.org/files/1400/1400-0.txt', 886, 886 + 500)]

    for book in books:
        print book
        print book.tokens

I commented out the words, words2tokens and pos attributes as they are not currently needed.

Alternatively, if you don't want to insist on the delayed getting of the values, you can do it all already in the constructor:

class Book(object):
    def __init__(self, title, url, start=0, end=-1):
        self.title = title
        self.url = url
        self.start = start
        self.end = end
        self.raw = self.get_raw(url)
        self.tokens = nltk.word_tokenize(self.raw)
        # self.words = None
        # self.words2tokens = None
        # self.pos = None

    def __str__(self):
        return self.title

    def get_raw(self, url):
        response = request.urlopen(url)
        draft = response.read().decode('utf8')
        return draft[self.start:self.end]

Which you can use exactly the same way.


How to make a loop of nested if-statements to find the smallest number of something?

I'm not sure what your code is doing. As it currently stands, it will print the first number that satisfies the requirement of being composed of various parts, all divisible by 5 with a remainder of 1.
If that is your objective, then you should certainly compute the number as an equation: (0*5)+1 *5 ... etc.
If you are working up to determining whether any given number meets the condition, then you can certainly continue as you are doing.
Here are some tips to improve your efficiency and clarity:

Get rid of the continue at the bottom of the loop. It is not needed.

Get rid of the various statements getal = getal + 1 in your else branches. By inspection, I can see that this adjustment is always done whenever you loop (since you sys.exit() on success) so just move the statement to the top of the loop, and adjust your incoming variable:
 getal -= 1
 while True:
     getal += 1
     # many, many if statements

Perform your multiplication as part of your adjustment to getal, not as a separate part of your if statements:
 a = ((getal - 1) / 5) * 4
 if a % 5 == 1:

Consider negating your tests. Instead of looking for "good" values, look for "bad" values. Because you are testing for "failure," and because the response to failure is to jump away (continue), you can replace nesting with a series of tests at the same level:
 if a % 5 != 1:
     continue
 b = ...
 if b % 5 != 1:
     continue
 c = ...
 if c % 5 != 1:
     continue


I don't know redux at all, so I might have missed something important so that my suggestion may be naive and doesn't work.
If so, my apologies, and don't shoot me too hard :)

That said, here is how I'd work:

first add a registry for the currently added langs
then merely use the right one depending on action.locale if it exists in registry, or keep initialState if not

Actually it results in something like this:

import { FRENCH } from '../../public/messages/fr';
import { ENGLISH } from '../../public/messages/en';

const initialState = {
  lang: FRENCH.lang,
  messages: FRENCH.messages
};
const langs = {
  fr: FRENCH,
  en: ENGLISH
}

export const localeReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'LOCALE_SELECTED':
      if (langs[action.locale]) {
        return {
          ...initialState,
          lang: langs[action.locale].lang,
          messages: langs[action.locale].messages
        };
      }
    default:
      return state;
  }
};


Cleaning up nested promises in Cloud function

I'd start with refactoring the promises functions and remove any code repetition, something like this:

...

function success(object){
    // success
}
function error(error){
    return response.error(error);
}
...

query.find().then(function(array){
    if(array) {
        // found at least one object - take the first
        parseObject = array[0];
        parseObject.set(dataObject);
     } else {
        // nothing found - create new
        parseObject = new Class(dataObject);
     }
     parseObject.save().then(success,error);
});
...


Iterating through two objects with different structures in parallel

You don't need the count variable to increment the index, Array.forEach accepts a second ( optional ) parameter which is the current index that you can use :

stored.forEach((obj, index) => {
   obj.value = input[index];
});

OR

stored = stored.map((obj, index) => ({...obj, value: input[index]}))

example :

let stored = [{ name : 'a', value: 2 }, {name : 'b',  value: 4 }, { name : 'c',  value: 6 }];
let input = [10, 11, 12];

stored.forEach((obj, index) => { obj.value = input[index]; });

// OR
// stored = stored.map((obj, index) => ({...obj, value: input[index]}))

console.log(stored)


Not used variables

I don't think this variable is used:

private static int interval;

Method

If you want to type the text without having to do each letter at a time, I'd use a Map to keep track of what code relates to each letter. Something like:

  // earlier on in your class, set up the map
   private static Map<Character,Integer> charMap;

   static {
      charMap = new HashMap<Character,Integer>();
      charMap.put( ' ', 32 );
      charMap.put( 'a', 65 );
      charMap.put( 'b', 66 );
      charMap.put( 'c', 67 );
      charMap.put( 'd', 68 );
      charMap.put( 'e', 69 );
      charMap.put( 'f', 70 );

      // ... and so on until ...
      charMap.put( '0', 48 );
   }

   // now define the method to use it
   public static void sendText(String aa) {

      for ( int i = 0; i < aa.length(); i++ ) {
         robot.keyPress( charMap.get( aa.charAt( i ) ) );
      }
   }

Exception Handling

In the case of creating a Robot, if you get an AWTException as you have, remember that this means no Robot was created so you can't rely on it later.
Remember also to show the exception description. Typing "error" or "unknown error" isn't so fair for me, you can easily get the description of the exception.


I have been though this loop before. I chose to do things in a slightly different way to you, in that instead of creating a Runnable, I instead add a try/catch block to the actual test.

Each system has pros/cons, but the differences are really cosmetic. Using a Runnable does make the JUnit logic better contained in the utility code.... but makes calling the utility test code a little bit more complicated. I am not sure which one I prefer.

I have a suggestion regarding this line here:

if (!exceptionClass.equals(e.getClass())) { ....

It is useful to be able to expect a super-type of an exception. For example, you want to trap an SQLException when you run a query, or you want to trap an IOException when you do something on a Stream..... you have the code:

TestingUtils.assertExpectedException(SQLException.class, ....);

but, the actual exception may be com.ibm.db2.jdbc.xxx.PicnicException, which is a subclass of SQLException.

Using equals() to match the exceptions is a problem.... you should use:

if (!exceptionClass.isInstance(e)) {....

One other thing, which is android specific.....

I found a bug in the Android Dalvik implementation/SDK relating to this problem... you should be setting the 'cause' for your AssertionError so that it is logged correctly. Unfortunately, the bug (which is fixed in Jelly-Bean) makes this impossible.

If you are sure you will be testing on Jelly-Bean or newer (the bug was fixed a while ago), you should also be initializing the cause on your AssertionError:

            AssertionFailedError tothrow = new AssertionFailedError(
                    "Expected exception: <" + exceptionClass.getName() + "> " +
                    "but was: <" + e.getClass().getName() + ">"
            );
            tothrow.initCause(e);
            throw tothrow;


Can't give you any pointers towards readibility; seems like you're doing all you can for that within the character/space limits.

As for the code: I see you reset the ACC twice. From Middle Left:

MOV 0, ACC
MOV UP, ACC

And again in the top right one. This is wasting precious cycles. You don't have to set ACC to 0 if you're writing in from a port in the next instruction. If I disable those, I get your program down to 407 cycles.

But by far the greatest improvement can be made by leveraging the TIS-100's parallel processing power! Try moving the addidion logic down to the bottom row, make the top-most block send its accumulator down only once and use the middle block to double the signal. This kills 1 cycle on the input pipe and this adds up to 30 cycles over all the input values combined. Doing ths as well with the 1/0 you send down the right path will save 30 c again. I got you down to 264 cycles this way!

Have fun trying this out.


Knapsack problem with duplicate elements

table is a meaningless name for an important data structure. It should be explained by a comment at least.
W and w look similar enough to cause confusion.
Instead of using enumerate, you could iterate over zip(weight, cost) and avoid indexing.
The max builtin function is convenient for computing a maximum. The inner for loop can be converted to a generator expression for max to process. However, max raises an error if there are no items to process. In recent versions of Python a default value can be given to max to avoid that.

My rewrite for Python 3.4 or later (I see you are using Python 2.x):

def knapsack(W, weights, costs):
    '''Given weights and costs of items, compute maximum cost for total
    allowed weight W when any item can be picked any number of times.
    '''
    best = [0] # best[x] is the max cost for allowed weight x
    for capacity in range(1, W + 1):
        best.append(max((cost + best[capacity - weight]
                         for weight, cost in zip(weights, costs)
                         if weight <= capacity),
                        default=0))
    return best[W]


Refactor Ruby method for getting domain?

Use URI::parse:

require 'uri'
URI.parse("http://gist.github.com/a/b/c").host.sub(/^www\./, '')
#=> "gist.github.com"


A scala implementation of the Java trim method

No good idea about the concern of reversing the list twice. But you may

Let you inner function return a List instead of a string thus having less conversions from list to string and string to list.
Change your match to the following pattern (not tested):

case " " :: tail => removePreString(tail)
case _ => _

I just realize you could also use on a list def dropWhile(p: (A) ⇒ Boolean): List[A] which drops longest prefix of elements that satisfy a predicate. You could then chain dropWhile not a space | reverse | dropwhile not a space | reverse...


A simple program which returns specific value from array

am I doing it right or wrong?

You are mostly right. This is a very common pattern but your naming is a little bit different to standard implementations. I should note that in this particular case, this is completely overkill but I'm assuming that this is a learning exercise for you and not something you are planning on using.

public interface IArrayPerformer
{
    int GetAnswer(int[]arr);
}

IArrayPerformer is a bad name because it's very general and it reveals the implementation details. The interface could be made more general by working on an IEnumerable<int> which is the more general interface for a sequence of numbers.

public interface INumberSequenceOperation
{
    int GetAnswer(IEnumerable<int> numbers);
}

Naming this is pretty tough - you'd probably need several attempts to get something good.

Your ActionChooser is normally referred to as a Factory.

public class NumberSequenceOperationFactory
{
    public INumberSequenceOperation CreateOperation(MathAction mathAction)
    {
        // ...
    }
}

I would remove your Math class entirely. It also violates the D in SOLID because it depends on your chooser directly.

static void Main()
{
    var numbers = new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    var factory = new NumberSequenceOperationFactory();
    var operation = factory.CreateOperation(MathAction.LowestNumber);
    var lowestNumber = operation.GetAnswer(numbers);
    Console.WriteLine(lowestNumber);
    Console.ReadKey();
}

As another answer has said while I was typing - LINQ gives you most of what you need out of the box and extension methods fit very nicely here.

Update

How does the Math class violate the dependency inversion principle?

Here is the Wikipedia definition of the dependency inversion principle (emphasis is mine):

  A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  B. Abstractions should not depend on details. Details should depend on abstractions.

Your Math class is supposed to be an abstraction but it's depending on the detail directly:

private ActionChooser mathChooser = new ActionChooser();

That ActionChooser is a detail but you're tying Math to it! It should be possible to replace that dependency with a different one if you want. The standard way of doing that is with Dependency Injection. e.g. using Constructor Injection:

// Using your names
public class Math
{
    private readonly ActionChooser chooser;

    public Math(ActionChooser chooser)
    {
        this.chooser = chooser;
    }

    public int ReturnAnswer(MathAction mathAcs, int[]arr)
    {
        return chooser.imath(mathAcs).GetAnswer(arr);
    }
}

In general, you create your entire object graph at your composition root and never create the dependencies again. You can achieve that with "Pure Dependency Injection" (my Main example) or with some kind of Inversion of Control container. There are a lot of these, e.g. StructureMap, Ninject etc.

Learning all of this can be really tough - I'd recommend Mark Seemann's fantastic PluralSight course on Encapsulation and SOLID. If you don't have access to PluralSight and don't want to pay, you can get 3 months free with Dev Essentials. After the 3 months you'll probably decide you want to pay anyway.

Are extension methods bad?

No.

Well, not when they're used properly. There are certainly trade-offs involved in using extension methods but they are extremely effective when used correctly.

Of course, this type of thing is pretty terrible IMO:

// BAD
public static bool IsNullOrWhitespace(this string source)
{
    return string.IsNullOrWhitespace(source);
}

so you can do this:

// Yuck!
string test = null;
test.IsNullOrWhitespace();

Without knowing why you currently believe that they are bad it's difficult for me to make a case for why they're not :)


Node.js/Express middleware to relay requests to various APIs

I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.

I would suggest the NPM Module express-app-generator

The advantages of it include:

Code Management in clean way.
Structured Routing.
Add Multiple Middle-Wares in filters array.
Create CRUD API's with REST or CRUD Keyword.


The method name getProducts looks like a getter. However, there is some logic inside and getters usually don't have arguments. getProducts(Category category) seems a bit suspicious for me.

The name getProductsForCategory(Category category) looks too verbose: category is present three times. Why not calling it getProductsFor(Category category)? There would be no repetition and it is read straightforward.

To avoid the confusion with a getter, I also think that it could be named filterProductsBy(Category category) or retrieveProductsFor(Category category).


Code review:

Well, your code seems ok, it can be improved:

You can replace the letters by string.ascii_letters
You can remove obj since it is not used.
You can format your date using the format method, i.e. ˋ"{0:%Y/%j}".format(date)`.  That way, you can have a directory by year and a subdirectory by day in the year.

Analyze:

Instead of creating an UID and then writing a file, I usually process in reverse order and use tempfile.mkstemp.

  [It] Creates a temporary file in the most secure manner possible…

That way, you avoid collisions. Then, I use the newly created file name as an ID.

You speak about performance: note that the more you have subdirectories, the more you have inodes. This can decrease performance when you want to access the files.

To summarize:

Create a directory for each day using the format "{0:%Y/%j}".format(date)
Create a temporary file in that directory
Use the relative path and the filename to construct your UID. For instance, replace "/" and dots by underscore.

Generating UUID

If, for any reason, you can't rely on the file system temporary files, and you must create an UID yourself, I suggest you to consider using UUIDs (Universally Unique IDentifier).

See the Python module uuid available for Python 2 and 3.

For instance, you can use uudi.uuid1:

  Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.

Example:

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

If you want folders, you only need to replace "-" by "/".


Generating a random number of progress bars

1. Native methods will perform better than jQuery equivalents

Replacing jQuery calls with the native JavaScript equivalents where possible will improve performance. This will also increase the verbosity of your code, which may be undesirable, although arguably it can make the code more readable/less ambiguous.

Examples:

Use document.getElementById('ID') instead of $('#ID') when retrieving a single element by its ID
use document.querySelector('.className') instead of $('.className') when retrieving a single element by a CSS selector
Use document.querySelectorAll('.className') instead of $('.className') when retrieving an array of elements by a CSS selector
Use Element.innerHTML to update the text/html inside an element instead of using $(.cssSelector).html() or $(.cssSelector).text()
If you're only appending HTML to an element, use the more efficient Element.insertAdjacentHTML('beforeend',YourHTML) instead of modifying Element.innerHTML

2. Don't query the DOM for elements any more than you need to

In some cases your code selects an element multiple times. You can improve performance by selecting it once and saving it to a variable, then referencing that variable instead of selecting it again. Otherwise the JavaScript is forced to crawl the DOM multiple times to retrieve the same element.

Examples:

In the runBars() method, $('#bars-container') is called once to clear its HTML content, then again several times (once for every bar) to append more HTML to it. This is causing performance to degrade steeply as the number of bars increases.
Similarly, in the runPercent() method, the array of progress bars is selected via $('.progress-bar') once to get its length, then selected a second time to set the width and text of each progress bar.

3. Include a Radix parameter when calling parseInt()

This one is more of a minor nitpick: when calling parseInt() you should make it a habit to include a radix parameter indicating the base of the number in the string.

Otherwise the browser will do its best to pick the right base system based on the string value... strings that start with '0x' will be considered hexadecimal, while strings that start with '0' will be considered octal, and any other strings will be considered decimals.

Making a habit of passing 10 explicitly as your radix parameter will not only save the browser the tiny bit of effort it expends on checking for a string prefix, but it will save you from headaches if you ever find yourself parsing a string with a zero preceding a decimal number.

Example Code

Check out the performance of the code below, which has no jQuery dependencies except for the progress bar CSS:

/*Creates a random amount of bars*/

function runBars() {
    var start = new Date().getTime();
    /*Sets the maximuim amount of bars, 10 if NaN or less than 1*/
    var max_bars = parseInt(document.getElementById('max_bars').value, 10);
    if (isNaN(max_bars) || max_bars < 1) {
        max_bars = 10;
    }
    /*Grabs a random number of bars*/
    var bars = getRandom(max_bars);
    /*clears bars container*/
    var container = document.getElementById('bars-container');
    container.innerHTML = '';
    /*Appends progress bars.*/
    for (var i = 0; i < bars; i++) {
        container.insertAdjacentHTML('beforeEnd', 'Number ' + (i + 1) + '

');
    }
    var end = new Date().getTime();
    var time = end - start;
    document.getElementById('bar_time').innerHTML = time;
    document.getElementById('bar_amount').innerHTML = bars;
    /*Populates bars with percents*/
    runPercent();
}

/*Random int with max*/
function getRandom(max) {
    return Math.floor((Math.random() * max) + 1);
}

/*Gets percent based on maxium number, making the percent scale */
function getPercent(x, total, biggest) {
    return Math.floor(x / biggest * 100) + '%';
}

/*Populates percent in each progress bar*/
function runPercent() {
    var start = new Date().getTime();
    var progressBars = document.querySelectorAll(".progress-bar");
    var data = [];
    var total = 0;
    var biggest = 0;
    /*pushes random ints to array*/
    for (var i = 0; i < progressBars.length; i++) {
        var temp = getRandom(50);
        data.push(temp);
        total += temp;
        if (biggest < temp) {
            biggest = temp;
        }
    }
    /*Each progress bar gets a width percentage and sets the text.*/
    for (var index = 0; index < progressBars.length; index++) {
        progressBars[index].style.width = getPercent(data[index], total, biggest);
        progressBars[index].innerHTML = data[index] + ' / ' + total;
    }
    var end = new Date().getTime();
    var time = end - start;
    document.getElementById('percent_time').innerHTML = time;
}
/*handles button events*/
var btnPercent = document.getElementById("percent");
var btnBars = document.getElementById("bars");
if (btnPercent.addEventListener) {
    btnPercent.addEventListener("click", runPercent);
    btnBars.addEventListener("click", runBars);
} else {
    btnPercent.attachEvent("onclick", runPercent);
    btnBars.attachEvent("onclick", runBars);
}

/*initiates on page load*/
runBars();
.float {
  position: fixed;
  right: 0px;
  text-align: right;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

  <button id='percent'>Randomize %</button>
  <button id='bars'>Randomize Bars</button>

  <input id='max_bars' type='number' placeholder='Max Number of Bars' />

Result:

Amount of Bars:

In Miliseconds:

Bar Time:
Percent Time:


Won't this work too?

string name = "lltt";
int uniqueCharacterCount = name.Distinct().Count();

will return 2


Listing all possible names from a phone number

Without the link, I can only make certain assumptions, so I am going to give a couple of global comments:

When checking if something is contained in a dictionary, you each time read the file again. Second, you can linearly through it in order to determine if a name is contained in it or not. This is very, very slow. Is this because you have some memory constraints? Because else, it would be much faster to read it at the start, and use a HashSet to check for existence.
Should you be able to read the whole file in memory, perhaps you could even create a mapping between the names and the key combinations that make up this name, by precalculating this. I think that would be a rather optimal solution?
genPermutations does not work. You pass a depth, which is basically a key index, and generate all permutations from that key until the final key. If you nevertheless keep and fix the genPermutations method, you have another point which can be improved. As I commented earlier, if you would look at the generated results, you could notice a lot of duplication. Take your 4734 example, which among other things generates GPDG, HPDGand IPDG. The three strings are equal except for the first letter. This means you are calculating a lot of the same things. This could be cached.

Some minor remarks:

Class names should be uppercase (or better, CamelCase), e.g. NameNum
Variables should start with a lowercase, so List<List<Character>> lists = new ArrayList<>();
Do not use reference equality with Strings, instead use the equals method. You might get unexpected results otherwise.


Instead of checking if the parse succeeded and then unwrapping the result in two steps, you can combine the operations by using pattern matching instead. Here, an if let expression will do the job.

if let Ok(n) = num {
    // use `n` here
}

I also have some suggestions concerning style, based on the prevailing style in the community:

Don't put a space between an identifier and the colon that precedes a type (message: &str rather than message : &str).
Put the } and the else on the same line.

Additionally, considering the way you've written the prompt messages, it looks like there shouldn't be a newline after the prompt, so I suggest you change the println! that prints the prompt to a print!.

Here's the revised code:

use std::io;

fn read_time(message: &str, max: u64) -> u64 {
    let mut input = String::new();

    loop {
        print!("{}", message);
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let num = input.trim().parse::<u64>();

        if let Ok(n) = num {
            if n < max {
                return n;
            } else {
                println!("exceeded max value of {}", max - 1);
            }
        } else {
            println!("Need a number above 0 and less than {}", max);
        }
    }
}

fn main() {
    println!("Waiting Sample Program");

    let hours = read_time("Enter hours: ", 24);
    let minutes = read_time("Enter minutes: ", 100);
    let wait = hours * 60 + minutes;

    println!("Going to wait {} minutes", wait);

    std::thread::sleep(std::time::Duration::new(wait * 60, 0));

    println!("done.");
}

If you want to combine the result of parse with the range checking in a single operation, that's possible too. First, let's look at the "lazy" way, where both error situations will produce the same error message:

fn read_time(message: &str, max: u64) -> u64 {
    let mut input = String::new();

    loop {
        print!("{}", message);
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let num = input.trim().parse::<u64>();

        if let Some(n) = num.ok().and_then(|n| if n < max { Some(n) } else { None }) {
            return n;
        }

        println!("Need a number above 0 and less than {}", max);
    }
}

Here, I'm using ok to convert the Result to an Option, because I'm too lazy to define an error type that unifies the parse error and our new out-of-range condition. Then I'm using and_then to perform the range validation only if the parse succeeded. The closure returns Some(n) if the value is in range, or None if the value is out of range.

Instead of using and_then, we could also use the filter method provided by the option-filter crate. It takes a closure that returns a bool, and returns None if the closures returned false, or the original value otherwise.

if let Some(n) = num.ok().filter(|n| n < max) {
    return n;
}

And now, let's not be lazy and code this up properly. We'll need to introduce a type that can represent either a parse error, or an out-of-range condition.

use std::num::ParseIntError;

enum ReadTimeError {
    ParseError(ParseIntError),
    ValueOutOfRange,
}

impl From<ParseIntError> for ReadTimeError {
    fn from(e: ParseIntError) -> Self {
        ReadTimeError::ParseError(e)
    }
}

fn read_time(message: &str, max: u64) -> u64 {
    let mut input = String::new();
    let check_in_range =
        |n| if n < max { Ok(n) } else { Err(ReadTimeError::ValueOutOfRange) };

    loop {
        print!("{}", message);
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let num = input.trim().parse::<u64>();

        match num.map_err(ReadTimeError::from).and_then(check_in_range) {
            Ok(n) => return n,
            Err(ReadTimeError::ParseError(..)) => {
                println!("Need a number above 0 and less than {}", max);
            }
            Err(ReadTimeError::ValueOutOfRange) => {
                println!("exceeded max value of {}", max - 1);
            }
        }
    }
}

Here, we have three cases to handle, so I'm using a match expression rather than an if let expression. I'm taking advantage of the fact that patterns can match "deeply" to match on two levels of enums at the same time. Result also has an and_then method, and naturally, the closure must return a Result. I moved the closure out of line to keep the expression being matched on short enough.

Now, it's up to you to decide whether combining the two validations is worth the additional complexity or not! :)


Solving Project Euler problem #48 in Scala

Your solution is clean but doesn't scale well. A well known optimization for a^k mod m is to perform all computations modulus m. If m is sufficiently small, we furthermore can switch to native types (this is not the case here !).

val n = 1000
val m = BigInt(10).pow(10)
(for (i <- 1 to n) yield BigInt(i).modPow(i,m)).sum % m

Rounded avarage timing results (Scala 2.9.1 with -optimize) :

n                     1000     | 10000
Initial solution       4.8 ms  |  6700 ms
Fold left              4.8 ms  |  6700 ms
My humble version      0.5 ms  |     5 ms