At first glance, you code appears to have a lot of complicated and repetitive sections.  That's a bad smell, and often a hint that you should either split the repetitive parts off into a function or otherwise reorganize your code to get rid of the repetition.  (Sometimes, one option can be to just simplify the code until the repetitive parts become trivial.)

A lot of the complexity in the repetitive parts of your code seems to come from your decision to store the grid as a dictionary of dictionaries.  There's a couple of ways to simplify that:

In Python, dictionary keys can be tuples.  So you can just do:

visited = {}
# ...
if (row, col) not in visited:
    # do something
    visited[row, col] = True
else:
    # do something else

(Also, you shouldn't name your dictionary dict, both because it's the name of the dictionary type in Python and also because it's an uninformative name that doesn't explain what you're using the dictionary for.  Call its something meaningful like visited_cells or just visited instead.)
Also, since you're really only using the dictionary as a set, why not make it one?  The code can look exactly the same as above, except that you'll start with visited = set() instead of visited = {}, and mark cells as visited with visited.add((row, col)).
Alternatively, instead of using a dictionary or a set, you could just use a two-dimensional array (implemented e.g. as a list of lists) of booleans, initialized to all False, something like this:

visited = [[False] * cols for row in range(rows)]
# ...
if not visited[row][col]:
    # do something
    visited[row][col] = True
else:
    # do something else

I suspect this is what the exercise is actually expecting you to do.  However, I do rather like your idea of using a dictionary (or a set) instead, and I'm only mentioning this alternative for the sake of completeness.

One advantage of using a dictionary or a set to store the visited cells is that it means you don't actually need to care about the boundaries of the grid, since the dictionary can accommodate arbitrary large or small coordinates.  In particular, you don't actually need to adjust the input coordinates from one-based to zero-based indexing (and back again for output), so you can just eliminate those parts of your code.

Another way to reduce the repetitiveness of your code is to observe that all the sections for handling movement in different directions look basically the same, except for the index (row or column) being changed and the step size (+1 or -1) it's being changed by.  If you defined a dictionary that mapped the N/S/E/W direction letters to the corresponding coordinate offsets, something like this:

directions = {
    'N': (-1, 0),
    'S': (+1, 0),
    'W': (0, -1),
    'E': (0, +1),
}

then you could combine all those sections into a single one, something like this:

row = start_row
col = start_col
visited = {(row, col)}  # loop below assumes current square is always marked as visited

for compass_heading in instructions:
    row_step, col_step = directions[compass_heading]

    while (row, col) in visited:
        row += row_step
        col += col_step

    visited.add((row, col))

(Note that I renamed a few of your variables here.  You should not use variables named startRow and startCol to store the current row and column, since that's just plain misleading, and in any case variable names in Python should be written in snake_case instead of camelCase.  And a is just an awful variable name, so I renamed it to instructions.  You already have a variable named that, but it's completely unnecessary and unused.  You could just use the dummy variable _ in the list assignment instead.)

As for making the code faster, I see no obvious trivial opportunities there.  Using a single set instead of a dictionary of dictionaries is probably somewhat faster, perhaps even twice as fast if your running time is dominated by dictionary lookups, but not orders of magnitude faster.  A list of lists of booleans might be even faster for small grids, but the time to initialize it scales with the size of the grid, whereas the time to set up a single-element set (or dictionary) is basically constant.  Anyway, I'd suggest first focusing on cleaning up your code, and only worrying about optimization if it's still too slow after that.

If it is, a good starting point is to focus on worst-case performance, i.e. to think about how a sneaky test case designed might make your code run as slowly as possible, and try to find ways to counter that.

In particular, the worst case input for your algorithm (with or without the improvements I suggested above) is something like NSNSNSNSNSNSNSNSNSNSNSNSNS..., which forces the robot to move back and forth over an increasingly long stretch of visited cells, leading to an O(n²) execution time.

One way to avoid that would be to store a dictionary of "signposts" recording, for each move we make, where we ended up on the grid after that move.  That way, the next time the robot finds itself in the same square and moving in the same direction, it can skip all the cells in between.  Also, since the movement rules are symmetric, we can also leave behind "backwards" signposts recording where the robot came from as it entered each cell, allowing us to skip the intervening cells in the opposite direction as well.

A quick sketch of how to implement that might look something like this:

# look-up table of (row_step, col_step, opposite_heading) for each compass heading
directions = {
    'N': (-1, 0, 'S'),
    'S': (+1, 0, 'N'),
    'W': (0, -1, 'E'),
    'E': (0, +1, 'W'),
}

row = start_row
col = start_col
visited = {(row, col)}  # loop below assumes current square is always marked as visited
signposts = {}

for compass_heading in instructions:
    last_row = row
    last_col = col
    row_step, col_step, opposite_heading = directions[compass_heading]

    while (row, col) in visited:
        if (row, col, compass_heading) in signposts:
            # we've been this way before!
            row, col = signposts[row, col, compass_heading]
        row += row_step
        col += col_step

    visited.add((row, col))

    signposts[last_row, last_col, compass_heading] = (row, col)
    signposts[row, col, opposite_heading] = (last_row, last_col)

Note that, as written, the signposts dictionary always grows linearly with the size of the input.  You may obtain some additional speed and memory savings by removing old signposts as they become unnecessary.

In particular, we can safely remove any signposts we encounter as soon as we've used them, since they will either become useless or get overwritten anyway.  We can also safely remove any backwards signposts that we pass, since those also become useless.  With those changes, the optimized inner loop would look something like this:

    while (row, col) in visited:
        if (row, col, compass_heading) in signposts:
            # follow and remove signposts; any that are still valid will be restored below
            row, col = signposts.pop((row, col, compass_heading))
            del signposts[row, col, opposite_heading]
        row += row_step
        col += col_step

However, note that the set of visited cells will still grow linearly, and that meandering paths like, say, NESWNESWNESWNESWNESW... can still leave behind a linearly growing number of signposts, so the worst-case memory consumption is still linear even with this optimization.

Ps. Here's a simple online demo of the signpost-optimized algorithm I describe above, with some debug print statements added.  Feel free to play around with it to see how it works.


find if a number divisible by the input numbers

You really need to make your code easier to read, and more consistant.

I highly advise you learn all of PEP8 and follow it, so that your fellow Python developers can read your code with ease. And not cringe when you start using one and three spaces as indentation.
I highly advise you get one of the linters avaliable for Python.
Use functions, they help people know the scope of your code. I don't need to know about count and j when getting input.
Rather than using list(map(fn, it)) you can use a list comprehension, [fn(i) for i in it]. This is generally the prefered way.
Use sugar when provided, j=j+1, looks like a mess. Applying PEP8 would change it to j = j + 1, but you can always use +=, to get j += 1. Reducing the amount we need to read.
There's no need for one of your else's. If you have if ...: ... a += 1 else: a += 1, then you can remove the else and move the a += 1 to run either way.
It's advised to use gaurd statements, rather than follow the arrow anti-pattern. if count<=inp[2] : could be inverted, followed with the break, and the rest of the code doesn't have another indentation level.

In all I'd highly advise changing your code to something like the following:

def get_nth_multiple(a, b, limit):
    count = 1
    j = 1
    while True:
        if count > limit:
            break

        k=j
        if j%a == 0 or j%b == 0:
            count += 1
        j += 1
    return k

test_case = int(input())
if 1<= test_case <= 100000:
    for _ in range(int(test_case)):
        a, b, limit = [int(i) for i in input().split()]
        if 1 <= a <= 10000 and 1 <= b <= 10000:
            print(get_nth_multiple(a, b, limit))
        else:
            break

This is good, however, I'm not sold on the if statements outside the function. I personally would just remove them, as they're not needed.

I'd also change get_nth_multiple. Say you were asked to get the tenth multiple of five, you'd just do \$5 * 10 = 50\$. However you could make a function that returns all multiples of five, and only take the tenth. Something like next(islice(count(5, 5), 10 - 1, None)). And so, you only really need to merge two count(n, n)'s together to make one list, which you can then take the wanted multiple from.

This should sound simple, however, you also have to account for the fact that count is an iterator, not an iterable. And so you have to make a 'peek' list, that contains the next values of a and b. Which can be implemened as:

from itertools import count, islice

def get_multiples(*nums):
    sources = [count(i, i) for i in nums]
    peek = [next(source) for source in sources]
    while True:
        num = min(peek)
        yield num
        peek = [
            next(source) if i == num else i
            for i, source in zip(peek, sources)
        ]

def get_nth_multiple(a, b, limit):
    return islice(get_multiples(a, b), limit - 1, None)

test_case = int(input())
for _ in range(int(test_case)):
    a, b, limit = [int(i) for i in input().split()]
    print(get_nth_multiple(a, b, limit))


EmptyBST.min

Since min can only return type T, EmptyBST.min has to throw an exception.  There is no logical alternative.

You could consider also implementing minOption: Option[T], which gives the caller more flexibility. Then EmptyBST.minOption would return None.

Tail recursion

None of your methods are tail recursive - not even the simple ones min and search.  You can test this by placing @annotation.tailrec before any of them. The compiler will give an error.

min and search

These cannot be tail recursive, even though the calls to l.min or left.search/right.search seem to be in tail positions. Class methods (as opposed to object methods - functions, in other words) have to be final or private and have to call themselves, not - as you are doing - a superclass method.

For these two methods, this can be solved simply.  One way is to use a while loop and a var to descend the branch (this is how many methods in the collections library do it).  Another is to use an internal helper function like this (for NonEmptyBST.min):

def min : T = {
  @annotation.tailrec
  def go(node: NonEmptyBST[T]): T = node.left match {
    case EmptyBST() => value
    case l: NonEmptyBST[T] => go(l)
  }
  go(this)
}

search can be fixed in the same fashion.

Updating the tree safely

Removals and insertions are much harder to do safely (that is, without risking stack overflow) in a functional, immutable tree. It is much easier in a mutable tree, where an insertion will only modify one node.  In an immutable tree, the final node and each node back down the path has to be modified.

The best way I know to do this is with a zipper.  Zippers allow you to navigate the tree with a minimum of copying to the point where the modification should be made.  Once that is done, the tree can be reconstructed from the zipper (again with a minimum of copying).  I could write a zipper implementation here but as it happens this set of slides begins with a description of how to write one for a binary tree like yours. You can stop once you get to "A Zipper Complete" - that shows you enough for this problem.

If you are still struggling after reading the slides, let me know and I will update this answer.

Easier building

For building a BST from a given set of values, it would be useful for you to modify your apply method to take a sequence of values of type T as input.  That would allow you to create a BST from a list in one concise line of code.


Your braces do not follow the Standard Java Conventions. The standard way is:

public BinaryTree(E data, BinaryTree<E> leftNode, BinaryTree<E> rightNode) {
    this.data = data;
    this.leftNode = leftNode;
    this.rightNode = rightNode;
}

Notice the movement of the braces.

You should have a constructor for your BinaryTree that takes no parameters and one that takes only the data:

public BinaryTree() {

}

public BinaryTree(E data) {
    this.data = data;
}

public BinaryTree(E data, BinaryTree<E> leftNode, BinaryTree<E> rightNode) {
    this.data = data;
    this.leftNode = leftNode;
    this.rightNode = rightNode;
}

This way, programmers using it has a choice of being able to give less information, and add it later through the set() methods. Also, this allows them to prevent them from doing stuff like:

BinaryTree<Integer> tree = new BinaryTree<Integer>(null, null, null);

After all, who wants to do that?

I don't see any point in making a separate class for finding the deepest node int the tree. Why not just put it under one class?

There is a better way to do it with recursion:

public BinaryTree<E> getDeepestNode(BinaryTree<E> rootNode) {
    if (rootNode.leftNode.isLeafNode() && rootNode.rightNode.isLeafNode()) {
        return rootNode;
    }
    return getDeepestNode(rootNode.getLeftNode(), 0) > getDeepestNode(
            rootNode.getRightNode(), 0) ? getDeepestNode(rootNode
            .getLeftNode()) : getDeepestNode(rootNode.getRightNode());
}

private int getDeepestNode(BinaryTree<E> rootNode, int depth) {
    if (rootNode.leftNode.isLeafNode() && rootNode.rightNode.isLeafNode()) {
        return depth + 1;
    }
    return getDeepestNode(rootNode, depth + 1);
}

I know you wanted it without recursion, but I only came up with a solution by using recursion. If you really don't want to use recursion, then your code is fine.


Make querySelector in kotlin-js more convenient and type-safe

"Would be cool somehow, to "default" base type to Element if none is specified, but can't think of way to do that." Indeed it is not possible to do that, at least not with the same method. An option could be to have a separate method for that. document.queryHtmlSelectorRaw ? Or wait, actually... That leaves you back to what you were starting with, Element.querySelector.

  I'd like something, that can pretty much replace original function and just add benefits of stronger typing and nicer error message. Any hints on how to improve this are greatly appreciated.

Given those requirements, I'd say that the current methods is about as good as you're gonna get. You have the stronger typing (but you will have to specify it). You have the better error message if it's null.

The only things that I would consider are:

Get rid of reified, I'm not convinced that you need it.
Change method names, queryHtmlSelector can easily be confused with the built in querySelector. May I recommend just the name selector or select?
Improve the error message even further, such as No element found using selector '$selector' on $this.


Delete all instances of "b" or "ac" from a string

As best I can tell (with the limited info available on the language), it looks like you're violating just a couple language concerns.

First: all example SNOBOL4 code I've seen has the lines without labels indented past the horizontal extent of the longest label by at least 2 spaces. That is:

    input_string = input
del_loop input_string ("b" | "ac") =     : s(del_loop)
    output = input_string

Seems to be expected to be:

          input_string = input
del_loop  input_string ("b" | "ac") =     : s(del_loop)
          output = input_string

It also looks like SNOBOL4 labels are expected to be SHOUTYLABELS:

         input_string = input
DELLOOP  input_string ("b" | "ac") =     : s(DELLOOP)
         output = input_string

The next thing I seem to have seen is that output, input, and s are supposed to be SHOUTY.

         input_string = INPUT
DELLOOP  input_string ("b" | "ac") =     : S(DELLOOP)
         OUTPUT = input_string

The next comment is that it looks like SNOBOL4 code uses PascalCase subject (variable) names.

         InputString = INPUT
DELLOOP  InputString ("b" | "ac") =     : S(DELLOOP)
         OUTPUT = InputString

Next, it looks like the colons should line up vertically and be past the last horizontal character on any line. This doesn't apply to you, unless we include your comments:

         * read a string from standard input
         InputString = INPUT

* find "b" or "ac" in s, replace with nothing, and repeat if successful:
DELLOOP  InputString ("b" | "ac") =                                       : S(DELLOOP)

         * write out resulting string
         OUTPUT = InputString

Lastly, it looks like the transfer is supposed to directly follow the colon. (No spaces.)

         InputString = INPUT
DELLOOP  InputString ("b" | "ac") =     :S(DELLOOP)
         OUTPUT = InputString

Now, that looks like SNOBOL4. :) All-in-all, it looks quite good. Very nice to see an application of a very old language, that shows that sometimes the new ones just aren't the best suited for the task. (In fact, SNOBOL4 was designed to fulfill programmes with this in mind, it was designed to handle pattern-matching and string-processing very well.)


I would definitely rename onlyOwnerCanChangePermissions, maybe to permissive or restrictPermissions or something like that.

I would also definitely remove item.ownerId, create a new RoleType owner and propagate an itemShare entry. I also think that itemShare is a rather bad name and should be renamed to something like permission or accessList.

Get rid of item.publicRoleType and use itemShare instead. This could also simplify your code e.g. you only have to check itemShare for the access. But i would use an AnonymousUser instead of making the emailAddresse nullable.

I think a better name for sharingRoletype would be just roleType as a role is not necessarily related to sharing.

item.visibilityType doesn't really fit into itemShare as itemShare defines permissions (what and who could do what with the document) for users. But you could create a SystemUser and merge visibilityType and sharingRoleType but this isn't a good fit either.


Generate a large block diagonal covariance matrix with exponential decay

JJ <- (alpha - 1) %% nrows + 1
    II <- ((alpha - JJ)/ncols) + 1

That looks likely to be buggy. I would guess that a is supposed to be an encoding for a pair (row, col), but in that case the same base should be used for the %% and the /.

I would also suggest that if you can't use 0-indexed matrices then you do the offset to 1-based when you access the matrices, and keep the values you manipulate 0-based. See how much simpler this is:

for (rowa in 0:(nrows-1))
{
  for (cola in 0:(ncols-1))
  {
    a = rowa * ncols + cola
    for (rowb in 0:(nrows-1))
    {
      for (colb in 0:(ncols-1))
      {
        b = rowb * ncols + colb
        d = sqrt((rowa - rowb)^2 + (cola - colb)^2)
        Q[a+1, b+1] <- Qvariance * (Qrho^d)
      }
    }
  }
}

Incidentally, since Qvariance is multiplied into every single element you could pull that out and post-multiply the final \$48 \times 48\$ matrix instead.

Now, elimination of the matrix. We have \$(AB)_{i,j} = \sum_k A_{i,k} B_{k,j}\$, so $$(HQH^T)_{i,j} = \sum_k H_{i,k}(QH^T)_{k,j} = \sum_k H_{i,k} \sum_l Q_{k,l} H^T_{l,j} = \sum_k \sum_l H_{i,k} H_{j,l} Q_{k,l}$$ which allows you to restructure the code so as to avoid creating \$Q\$ in memory. However, it is at the cost of using the naïve algorithm for matrix multiplication, and your matrices are large enough that R is probably using a sub-cubic algorithm. So what you might want to do is to instead break it down into chunks: e.g. of size nrows \$\times\$ nrows. I don't know enough R to be certain, but I expect that its index range notation allows you to do this quite cleanly.

Following up on some comments, we can expand \$k = r_1 C + c_1\$, \$l = r_2 C + c_2\$ where \$C\$ is ncols, and get
$$(HQH^T)_{i,j} = \sum_{r_1} \sum_{c_1} \sum_{r_2} \sum_{c_2} H_{i,r_1 C + c_1} H_{j,r_2 C + c_2} Q_{r_1 C + c_1,r_2 C + c_2} \\
= \sigma \sum_{r_1=1}^R \sum_{r_2=1}^R \sum_{c_1=1}^C \sum_{c_2=1}^C H_{i,r_1 C + c_1} H_{j,r_2 C + c_2} \rho^{\sqrt{(r_1-r_2)^2 + (c_1-c_2)^2}} $$

Let \$Q^{(\delta)}\$ be a symmetric \$C \times C\$ matrix with \$Q^{(\delta)}_{i,j} = \rho^{\sqrt{\delta^2 + (i-j)^2}}\$. Then $$(HQH^T)_{i,j} =  \sigma \sum_{r_1=1}^R \sum_{r_2=1}^R \sum_{c_1=1}^C \sum_{c_2=1}^C H_{i,r_1 C + c_1}  Q^{(|r_1-r_2|)}_{c_1,c_2} H_{j,r_2 C + c_2} \\
HQH^T = \sigma \sum_{r_1=1}^R \sum_{r_2=1}^R H_{1..48,r_1 C .. (r_1+1)C}  Q^{(|r_1-r_2|)} H_{1..48,r_2 C..(r_2+1)C}^T $$

and the sum can be regrouped by \$|r_1 - r_2|\$ to calculate each \$Q^{(\delta)}\$ only once. When calculating \$Q^{(\delta)}\$ you can exploit the symmetry without worrying too much about cache coherence, because the whole of \$Q^{(\delta)}\$ should fit in L2 cache.


Looks good to me, algorithmically and syntactically. What makes you think it's wrong?

Stylistically, there are a few things you could improve:

Don't using namespace std. It's more idiomatic and readable to explicitly qualify std::max, std::cout, etc., and it's not much more typing.
Don't comment out dead code; delete it instead. ;)
tree[layer][pos] = tree[layer][pos] + ...; should be simply
tree[layer][pos] += ...;

And algorithmically, notice that if you start at the top of the tree and work downward, you don't need to store O(Rows²) numbers; you just need to store the previous row's sums, for a total space cost of O(Rows). (And then at the end you have Rows possible answers, and you pick the std::max_element of all of them.)

This might be a Project Euler constraint; but in the Unix/Linux world, it's more traditional to get your input from stdin rather than reading a filename off the command line. (Most utility programs support both, of course. The only one I know of that doesn't is tr.) Combine that with the top-down approach, and you get a nice Unixy stream filter that makes just one single pass over the data.


Closures with validation rules for domain object properties

my two cents :

I think tying validation activation to setters is not really good. What if you never set any value on your object ? It will be considered valid ! And what happens if you set the property more than once ?
Some implementations use external validator objects, which allow more flexibility (validation rules often vary, according to which user requests saving for instance). When you call validate(), you either pass a validator instance or let the object use a default validator. As a side note, coming from Rails / ActiveRecord, I can tell that complex projects often do not turn well when your domain object's lifecycle is so tightly tied to a single validation scheme !
Speaking DDD lingo, some of your problems might be efficiently solved using Value objects. For instance, your Id property could be a value object that has a isValid() method (it would be responsible for its own validation). Wether or not this is a good idea depends on your domain.


I don't know if this is the best method to parse an HTTP request. You probably should have a look into one of the simpler ruby http servers out there to get some ideas. I do know though that you're doing some strange things here:

headers['Heading'] = request.gets.gsub /^"|"$/, ''.chomp

It looks like you're calling the #chomp method on '' here, which doesn't make sense. You really should use parenthesis here:

headers['Heading'] = request.gets.gsub(/^"|"$/, '').chomp

But on the other hand I can't see what the gsub is doing here, you probably can just get rid of it.

method = headers['Heading'].split(' ')[0]

Probably nitpicking but you can make this easier (and a little faster) by using:

method = headers['Heading'][/[^ ]*/]

That translates to: get the substring till the first space character (so no need to create an array here).

line = request.gets.inspect.gsub /^"|"$/, ''

That is really strange, you don't need to "inspect" a string just to parse control characters. You can match control characters with double quoted strings (e.g. "\r\n").

label = line[0..line.index(':')-1]

#get rid of the escape characters
val = line[line.index(':')+1..line.length].tap{|val|val.slice!('\r\n')}.strip

The ruby god weeps. You can make this much simpler (and more efficient) by using a regexp here:

line =~ /(.*?): (.*)/
label = $1
val = $2.strip

Modifying the stream inside #tap is bad style and the #strip removes surrounding whitespace like "\n" and "\r" anyway.

For the loop you can do the most natural thing and just write the break condition in the while condition part:

while (line = request.gets) != "\r\n"
  ...
end


Bugs
Your code does have a problem with the concurrency, and it's a big one.... your buffered channels are not going to be able to complete the system. The issue is the unbuffered resc and errc channels:

resc, errc := make(chan string), make(chan error)

Your code attempts to loop through a million input records, but your concurrency is set relatively low at 1000. After you have looped a thousand times, you have 1000 go-routines all looking to write a result to either the resc or errc channels.... but, because those channels are unbuffered, there needs to be something reading from them before they can be written to...
... but you have to queue up all 1000000 CSV records before you start to read those channels.
Because you never complete the loops (you're blocked writing to the resc channel), you never release a value from the sem either.... thus, you never get to progress in the loop.
Your code is buggy.
A solution would be to put the entire CSV-reading code in to a separate go-routine, so that your can start reading from the resc/errc channels immediately.
struct instead
Instead of having 2 return channels errc and resc, it would be better to return a simple struct:
type dnsLookup struct {
    domain string
    ips    []string
    err    error
}

then you can monitor just a single channel, and can also correlate any results to a name in a better way, and also correlate an error better too.
Concurrency
The use of the sem channel is OK for concurrency, but for a job like this I would instead defer to having a more discrete mechanism. Have a channel that you push domain names on to from the CSV parser, and then have X number of concurrent go-routines reading from that. Closing the channel indicates no-more-data to process. Use wait-groups to monitor completion....
func lookupRoutine(source <-chan string, wg *sync.Waitgroup, results chan dnsLookup) {
    defer wg.Done()
    for name := range source {
        results <- lookup(name)
    }
}

The above loop will process any/all available names from the source (until it is closed), and will then send values to the results channel.
Then, in your main loop, you can have a channel to send CSV parse results to:
names := make(chan string, 1000)
results := make(chan dnsLookup, 1000)

// parse names in a goroutine
go parseCSVData(csvfile, names)

wg := new(sync.WaitGroup)
wg.Add(concurrency)
for I := 0; i < concurrency; i++ {
    // parallel routine for lookups
    go lookupRoutine(names, wg, results)
}

// close the results when all lookup routines complete:
go func() {
    wg.Wait()
    close(results)
}

for r := range results {
    // print the results out here
    ...
}


Clicking child view and preventing parent view from running dblclick event

I'm not sure what seems convoluted to you. It's a simple piece of code, and if you remove anything from it, it will fail to do what you want, as you noted yourself:

If you remove the debounce, the method will be fired 3 times: once for the single click + twice for the double-click. So you need that.
If you remove the double click handler, then it will be fired in the parent

There is one thing you could "optimize", in the ChildView you could make the dblclick handler do nothing:

var ChildView = Backbone.Marionette.ItemView.extend({
    events: {
        'click': '_addToStream',
        'dblclick': function() {}
    },

This will work, because the dblclick will also trigger click, so _addToStream will be called. You still cannot remove the debounce, because without it the dblclick will trigger 2 click events.

Finally, the ChildView doesn't extend the ParentView, maybe that's a typo, and your real intention was this:

var ChildView = ParentView.extend({


More ergonomic / convenient STL algorithm calls -- sort order & member field extraction using std::invoke

Indeed, your sortby when used in the style shown, with data members, will not be quite as fast as if you used the STL with a lambda. Look at the difference in assembly between

struct Date {
    int year, month, day;
};

void test1(std::array<Date, 100>& a) {
    sortby(a, &Date::month);
    sortby(a, &Date::year);
}

void test2(std::array<Date, 100>& a) {
    sortby(a, [](const auto& x){ return x.month; });
    sortby(a, [](const auto& x){ return x.year; });
}

In test1, the difference between &Date::month and &Date::year is encoded in the runtime value of the member pointer. In test2, the difference is encoded in the compile-time type of the lambda. So test2 instantiates two different template instantiations, whereas test1 calls the same instantiation twice with different inputs. (But if both calls are inlined, the optimizer might be able to hide the difference.)

However, this is not the fault of your sortby helper; it's the fault of using member pointers instead of custom lambdas. You can observe the same differences happening if you call std::sort with a function pointer, versus calling std::sort with an instance of some bespoke type such as std::less<> or std::greater<>.

You pass Member&& m by forwarding reference, but then you use it as an lvalue (without forwarding it again). I think I've mentioned before: if you don't intend to forward an argument, then you shouldn't be using a forwarding reference with it. In this case, you just need to look at the value of the member-pointer m without modifying it, so const Member& m would be appropriate. Or, since member data pointers and custom lambdas are both going to be small trivial types, and member function pointers are also trivial types (if slightly larger), we should seriously think about taking Member m directly by value.

Notice that you already take Comparison comp by value.

The comment about using std::begin(c) over c.begin() is accurate. If you want your sortby template to work for C-style arrays, then you should use std::begin(c). Remember, you can't pass arrays by value (they decay to pointers) — but you can certainly pass arrays by reference, and that's what you're doing here when you sortby an array "in place."

The vast majority of lambdas you write should just take [&]. I don't see any benefit to writing [&m, &comp] when it ends up meaning the same thing as [&].

So I'd write your helper like this:

template<class Container, class Member, class Comparison = std::less<>>
void sortby(Container& c, Member m, Comparison comp = Comparison()) {
    using std::begin; using std::end;
    std::sort(begin(c), end(c), [&](const auto& a, const auto& b) {
        return comp(std::invoke(m, a), std::invoke(m, b));
    });
}

using std::begin; is the "std::swap two-step," familiar to anyone who's used std::swap before. It means "consider using std::begin for unqualified calls, but if someone has provided a better-matching ADL version of begin, then we'll happily use that version instead." This is certainly overkill — I mean we could just write std::begin(c), std::end(c), — but the two-step is how all the standard customization points are meant to be used as far as I know, so we might as well stick to it.

Vice versa, I would personally shy away from using the two-step in main —

using os::algo::sortby;

This seems more confusing than helpful. Are you expecting that someone else might provide a better-matching ADL sortby? If not, then sortby(x,y,z) will always mean os::algo::sortby(x,y,z)... and if it is os::algo::sortby, why not say so?


Implementation of an Stack without Linked Lists in C

makestack should return a struct stringstack * instead of void *.
malloc and realloc may fail. Check their return values.
push doesn't copy the string (it only makes a redundant copy of the pointer). It is OK as long as you can guarantee that the string parameter has a lifetime long enough. Consider a scenario:

void foo(struct stringstack * stack)
{
    char bar[] = "aaa";
    push(stack, bar);
}

Upon the return, bar disappears, and the stack entry points to the pretty random place in the application stack. Do not expect to have "aaa" there.

To actually copy the string, do

 *(ptr->stack + ptr->count) = strdup(stringtext);

which may introduce other problems in interacting with client (who owns the string after peek?). Unfortunately, C doesn't offer a clean solution.
You may want to shrink the stack when ptr->count hits the low watermark of ptr->slots.


Service Layer, using Entity Framework 6.2

How do you like it?

I don't like it ;-)

Because...

This is a repository and should be named ItemRepository
Unless you can prove (with proper profiler results) that reusing the context has a better performance I wouldn't care about it. Because of this opmization your API gets more complicated and confusing. See Performance Considerations (Entity Framework) Actually you might win more performance by disabling change-tracking than by reusing the context.
The ContextFactory property is public and it has a setter. Why? It's already set via the constructor. Make it either a private field or remove the constructor because a constructor informs me that this value is mandatory. For this class however it's both. Mandatory for creation but it can be set to null after creating the ItemService. This is very confusing.
You don't need any of the helper variables returnedItemStatus or returnedQuantity. Just return the value where you get it.
ItemStatus.New is another confusing thing. If I try to GetItemStatus and it does not exist then I expect it to either throw or return a status that tells me the item actually does not exist. How can it be New if it wasn't found? The same applies to the other method. If the item does not exist I expect either an exception or a -1 for the quantity that informs me that the item does not exist. Saying 0 for something that isn't even there is just wrong. It makes me think it could be or was there but is sold out. So, does a 0 mean you don't offer it at all or it's currently not in stock? 0 is not a very useful result in this case. You should better differentiate both cases.
Here I'm done reviewing your code because you cannot return a single Status from this query .Where(p => p.ItemId == itemId).Status which makes me think this is not your real service...
One last thought... instead of querying each item property at a time with queries like these... why don't you simply get the item or an info-object about it. I would save you a lot of database trips.


Yes, there is a more elegant version. Here it is:

class EquationSolver
  def solve(x, *args)
    args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
  end
end

It's possible to do this because iterator methods like each_with_index, when called without a block, return an Enumerator object on which you can call all the methods of the Enumerable.

In fact, an even shorter solution is obtained by using a variation of reduce to use a symbolic operator:

class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)
  end
end


LINQ query that filters elements from a list of object

You can simply combine the conditions inside the FirstOrDefault() like

PersonResultList = PersonResultList
    .Where(pr => PersonList
                    .FirstOrDefault(p => pr.PersonId == p.PersonId
                                         && p.Gender == "female") != null );

Because I only changed your existing code, it didn't came to my mind what Nikita Brizhak commented here .

  You should probably use Any instead of FirstOrDefault

So let us change the code to

PersonResultList = PersonResultList
        .Where(pr => PersonList
                        .Any(p => pr.PersonId == p.PersonId
                              && p.Gender == "female"));

This is based on the assumption that for each entry in the first list there will be only one entry in the second list.


First of all, I would stop what you're doing. What you're essentially doing is what the new fetch is for. It does an asynchronous HTTP call, and returns a promise. For older browsers, there's a polyfill.

Should you choose to proceed, here's a few things:

I am not sure why http is a function that returns an object that attaches to $hR. A lot of the code is unnecessary. If what you're doing is just exposing $hR as a global and having a bunch of functions on it and maybe a private scope to put stuff in, then the following will do:

;(function(ns){               // 2

  ns.get = function(){...}    // 3

}(this.$hR = this.$hR || {}); // 1

What this code does is:

Uses an existing $hR global or create a new object and assign it as the $hR global.
The global is passed into the closure as ns. ns will represent your global object.
Attach functions to ns. In this case, the get function.

Now for your AJAX code. A cleaner way to define this code is to put everything inside the promise constructor. This way, the promise function just looks like a wrapper.

ns.get = function(url){
  return new Promise(function(resolve, reject){
    // The entire AJAX operation inside here
  });
}

Your xhr handler only checks for state 4. State 4 only indicates the operation succeeded but does not indicate that you encountered HTTP errors like 400 or 500. Additionally, if the xhr did fail, there's no way of knowing from the Promise since you did not do a reject. Check for HTTP success and failure, do a resolve and reject respectively.

if(ajax.readyState === 4 && ajax.status === 200){
  resolve(ajax.responseText);
} else {
  reject(ajax.responseText);
}


Data structure that is fast to read and modify

This looks like a good (i.e. not stupid) implementation if your main requirements is efficient sequential access to the data. Addition and removal will necessarily be slower than for a Dictionary because you are wrapping a dictionary, but the time complexity is of the other work is constant, so it isn't something I would worry about too much if your goal is fast read/modification.

Encapsulation

Generally the encapsulation is fine, but there is one exception: m_array should not be publically settable. It should be readonly or a getter-only {get; } property. Being a reference type, I can't think of any downside to making it a property. Being publically settable means that anyone can change it to null or an array of the wrong size and break the data-structure, which is obviously bad. The other array and dictionary should also be readonly.

I do wonder why you provide an indexer as well as the array, but do not provide a setter for the indexer. The indexer will also create confusion by copying structs you want to mutate. You should probably look at whether you can hide m_array altogether, and do all the work via the indexer: this would produce a much tighter API if you can 'get away' with it. You may be interested to look into ArraySegment as a possible means of facilitating a somewhat tighter API if that indexer is deficient.

Exception Handling

I don't know you use-case, but I'd reconsier using Debug.Assert for input sanitisation. It would seem much better would be to exploit the TryGetValue method of Dictionary'2 in Remove and TryAdd in Add to efficiency perform the check and throw under any runtime conditions.

Your exception messages could also be clearer. "NotFound": what is not found? If you throw an exception instead of asserting, you can throw an ArgumentException and make it completely clear what was not found and where the caller went wrong. "IllegalRead" means nothing at all. "Double Insertion" is pretty cryptic.

You could also do with checking that Size is less than Capacity when adding, as this should also throw an exception, rather than relying on the order of operations to throw with an IndexOutOfRange exception before doing any damanger (if m_guidToIDs[guid] was set first, this would linger despite the operation failing, so the code is extremely brittle).

A check in the constructor that capacity is non-negative would also be nice, just to cover as much of the API surface as possible with clear and useful exceptions (it will still fail if it tries to allocate a negative length array, but an ArgumentOutOfRangeException would be so much nicer.

Typical C♯

The code is mostly nice-to-read C#, though there are some bits that could be nicer:

The m_ member prefix is typical in C++, but much less so in C#. m_array should have a name consistent with being a public member: it should be in ProperCamelCase.
Generally it is advised that the accessibility of any member of type is made explicit e.g. public class FixedCapCollectionIntGuids<T>, private int m_capactiy). This avoids any confusion (particularly when people are used to using different languagse with different defaults), and makes it completely clear that this is the intention and you didn't just forget to qualify the accessibility.
The BCL uses Count rather than Size for everything: it's what people using C# will expect. I'd also argue it is clearer, because Size has can relate to size in memory. Conformity with the BCL also be sensible if you wanted to implement IReadOnlyList<T> (for which you would need to provide in addition an enumerator but nothing more), which could be useful.
It's also typical to have key, value in the BCL add methods, so you might want to consider having the same in Add.
Usually we use 4 spaces for indentation.

Other Comments

While I think I see why you would except this to only be used with structs, I don't see why you need limit this general purpose data structor to only structs. If you don't have a reason, I would remove the generic constraint (it has no semantic/performance impact for when structs are used). The only change this would warrant would be clearing removed values (so that you don't hold references to objects that are not in the structure). This is just a suggestion, and 'that would increase the API surface and costs of maintance/testing' would be a good reason to not do this.
public T this[int key] should have parameter guid for consistency.
FixedCapCollectionIntGuids is an odd name; I will only say that shorting Cap to Capacity is not a good idea: it only obfuscates the meaning.
For a 'tricky' API like this one (where it's very easy to mis-use m_array), you need to provide inline documentation (///) for all public parts of the API. This should detail the usage and assumptions, and explain things like "this is not thread safe at all", and that m_array may be larger than Size and you should not access anything beyond index Size - 1. I find that the act of writing documentation makes me aware of the edge cases I need to handle, makes it possible to maintain code without having to guess at the exact intention of a method/class, and gives consumers the information and confidence they need to use your APIs as intended.
Remove is a bit untidy looking: I would try to break it up a bit with empty lines, to separate the bit where you remove the old values, move the 'last' value into the inner position, and finally resize the structure. There is also a bug in Remove: it will go wrong if you try to remove the last element: writing the code to detect this should automatically force you to organise it so that my previous comment is addressed.


Function to split full name into first & last

First of all, you should be aware that "first name" and "last name" are very tricky concepts. An example in that linked Wikipedia article is José Luis Rodríguez Zapatero. José Luis is the first name, though it's in two words. Rodríguez Zapatero are both surnames (paternal and maternal). Or you have cultures where "name" means surname first and then given name, i.e. the opposite of Western tradition. Example in the linked article is Zhang Wei, Zhang being the family name and Wei being the given name.

Heck, royalty and aristocracy don't even have regular surnames, really (or they're almost never used). They're just "of" some place; Elizabeth II of England, for example. Or take someone like Albert Maria Lamoral Miguel Johannes Gabriel, 12th Prince of Thurn and Taxis (yes, that's the guy's full "name" though it's part-title and honorific). Rarely something you need to worry about of course, but just to show that names aren't simple.

Hence the most common - and most robust - solution is to simply use two text fields: First name and last name. Trying to split things in code is nigh impossible because there's no single, standard naming scheme for everyone, everywhere.

Even Facebook, which certainly has the brains and computing power to attempt something clever, just uses two separate input fields. It's just easier.

So short answer: Don't try. Just make two inputs. Especially as the backend needs two separate values anyway.

But hey, code review:

I don't see the need to pass in the fullName separately. It's already in the data object.
I'm not sure why _lastName has an underscore in it. There's (as far as I can tell) nothing special about that variable.
I'm also not sure why it's there to begin with. You can just assign to formData.last_name directly; no need to to store it in a local variable first.
There's no need for the if (nameArr.length > 2) branching. Given an array of exactly two words, the first branch would do the same as the else branch does, just via a different route. So, really, the pop and join strategy covers both cases already.
... what it doesn't cover is the case where there's only 1 word. If fullName is just "John", then that will (via the else branch) become formData.first_name. But formData.last_name will just undefined. If you only use the pop and join strategy, you'd get "John" as the last name, and empty string as the first name. Either way, it's not optimal.
When you split, you'll split twice on double whitespace and split on leading/trailing whitespace, too. So given a full name like " John  Smith ", you get nameArr = ["", "John", "", "Smith", ""].
I believe Angular can/will automatically trim leading/trailing whitespace, though. If not, you can use String.trim. However, doubled whitespace will remain, so split with a regular expression like /\s+/ instead.

I'd do this:

var nameArr = formData.full_name.split(/\s+/);
formData.first_name = nameArr.slice(0, -1).join(" ");
formData.last_name = nameArr.pop();

That's pretty much it. You'll still want to copy the formData, and perhaps delete the full_name property, but otherwise that's the meat of it. It'll still be weird if full_name is just "John", because you'd get "John" as both first and last name, so you should probably have some more validation somewhere.

Still, though: Just use two fields.


Better or more idiomatic way to apply a sequence of functions in Haskell

notK q = map (uncurry filter) . (zip (kFilters q))

is equivalent to

notK q rows = zipWith filter (kFilters q) rows

Onto making above Haskell less idiomatic and less pointfree and more readable.

notC q = map (filter (/= q))
notD q = (map (\(x, r) -> filter (\y -> abs(y - q) /= x) r)) . (zip [1..])
notK q = map (\(f, r) -> filter f r) . (zip (kFilters q))

These three are logically similar but structurally dissimilar.

First let's factor out common components, give them meaningful names, and some comments to help those readers without the Developer's Manual.

-- a new queen placed in column q
-- would take a piece placed in column x
-- n rows down
-- because (r, q) and (r+n, x)

-- are on the same column
sameColumn q n x = x == q

-- are on the same diagonal
sameDiagonal q n x = abs(x - q) == n

-- or (n, |q - x|) is in [(1,2),(2,1)]
onKnightMove :: Int -> Int -> Int -> Bool
onKnightMove q n x = (n, abs(x - q)) `elem` [(1,2),(2,1)]

The last one needs a better name still, oh well. At least they are of the same form, with parameter name use consistent among them (and elsewhere).

rowFilterList :: Int -> (Int -> Int -> Int -> Bool) -> [Int -> Bool]
rowFilterList q pred = map (\n x -> not $ pred q n x) [1..]

such that kFilters q = rowFilterList q onKnightMove

filterRows :: Int -> (Int -> Int -> Int -> Bool) -> [[Int]] -> [[Int]]
filterRows q pred rows = zipWith filter (rowFilterList q pred) rows

This way notC q = filterRows q sameColumn and notD q = filterRows q sameDiagonal

notK q . notD q . notC q a repetition is evident. And we now can factor it out easily.

filterWithAll :: Int -> [[Int]] -> [Int -> Int -> Int -> Bool] -> [[Int]]
filterWithAll q rows preds = foldl (\rows' pred -> filterRows q pred rows') rows preds

such that safe q rows = filterWithAll q rows [sameColumn, sameDiagonal, onKnightMove]

By factoring out [sameColumn, sameDiagonal, onKnightMove] as a parameter to place n one could easily generalize place from n super-queens to n queens or n rooks.


Join a collection of strings until character limit is reached

Although @TopinFrassi's solution is death plain and simple, I would separate the fetching of the values which fit in the limit and the actual joining with the separator like so

private static IEnumerable<string> FetchInRange(IEnumerable<string> collection, int characterLimit, int separationLength)
{

    int currentlength = -separationLength;

    foreach (var value in collection)
    {
        int length = value.Length + separationLength;
        currentlength += length;
        if (currentlength  > characterLimit)
        {
            yield break;
        }

        yield return value;
    }

}
private static string Join(IEnumerable<string> collection, int characterLimit, string separator = ", ")
{
    return string.Join(separator, FetchInRange(collection, characterLimit, separator.Length));
}

Each method has only one responsibility and they can be used for a wider range of separators as well.


I want to make the code a bit more clear

I would start by removing one of the if branches and customize the loop to do the job according to the parameters because both loop are nearly identical.

You can create two helper variables for the conditions and act appropriately:

var canAddTreeNote = _pagemode != BoPage.PageMode.View || ExistKeyWord(node);

if (!canAddTreeNote)
{
    continue;
}

and for adding child nodes something like this:

var canAddChildNote =
    _pagemode == BoPage.PageMode.View
    && ExistKeyWord(node)
    && node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0;

if (canAddChildNote)
{
    parentNode.ChildNodes.Add(newNode);
}

by their powers combined you'll get:

private void BindTreeView(IEnumerable<Opcion> OptionList, TreeNode parentNode)
{
    var nodes = OptionList.Where(x => parentNode == null ? x.ParentID == 0 : x.ParentID == int.Parse(parentNode.Value));

    foreach (Opcion node in nodes)
    {

        var canAddTreeNote = _pagemode != BoPage.PageMode.View || ExistKeyWord(node);

        if (!canAddTreeNote)
        {
            continue;
        }

        TreeNode newNode = new TreeNode();
        newNode.Text = (node.ParentID == 0) ? string.Format(@"{1}", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@"{1}", node.ParentID.ToString(), node.Descripcion.ToString());
        newNode.Value = node.OpcionID.ToString();
        newNode.ToolTip = node.Descripcion.ToString();

        if (parentNode == null)
        {
            TreeViewPalabrasClaveOpciones.Nodes.Add(newNode);
        }
        else
        {
            if (node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0)
            {
                newNode.Checked = true;
                parentNode.Expand();
            }

            var canAddChildNote =
                _pagemode == BoPage.PageMode.View
                && ExistKeyWord(node)
                && node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0;

            if (canAddChildNote)
            {
                parentNode.ChildNodes.Add(newNode);
            }
        }
        BindTreeView(OptionList, newNode);
    }
}

  How can I functionally decompose this method into many?

When you apply the above refactoring I think it's no longer necessary to create more methods.


Trying to follow your mathematical loop conditions makes my eyes go crossed in a hurry.

Perhaps you'd entertain a less-math-heavy alternative:

foreach (array_chunk($array, 4) as $row) {
    echo '
' , implode('	', $row) , '	' , str_repeat('	', 4-count($row)) , '
';
}

Granted this will be making a no-output call of str_repeat() on all rows except potentially the final row, but I think this technique will be more developer friendly.  I'm assuming that I understand your $data (Demo).  I could have written a conditional for str_repeat() but felt that would only bloat the code.

I tend to lean toward passing json back from an ajax call, but for this situation sending back html is the simpler approach.


Performance

Your program is slow because you check each number against all subsequent numbers.  For a fully consistent phone book with n entries, that's O(n2).

A better strategy would be to sort each phone book first.  Then you only need to check consecutive pairs.  If one number is a prefix of another, then the prefix will appear just before the longer number.  That's O(n log n) for the sorting, plus O(n) for the checking, which is O(n log n) in total.

Looping

The infrastructure for handling test cases is clumsy.

One problem stems for the fact that you slurp up all the input into one list right away, with content <- getContents followed by allLines = lines content.  As a result processCases has to take a list of those lines as input, and parcel them out using drop (caseLines+1) cases.  A further complication is that allLines contains non-homogeneous data: the first line specifies the number of test cases, the first line within each test case specifies the size of that test case, and all other lines contain phone numbers.  You're basically doing I/O by dissecting the list, and you would be better off doing real I/O.

processCases performs a countdown using its second parameter.  It would be better to have a processCase function instead, which is called n times.  You can't make that improvement, though, given the way all the input has been slurped up into one list.

Style

For readability, maintainability, and performance, declare the types of all functions.  You missed toYesNo and main.  Instead of [[Char]], use [String], which is easier to understand.
Avoid function names like checkSomething, which sound more imperative than functional.  For example, isListConsistent would be a better name than checkListConsistency.
Take advantage of standard library functions — use Google and Hoogle.  For example, notStartsWith is just ((not.).isPrefixOf).
Simplify predicate tests on a list.  checkNumberConsistency can be

checkNumberConsistency :: String -> [String] -> Bool
checkNumberConsistency n ns = all (checkNumberConsistencyVsNumber n) ns

Avoid if … then … else.  There is usually a better alternative.  For example, (if (checkListConsistency current) then True else False) is just checkListConsistency current.  Your checkListConsistency function can be simplified:

checkListConsistency :: [String] -> Bool
checkListConsistency [] = True
checkListConsistency (n:ns) = (checkNumberConsistency n ns) && (checkListConsistency ns)

Suggested solution

import Control.Monad (replicateM, replicateM_)
import Data.List (isPrefixOf, sort)

isConsistentPhoneList :: [String] -> Bool
isConsistentPhoneList numbers = not $ any (uncurry isPrefixOf) consecutivePairs
  where
    sortedNumbers = sort numbers
    consecutivePairs = zip sortedNumbers $ tail sortedNumbers

yesNo :: Bool -> String
yesNo True = "YES"
yesNo False = "NO"

processCase :: IO ()
processCase = do
  caseSize <- readLn
  inputs <- replicateM caseSize getLine
  putStrLn $ (yesNo . isConsistentPhoneList) inputs

main :: IO ()
main = do
  caseCount <- readLn
  replicateM_ caseCount processCase


Another approach would be to make the positions of sprites relative to the position of the entity. That way, the default of zero comes up naturally and when you move an entity, all of its sprites are automatically moved too.

One more advantage is that this means position zero now becomes a valid one.


You can use the ComparerExtensions library to help you create comparers more easily.

With it, your code could look something like:

IComparer<Physician> comparer = null;

if (criteria.SortBy == "name")
{
    comparer = KeyComparer<Physician>.OrderBy(x => x.Name);
}
else if (criteria.SortBy == "birth")
{
    comparer = KeyComparer<Physician>.OrderBy(x => x.DateOfBirth);
}

if (comparer != null)
{
    if (criteria.SortDirection != "ascending")
    {
        comparer = comparer.Reversed();
    }

    physicians.Sort(comparer);
}


Python pandas: Take column of counts and create DataFrame with a row per count

You are correct in thinking that iterrows is a very bad sign for Pandas code. Even worse is building up a DataFrame one row at a time like this with pd.concat - the performance implications are dreadful.

Instead of reaching for loops, your first step should be to check if there is a vectorized DataFrame method you could use. In this case.. perhaps there isn't.

Next step is dropping into NumPy. And lo and behold, there is numpy.repeat, which allows you to repeat an array along an axis with another array of counts. We can wrap that up in a function.

def repeat_frame(df, counts):
    rep_array = np.repeat(df.values, counts, axis=0)
    return pd.DataFrame(rep_array, columns=df.columns)

# would be called with
repeat_frame(df[['a', 'b']], df['count'])

This runs in 450 µs on my machine compared to your current solution in 20.2 ms for your sample data. On a larger sample size with 1000 rows, it runs in 511 µs compared to 6.86 s for your current solution, roughly 13000 times faster.

If you find yourself wanting to use pd.concat or similar in any situation like this to build up a DataFrame row-by-row, stop! There is going to be a faster way.

Check for vectorized Pandas functions that can help you out
Ditto for NumPy and SciPy after that

And if you are certain you have some wild iteration logic that cannot be vectorized (which is unlikely), create an empty array of the necessary shape and consider using Numba or Cython to speed up filling it up with a loop.


Entity Framework already implements UoW+Repository for you.
To KISS, your code would simply "wrap" the DbContext with an interface, as explained here, here and here, and possibly elsewhere too. Shortly put: UoW+Repository is an abstraction. Entity Framework is an abstraction. Abstracting an abstraction by wrapping EF with UoW+Repository isn't going to KISS.
That said, there are a number of things to say about your code.

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
}

That seems pretty.. naked. Limited, to say the least. What if you only need to fetch a single T? You're going to GetAll and filter them on the client side with Linq-to-Objects? Linq-to-Entities has much more to offer than that. I'd expect a repository interface to support all CRUD operations!
I don't understand why GenericRepository<T> doesn't implement IRepository<T>. Looks like you can get rid of the HostRepository class

If your entity type is a Host, then this is over-complicated:

var hosts = from host in context.Hosts
            select new Host()
            {
                FirstName = host.FirstName,
                LastName = host.LastName,
                Email = host.Email
            };
return hosts.AsEnumerable().ToList();

It could be written like this:
return context.Hosts.ToList();

There's no need to project a selection of a given type into ..instances of that same type. There's no need to call AsEnumerable at all to return an IEnumerable<T>, because IQueryable<T> already implements IEnumerable<T>, which means this:
return context.Hosts;

Would return the same thing - the difference is when EF takes your query, translates it into T-SQL and sends it over to the database to materialize the results. You'll probably want to keep Linq-to-Entities within your DAL, which means you'll want to materialize the results before returning from the GetAll method - that's what ToList will do, so returning context.Hosts.ToList() is all you need to do here.

It's not clear why you're using internal, protected and virtual modifiers. A generic repository that needs to be inherited (virtual implies an eventual derived type that will override such a property/method), is missing its purpose I find - the very idea of having a generic repository is to avoid having to implement a repository for every entity type IMO.


Your code is buggy, if you have two Nodes with the same value in succession it will corrupt the list....

prevNode will be set to the deleted node tempNode, and if the next value also matches the input value you will be working with the wrong node as prevNode.

Also, why is d a good name for the input search value?

To avoid future bugs it is convenient to mark constant input values as final. It also can potentially help with performance

You need to change some code:

// added final, change input to `searchValue`
public boolean delete(final int searchValue) {
    Node tmpNode = head;
    Node prevNode = null;
    boolean deletedANode = false;

    /*
    This code is redundant, the while-loop does the same effective thing.
    if (head == null) {
        return deletedANode;
    }
    */

    while (tmpNode != null) {
        if (tmpNode.data == searchValue) {
            if (tmpNode == head) {
                head = head.next;
            } else { // fixed indenting/newline
                prevNode.next = tmpNode.next;
            }
            // fixed indenting
            deletedANode = true;
         } else {
             // only advance the prevNode when there's no match.
             prevNode = tmpNode;
         }
         tmpNode = tmpNode.next;
    }

    return deletedANode;
}


First, your exception wrappers are useless:

try:
    f = destpath
except IOError:
    print "Cannot open specified file: %s" % destpath

destpath is already a file object. If there were an opening problem, then argparse would have told you with an exception at this level.

  parseCSV function can be rewritten in one line by turning the csv reader object to a list by iterating on it when building the list object:

def parseCSV(path):
    '''
    Parses a CSV file and return the rows as a list
    '''
    return list(csv.reader(path))

(I suggest that you close the file outside the parseCSV method as it wasn't its responsibility to open the file in the first place)

  outputCSV function:

don't use the indices here, iterate on the elements:

for i in range(len(rows)):

becomes:

for row in rows:  # "rows[i]" becomes "row"

now all those append statements can be simplified/shortened by passing lists to extend.

Also note that if rows[i][1] is not None is always True: csv module returns str objects, never None.

    new_list = []
    if re.match(r'switch\d$', rows[i][0]):  # no need for ^: it's match not search
        new_list.extend([row[0],'','hostname '+row[0],'!'])
        # skipping the "always true" condition, you may need to adapt this
        new_list.extend(['interface '+row[1].lower(),' switchport mode '+row[2],' switchport '+row[2]+' allow vlan '+row[3],'!'])
        # skipping the "always true" condition, you may need to adapt this
        new_list.extend(['interface '+row[4].lower,' switchport mode '+row[5].lower(),' switchport '+row[5].lower()+' vlan '+rows[i][6]])
        writer.writerow(['\n'.join(new_list)])

Last but not least, when using csv & text mode in Windows you stumble on the

  infamous blank-line-every-two-line bug ¹ ² ³

So for python 2 (seems to be the case), you may want to change the argparse for output to:

parser.add_argument('destpath', help="Output CSV file", type=argparse.FileType('ab'))  # open as binary

and for python 3:

parser.add_argument('destpath', help="Output CSV file", type=argparse.FileType('at',newline="")) # don't issue extra CR chars, well, some magic like that :)


Calculating months elapsed since a given date

Don't reinvent the wheel for what Joda time has already written for you:

int monthsBetween = Months.monthsBetween(new LocalDate(date1), new LocalDate()).getMonths();

From the localDate doc:

You can pass a string in the constructor. (you could test that)
Empty constructor is current time.


You're almost there. You rebuild the entire HashSet for each of the i-m sub arrays resulting in (i-m)*m  worrk.

Change the HashSet to a HashMap and then imagine the sub array as a sliding window. When the window moves one step to the right, count down number at the far left of the old window position in the HashMap and if it becomes zero, remove it. And then add the number to the far right of the new window position to the count of that number in the HashMap (or add the number with count one if it didn't exist), and at each window position take the size of the HashMap. This is (i-m)+m work which is much faster.


Running a shell command and getting output

Prefer comparing pointers to nullptr instead of to NULL in C++11. nullptr exists for exactly that reason. The NULL macro is not portable. While it exists in many different environments there is no guarantee how it will be implemented or what it is intended to be used for. It may be implemented as 0, '\0', or as some pointer type, or anything else, and every different environment may define it differently or not at all. It is non-standard. nullptr is defined by the standard and all C++11 standard compliant compilers must support it.


It would seem that a simple optimization would be to do it in a single step, i.e. something like:

var finalPassArray = [];
for(var key in _self.productList)
{
    finalPassArray.push(_self.turnoverMonthlyData.filter(function (el) {
        return el.product == _self.productList[key].product;
    }).map( function(el) {{ el.ordered } ) )
}

But I would be tempted to use something like reduce:

var results = _self.turnoverMonthlyData.reduce( function(list, el) {
                if (!list[el.product]) list[el.product] = [];
                list[el.product].push(el.ordered);
                return list;
              }, {} );

Which I tweaked slightly to give results as:

{ T0000001_: [48,264,24,67,54],
  T0000002_ :[4567,511,24,18,5],
  T0000003_: [4,57,6,11,544],
  ...

which might be easier to work with.


Function to check that a Python list contains only True and then only False

You can just use x[n_trues:] rather than x[n_trues:len(x)].
Your comments don't really say more than the code. And so I'd recommend removing the comments.
If you want to keep your code documented use docstrings, which can be exported to your documentation via tools like Sphinx.
As commented by Konrad Rudolph, you can remove the and not any(should_be_false) as this will always fail if the all fails.

def check_true_then_false(x):
    """Check first n values are True and the rest are False."""
    return all(x[:sum(x)])

If you want your code to work with iterators, not just sequences then you can instead use:

def check_true_then_false(it):
    """Check first n values are True and the rest are False."""
    it = iter(it)
    # Takes advantage of the iterating side effect, where it consumes the iterator.
    # This allows `all` to simultaneously checks `it` starts with trues and advances `it`.
    return all(it) or not any(it)

For the following two inputs all will result in:

>>> all([True] * n)
True
>>> all([True] * n + [False, ...])
False

However it will mean that it is still [...] as all and any are lazy. Meaning that we just need to check the rest are false. Meaning all slices the iterator for you without you having to. Leaving any with:

>>> any([False] * n)
False
>>> any([False] * n + [True, ...])
True


In the Operation method

private static string Operation(int randomIndex)
{
    string operation = "";
    switch (randomIndex)
    {
        case 1:
            operation = "+";
            break;
        case 2:
            operation = "-";
            break;
        case 3:
            operation = "*";
            break;
        case 4:
            operation = "/";
            break;
        default:
            Console.WriteLine("error");
            break;
    }
    return operation;
}

instead of doing operation = ... and then returning operation you can just return

Example :

case 1:
    return "+";

Same thing in the Cal method.

In the CheckAnswer method you should just have else instead of else if(userInput != sum)

Also in the Main your Random rnd = new Random(); should be out of the do while loop.


Generally speaking, doing something with jQuery will perform worse than doing that same thing directly through the DOM. In this case, using the following code inside the each will yield better performance:

this.href += window.location.search;

Note, however, that code will create an invalid URL if there is already a query on the original href.


Bash script that checks for package dependencies and installs them if necessary

Instead of this:

    if [ $(dpkg-query -W -f='${Status}' $i 2>/dev/null | grep -c "ok installed") -eq 0 ]; then

A better way to write the same thing:

    if ! dpkg-query -W -f='${Status}' $i 2>/dev/null | grep -q "ok installed"; then

Instead of this:

        if [ "$response" == "y" ] || [ "$response" == "Y" ]; then

A simpler way to write is:

        if [[ $response == [yY]* ]]; then

This is not example the same. It will match anything that starts with "y" or "Y". If you want to match strictly only those letters, just drop the * from the pattern:

        if [[ $response == [yY] ]]; then

Finally,
all the ; at line endings are unnecessary.
The purpose of ; is to separate multiple statements on the same line.
Line breaks naturally serve as statement separators.


Wet Boxes problem: counting points on a triangular grid

It's been a while since I have worked in C, so a language-specific review would not be so accurate. The only thing I can say in that aspect is that you should put curly bracket even in single-command body ifs as the code gets more readable and less error prone.

Taking a look at the problem and at your solution I think that you're overcomplicating it. You are allocating memory for each box and working with it when you actually don't need them. All you need is a square matrix - to be more precise, a lower triangular matrix - of ints (in this case).

The idea is the following:

Represent the boxes' status via the matrix \$A\$. If the box in the position \$(x, y)\$ is wet then \$A_{x,y} = 1\$, otherwise \$A_{x,y} = 0\$. So, initially, every item in the matrix is \$0\$.
When the box in position \$(x, y)\$ leaks you just set all the appropriate cells of \$A\$ to \$1\$ and count the number of cells whose value has changed from \$0\$ to \$1\$.
Return the value of the counter for each case.

In pseudo-code (I'm not so practical in C), it becomes something like the following:

int[,] A = new int[7,7];

void initialize_matrix(){
    for(int i = 0; i < 7, i++){
        for(int j = 0; j < 7; j++){
            A[i, j] = 0;
        }
    }
}

int count_wet_boxes(int x, int y){
    int counter = 0;

    for(int i = x; i >= 0; i--){
        for(int j = 0; (i + j) <= (x + y); j++){
            if(A[i, j] == 0){
                A[i, j] = 1;
                counter++;
            }
        }
    }

    return counter;
}

int main(){
    initialize_matrix();

    // the rest of the logic goes here
}

You can also try to ask in the Mathematics SE site if there is a formula you can use.

Let me know if anything's unclear.


Is there a more efficient way to do Base 32 encoding/decoding than this?

If you really want to chase those milliseconds then I would try following:

1) I consider division operations as slow so I would avoid using two divisions if it can be replaced with one division and some easier operation:

Function ToBase32(ByVal lInput)
    Dim lModulo, sTemp, lNextInput
    Do Until lInput = 0
        lNextInput = lInput \ 32
        lModulo = lInput - 32 * lNextInput
        sTemp = Mid(kBase32Digits, lModulo + 1, 1) & sTemp
        lInput = lNextInput
    Loop
    ToBase32 = sTemp
End Function

2) In some other language I would use bit shift of course instead of diviosion/multiply. But as far as I got vbscript doesn't have bit shifting operators.

3) Your FromBase32 method doesn't look optimal to me at all. I would replace those Replace and InStr calls with array of integers for letter chars. This array will contains corresponding base 32 numbers for chars. And you will be able to translate letter into number using array indexing accessor which is much faster operation than looking for a character in a string. Some pseudocode showing how to convert character sR into number:

Dim sR;

// defining an array:
Dim charArray = [  10, // 'a' char
                   11, // 'b' char
                   ...
                   17, // 'h'
                   1 , // 'i' !!
                   ...
                   0 , // 'o'
                   ...];

Dim lNumber;
if (sR >= 'a' && sR <= 'z')
    lNumber = charArray[sR - 'a'];
else // it is digit
    lNumber = sR - '0'  // in most languages I know this will convert '1' char into 1 integer

P.S. of course I haven't measured anything, I do not even know vbscript, just wanted to give you an idea on what can be changed.

P.P.S.: My second point doesn't take into account that there is a chance that VBScript interpreter will do such an optimization for you.


Like so:
Here you can see that is easier to have errors as an array, use alternative control statments to separate php from html:

 <?php
    $messages = array();
    if(strlen($display)<4)
    {
        $messages[] = 'Display name is too short';
    }
    if (empty($email))
    {
        $messages[] ='You did not put a valid email address. We require this to verify your account.';
    }
    if(mysql_num_rows($check_display) != 0)
    {
        $messages[] = 'Display name is already in use';
    }

    if(mysql_num_rows($check_user) != 0)
    {
        $messages[] = 'Username is already in use.';
    }

    if(mysql_num_rows($check_mail) != 0)
    {
        $messages[] = 'Email is already in use.';
    }

    if ($pass != $pass2)
    {
        echo 'Passwords do not match.';
    }
    ?>

        <?php if(!empty($messages):?>

            <?php foreach($messages as $message):?>

<?php echo $message;?>

            <?php endforeach;?>

        <?php endif;?>


Set<Asset> transferredAssets = assetRepository.getAll(transfer.getTransferredAssets());
for (Asset asset : transferredAssets) { ... }

Since the transfer isn't done yet, and also to prevent ambiguity post-transfer, may I suggest renaming the method to getAssets()? You can also inline the call:

for (Asset asset : assetRepository.getAll(transfer.getTransferredAssets())) { ... }

Two minor improvements I can suggest for the snippet below:

It's safe to compare enums by ==.
Have a transfer(TransferType, long) method in Asset so that the toggling is done within Asset: callers only need to supply the TransferType value.

if (TransferType.TEMPORARY.equals(transfer.getTransferType())) {
    asset.transferTemporarily(transfer.getReceiver());
} else {
    asset.transferPermanently(transfer.getReceiver());
}

Since the use of realized and cancelled are just opposites of each other, you may want to consider having just a single boolean field, to keep the implementation simpler.

if (accepted) {
    this.realized = true;
} else {
    this.cancelled = true;
}

In Asset:

public void transferTemporarily(long receiverId) {
    this.currentOwnerId = receiverId;
    this.unblockIfBlocked();
}

public void transferPermanently(long receiverId) {
    this.actualOwnerId = receiverId;
    this.currentOwnerId = receiverId;
    this.unblockIfBlocked();
}

This can be slightly simplified as:

public void transferTemporarily(long receiverId) {
    this.currentOwnerId = receiverId;
    this.unblockIfBlocked();
}

public void transferPermanently(long receiverId) {
    transferTemporarily(receiverId);
    this.actualOwnerId = receiverId;
}

Alternatively, if reading temporarily inside a permanent method is slightly confusing, have a new method setCurrentOwnerAndUnblock() to do that instead...


There is no need to make anything static here. I would pass the config file name in the constructor, and make everything an instance variable.
Any other object that needs configuration needs this config object, rather than referencing it via the singleton pattern
Storing the database configuration, like hostname, username and password makes sense in a config class. Actually connecting to the database does not.
Instead of using the die(...) function, throw an exception. Really, this would be made obsolete by not connecting to the database in a config class, but whenever you decide to do this, throwing an exception is more appropriate. You communicate that an insurmountable problem has occurred that you cannot fix, but you give other code in the system the option of fixing it.
The method names are in PascalCase -- idiomatic for C#, but not for PHP. The PHP Coding Style Guide from PHP-FIG is a good reference. Use camelCase instead, so LoadConfig becomes loadConfig.
The RequireFiles method isn't really configuration and doesn't belong in a config class. A class or function that has a more global scope in the application should be loading those, or take advantage of autoloading.


Is it necessary to replace this cursor in SQL Server 2005?

So, you can simplify the CTE with some SQL magic:

WITH RecordsBeingUpdated AS
(
    SELECT
        NOTE_COUNTER,
        MEMBER_UPI,
        CASE_SEQ,
        DIFF_ENCOUNTER_DATE,
        ROW_NUMBER() OVER (PARTITION BY MEMBER_UPI, CASE_SEQ ORDER BY DIFF_ENCOUNTER_DATE ASC) AS RowNum
    FROM
        #TMP_NOTES
    WHERE
        TOTAL_CALLS > 1
)

UPDATE RecordsBeingUpdated
SET    NOTE_COUNTER = RowNum

Essentially, the virtual table built for the CTE has direct reference back to the concrete tables in the selection. This means you can update the CTE directly and SQL will update the corresponding concrete table within, provided the target table is the FROM table (not a joined) and there is no chance of ambiguity in what needs to be updated.

(Removed DIFF_ENCOUNTER_DATE from partition per comments).


How to find the unique values from the JSON file?

So… I have spent a bit time on this and generated myself a random JSON file matching your format. Mine is 167 MB in size, so not too far off from yours.

First of all, ijson’s performance is terrible. I’ve tried it multiple times and it’s very slow for me (much slower than your results actually). While the idea sounds great, it took very long to read and parse the file.

Using the normal json module gave me much better results. In fact, reading and parsing the file took only ~20 seconds, of which reading the file was just a very small fraction. Most of the time was actually spent on extracting the scores; generating the set from them again is very quick.

So to speed this up, we obviously want to avoid creating all those intermediary objects in between, and just extract the data we are interested in. In your case where the file has a rather simple structure, we don’t really need to parse it as a JSON object but we can just operate on the string directly and search for the scores.

As we discussed this on the SO Python chat, Jon Clements came up with this solution:

with open('file.json') as f:
    content = f.read()
    print len(set(m.group(1) for m in re.finditer('"score": (\d+)', content)))

This in fact runs in a few seconds, 8 on my machine, and is a multitude faster than anything that utilizes JSON. Of course this highly depends on the format of the file, so if you have additional data inside (which you left out in the question) you might need to adjust this.


In fact this would be sufficient:
return '{0:1.3f}'.format(s)

(provided that the argument passed is a float).
There is no need for a function.
The above will return a string, if you want to return a float then use the float function:
return float('{0:1.3f}'.format(s))

Or even shorter, taking advantage of F-strings. I prefer this option personally:
return f'{s:.3f}'

Again, this returns a string but you can cast it to a float if necessary.
As a reference: Python f-string tutorial


I wouldn't recommend using $("*").live, you only need the events on the document body, so long as they are allowed to properly bubble.


def parse_board(board):
    def map_black(spot):

This name suggests that the function is a variant on map. Whereas its actually intended to be used as a parameter on map

         return str(int(spot == 'B'))
    def map_white(spot):
         return str(int(spot == 'W'))

Both functions are very similiar, can you refactor?

    blackInit = '0b'
    whiteInit = '0b'

The python style guide suggest 'lowercase_with_underscores' for local variable names

    for line in board:
        squares = line.split('|')
        blackInit = blackInit + ''.join(map(map_black,squares))
        whiteInit = whiteInit + ''.join(map(map_white,squares))

Repeatedly adding strings is not very efficient python.

    return (blackInit,whiteInit)

Everything in your function is done twice. Once for 'B' and once for 'W'. I'd suggest you should have a function that takes 'B' or 'W' as parameter, and call that twice.

Here's how I'd tackle this:

def bitstring_from_board(board, letter):
    bits = []
    for line in board:
        bits.extend( spot == letter for spot in line.split('|') )
    return '0b' + ''.join(str(int(x)) for x in bits)

def parse_board(board):
    return bitstring_from_board(board, 'B'), bitstring_from_board(board, 'W')


Is the try-finally code block really required in your main() method?
Your get() fails if the default value is not any of those primitive wrapper classes. What if I want a BigDecimal instance? "1.0" can't be casted to that.
On a related note, you are relying on auto-boxing, which may lead to unexpected consequences:

// code compiles, but throws NullPointerException here
int npe = getValue("invalid-key", (Integer) null);

Maybe this is just a quick prototyping, but if you do decide to make this a full-fledged library class, you should not be having the main() method, the static initialization block, or your static fields. The fields should become class fields where Prefs needs to be instantiated. Testing should go into its own class.
On another related note, you don't necessarily need to create temporary files for testing. There is a Properties.load(Reader) method that will work with a StringReader, which can be used in turn to wrap your test Strings/lines.
I don't think there's a benefit to instantiating a FileOutputStream object immediately after you have load()-ed the file. Things may happen between the loading and storing of properties, so regardless of whether you have this object or not, the storing process may still fail afterwards. Also, it seems like you do not need to explicitly flush() after calling store() as that is already done according to the Javadoc:

  After the entries have been written, the output stream is flushed. The output stream remains open after this method returns.


Practicing recursion with getElementsByClassName

Apart from what cssGEEK pointed out, your code cannot work at all, since maNodes[i].classList doesn't return an Array but a DOMTokenList, which has no forEach() method.

So I'm surprised you said it works: it can happen only when no class is defined for an element (then your || [] makes classes to be an Array), but for each element having class(es) it fires an error "classes.forEach is not a function".

Here is a slighthly different code to achieve what you planned using the same way:

var getElementsByClassName = function(className){
  var result = [];
  function diveIn(motherNode, result, className){
    var maNodes = motherNode.childNodes
    for (var i = 0; i < maNodes.length; i++){
        var classes = maNodes[i].classList;
        if (classes && classes.contains(className)) {
            result.push(maNodes[i]);
        }
        if (maNodes[i].childNodes[0]){
            diveIn(maNodes[i], result, className);
        }
    }
  }
  diveIn(document, result, className);
  return result;
};

You can look at it working here.

But again don't forget that depending of how heavy is the HTML document it may encounter a max call stack size condition.


Not sure whether we have many Prism specialists on Code Review and I haven't worked with it for a while, so maybe my comments are incorrect at points.

I do not really like the way you're handling region.Views.CollectionChanged event. This event provides a lot of information in eventArgs but you're ignoring it. Firstly you do not handle removing views at all. Secondly instead of iterating through all views every time I would use those from eventArgs (NewItems property).
I believe generally it is better to have views isolated from regions in terms of concrete types. Your view is not isolated since it has to inherit RibbonTab class. Maybe it is not an issue here and I'm not sure whether it should be changed somehow, it just looks strange to me.


As written in the comment, it reminds me of LINQ. So, maybe it make sense to write a Linq QueryProvider to use the familiar LINQ syntax.

If that is not an option:

I would drop the method Build() and make the method From static instead. That simplifies the API.


TaskScheduler that uses a dedicated thread

TryExecuteTaskInline is used in what is called "task inlining": basically, when you call Wait() on a Task that didn't start executing yet, it might be executed on the current thread. A simple way to test that is:

var factory = new TaskFactory(new SequentialScheduler());

factory.StartNew(
    () =>
    {
        factory.StartNew(() => { }).Wait();
    });

For more information, see Stephen Toub's article Task.Wait and “Inlining”.

But this all means that a Task might be executed outside of your Run() loop, so the call to TryExecuteTask() there might return false. Because of that, you should simply ignore the return value there (just like the official example scheduler does, in its NotifyThreadPoolOfPendingWork()).

Another option would be to remove inlined Tasks from the queue, but there is no simple way to do that for BlockingCollection.

I think that m_disposed should be volatile, otherwise, the Run() loop can be optimized into an infinite loop that checks the value of m_disposed only once, at the start.

For disposal, you might want to use the completion capability of BlockingQueue. That way, trying to schedule a new Task after the scheduler has been disposed will throw, which I think is the correct behavior.

If you do this, you can also rewrite Run() to use GetConsumingEnumerable(), and remove m_disposed altogether.


Here's a partial solution:

as_strided = np.lib.stride_tricks.as_strided
def fun2(refArray):
        y = len(range(-halfwindow,halfwindow+1))
        II=slice(halfwindow, nrow - halfwindow)
        bA = boundsArray[:,II,II]
        x=len(range(halfwindow,nrow-halfwindow))
        shape = (x,x) + (y,y)
        strides = refArray.strides
        strides = strides + strides
        print(shape, strides)
        A = as_strided(refArray, shape=shape,strides=strides)
        print(A.shape,(refArray[0,0],refArray[-1,-1]),(A[0,0,0,0],A[-1,-1,-1,-1]))
        valid = (A >= bA[0,:,:,None,None]) & \
             (A <= bA[1,:,:,None,None])
        valid = valid.sum((-2,-1))
        # # valid pts per window
        print(valid.shape)
        return valid

It uses np.lib.stride_tricks.as_strided to create overlapping windows.  It's an idea that has been presented in several SO answers.

In timing it is 4-5x faster than your iteration.

A is a (470,470,31,31) view of refArray, i.e. 470x470 windows, each 31x31.  And with the strides value they overlap.

But it is partial.  valid.sum() gives the same values as your result.sum().  So it finds the same total number of 'valid' points. But valid (after summing on the 31x31 dimensions) is a (470,470) array, one value for each 'window', and that value is the number of valid points within the window.  It is the equivalent of doing windows[i-halfwindow,j-halfwindow] = valid.sum() in your iteration.

I think your result is the number of windows in which each point is valid.

I haven't figured out how to map the (470,470,31,31) valid array back on to the (500,500) points.  But I pretty sure there is such a mapping.

This is a temporary fix:

def fun2(refArray):
        y = len(range(-halfwindow,halfwindow+1))
        II=slice(halfwindow, nrow - halfwindow)
        bA = boundsArray[:,II,II]
        x=len(range(halfwindow,nrow-halfwindow))
        shape = (x,x) + (y,y)
        strides = refArray.strides
        strides = strides + strides
        A = as_strided(refArray, shape=shape,strides=strides)
        valid = (A >= bA[0,:,:,None,None]) & \
             (A <= bA[1,:,:,None,None])
        return valid

def fun3(refArray,valid):
        result = np.zeros_like(refArray)
        n0,n1,n2,n3 = valid.shape
        for i in range(n0):
            for j in range(n1):
                result[ i:(i+n2),j:(j+n3) ] += valid[i,j]
        return result
result = fun3(refArray, fun2(refArray))

fun3 has the same sort of iteration as your code, but there's still a 2x speedup.

While each window has the same number of points, the reverse is not true.  Corner points occur in only one window each.  Middle ones around 900 each.  That may make a pure vectorized numpy solution impossible.


Just a few thoughts...

Instead of using data tables and data sets I would try to go with POCO and a data reader. This is definitely more linq friendly. Perhaps even faster to load.
You could try to load the tables in parallel - I doubt a single table brings the SSD to its limits.
All SQLite objects need to be disposed.
Your naming conventions is in great need of improvement - lots of abbreviations and mixed case.
The return true isn't necessary. The method never returns a false anyway. It might as well be just void.


Reading contents of a file consisting of strings separated by a null character

A couple of issues:

while (ifs.good())

Don't loop on good() (or eof()). This is one of the more annoying parts of the C++ iostream library. This should be:

while(std::getline(ifs, s, '\0'))

std::getline returns a reference to its input stream (std::basic_istream&). How this actually checks the stream state and continues looping is pretty complicated* - suffice to say this is the canonical way of doing it. If you're really being good about your error checking, you'd then call ifs.readstate() after your while loop and check the fail and error flags aren't set.

Secondly, this creates a new string every time around the while loop. Instead, you probably want:

//Note you probably shouldn't call it list, because of the std::list<T> type
vector<string> v;
string s;

while(std::getline(ifs, s, '\0')) {
    v.push_back(s);
}

There are a few ways of signalling that an error has occurred - throwing an exception is one possibility. Returning a pair<vector<string>, bool> or pair<vector<string>, int> indicating either success (for bool) or number of characters read (for int) is another possibility - this is basically an "error code" way of dealing with the problem. Error handling is always tricky, unfortunately.

Either way, currently you return a vector whatever happens, so you might as well construct it outside the if test:

ifstream ifs(filename, ifstream::in);
vector<string> v;

if(ifs) { ... }

return v;

What happens that it calls the ifstream's operator void*() which tests all error flags and eof, returning a nullptr if any of them are set, otherwise a non-zero pointer. See also std::getline returns.


However, I feel it's long-winded.

To reduce the amount of repeated code, and to make it easier to adapt for different columns without writing the same sort of thing again 2 or 3 times, look for similarities across the different columns. For every column, you're calling arcapi.dataResult().columnNameToIndex, so you can make a function which, given a column name, calls that. You're also accessing the this.children[index].innerHTML for every index retrieved.
One option is to use objects instead of multiple standalone variables. You can have an object indexed by variable names, whose values are the column indicies. Then, in the selectAll callback, you can construct an object with the same properties but with the text values you're interested in by using mapping the object's entries and passing into Object.fromEntries:
function rm_row() {
  const getIndex = columnName => arcapi.dataResult().columnNameToIndex(columnName);
  const columnIndiciesByName = {
    inherent: getIndex('Inherent Risk'),
    residual: getIndex('Residual Risk'),
    perf: getIndex(arcapi.getSetting('Column name')),
  };

  d3.selectAll("#" + arcapi.chartId() + " .dataTables_scrollBody tbody tr").classed('removerow', function() {
    const columnTextsByName = Object.fromEntries(
      Object.entries(columnIndicies).map(
        ([key, columnIndex]) => ([key, this.children[columnIndex].innerHTML])
      )
    );
    columnTextsByName.perf = columnTextsByName.perf.replace(/[`~%]/gi, '');
    // Then refer to columnTextsByName.inherent, etc

The above is just an option to consider. While this makes the code less repetitive and more flexible for future added or removed columns you might want to check, I'm not entirely convinced that it's a solid improvement over your current code if you're not expecting your current code to change. YMMV; you may consider your current code to be more readable, or not.
Other possible improvements:
Don't use var in ES6: If you're going to write in ES6 syntax - which you should, it's great - there's no reason to use var, it has too many gotchas (such as function-scope hoisting and automatically being assigned to the global object on the top level) to be worth using. Always use const (or, when you must reassign the variable, let).
JS naming conventions The vast majority of professional JavaScript uses camelCase for functions and ordinary variables. snake_case is quite rare (and mixing snake case with camelCase in the same variable name is even weirder). Consider using camelCase everywhere that it's appropriate.
cf_regex On a similar note, name your variables appropriately: in your original code, cf_regex is not a regular expression, it's just a string which has had certain characters replaced. Better to call it something more accurate and longer (I don't have any idea what it's meant to be, and neither will other readers of the code given only this context)
Something odd about the regex - you're using the case-insensitive flag i, but you're not matching any letters, so the flag isn't doing anything. Might as well remove it. Or, to make it clearer what's going on, if you're expecting the result to contain only numbers, match digits instead:
columnTextsByName.perf = Number(columnTextsByName.perf.match(/\d+/)[0]);

(since you're going to be comparing with numbers later, it feels better to cast the variable being compared to a number too; it makes more sense and will make debugging a bit easier if problems arise later)
innerHTML or textContent? Unless you're deliberately retrieving HTML markup, which doesn't look present here, if you just care about the text of a cell, it would be more appropriate to use .textContent rather than .innerHTML. It's faster too.
Semicolons You're using a few semicolons, but also missing a bunch. Unless you're an expert or use semicolons everywhere, you may eventually get tripped up by Automatic Semicolon Insertion. Consider using a linter.
Performance You say

I have thought of creating an array and store all my variables in an array, but I feel this approach will be expensive.

On modern computers, the overhead of creating an array or object instead of multiple standalone variables is completely nonexistent. If using a particular data structure makes the code more maintainable (given whatever style you prefer), go ahead and do it. If you later find that there's a performance issue, feel free to go back and debug to find what exactly the bottleneck is, so you can figure out a more efficient method - but using an object or array will almost certainly not be the bottleneck. Try to avoid premature optimization, or at least don't sacrifice code clarity for it unless you have to.