Calculate sum of digits from a given number using String's slice method

Poor testing and vetting

There are a few problems with your approch.

Throwing an error seems to me to be the incorrect response. If the argument it not a number then the result should be NaN. Saves you having to wrap the function in a try catch which will basically stop the javascript engine from optimising the code.
Slice is a little over kill. You can use direct indexing str[index] or via str.charAt(index).
You had parseInt, which will remove any numbers after the decimal point. Use type coercion +num to convert from string to number and ""+num to convert to string.
You don't vet for exponent notation 123e-20
You don't vet - out of the number string and +,or  .
And your testing is very poor.

Rewrite

Below is a rewrite. It fails one test calcCheckSum("0006") should return NaN but it does not which means that isNaN("0006") is failing. This was a surprise to me and I can not make a decision on what to do untill I work out the extent of this bug.

 function calcCheckSum (num) {
    var ret, i;
    if (isNaN(num) || num === "") { // Could be a string that is a number. No need to check if its a type number
                                    // Why throw this will stop the whole program. Return a value that reflects the input
        return NaN;
    }
    // what about negatives,pluses, decimal points, exponent notation, fractions????
    num = (""+num).replace(/\+|\-|\./g,""); // remove junk if any
    if(num.indexOf("e") > -1){  // if exponent then remove it
        num = num.split("e")[0];
    }

    ret = 0;
    for (i = 0; i < num.length; i ++) {  // simpler as no need to -1 each iteration
        ret += +num[i];  // + does the type conversion. Split is expensive so just lookup char by index
    }
    return ret;
}

// -- TESTS -----------
var fails = [];
var valuesToReturnNAN = [NaN,"0006","a","0xff","","+",".","-","-0-","-.38.",true,false,Infinity,-Infinity];
var valuesToReturn6 = [123,6,1.23e20,1.23e-20,111111,"123","6","+6","-6","-.6","111111","111.111",".123",.123,0.123,123.,-123,-.123,+123.,+123.0,-123.0,0.123,"0.12300"];
valuesToReturnNAN.forEach(v=>{
    if( ! isNaN(calcCheckSum(v)) ){
        fails.push("failed : " +(typeof v) + " : (" + v + ") did not return NaN");
    }
});
valuesToReturn6.forEach(v=>{
    if( calcCheckSum(v) !== 6 ){
        fails.push("failed : " +(typeof v) + " : (" + v + ") did not return 6");
    }
});
console.log("Failed "+fails.length + " tests.");
fails.forEach(str=>console.log(str));


Evaluating Fibonacci-sequence-based recurrence relation (SPOJ Flibonakki)

First of all, make sure to add type signatures and use the appropriate number type. All your numbers are fine with Int, since they're bounded by

2 * (1000000006 * 1000000006)

Therefore, you can get rid of Integer throughout your program and simply use Int:

fib2 :: Int -> (Int, Int)
fib2 0 = (1, 1)
fib2 1 = (1, 2)
fib2 n
 | even n    = ((a*a + b*b)`rem` 1000000007, (c*c - a*a)`rem` 1000000007)
 | otherwise = ((c*c - a*a)`rem` 1000000007, (b*b + c*c)`rem` 1000000007)
 where (a,b) = fib2 (n `quot` 2 - 1)
       c     = a + b

Next, you want to use rem and quot, since they're usually faster and provide the same result as mod and div on positive numbers.

We also add a type signature to solve:

solve :: Int -> Int
solve n = (a*b)`rem`1000000007
    where (a,b) = fib2((2*n-1)`rem`2000000016)

Last but not least, we now simplify your main:

main :: IO ()
main = C.getContents >>= putStrLn . unlines . map (show.solve. fst . fromJust . C.readInt) . tail . C.words

However, I don't think that the IO part is the bottle-neck, so your usual String methods should be fine for this challenge, e.g.

main = getContents >>= putStrLn . unlines . map (show . solve . read) . tail . words

Indeed, this version of your program gets accepted of SPOJ. But so did your one. I guess that they updated the GHC version* and used the appropriate optimization flags. But you can make sure that they use optimization via

{-# OPTIONS_GHC -O2 #-}

* I just rememered that there was a defect with even in GHC 7.10. If they used GHC 7.10 (which is unlikely), then you were affected by that defect.


disable other default row- Entity framework

Does _uow.MarkAsBaseChanged() primarily hide EF's SaveChanges()?
If so, make a new version that can take an array of objeects.

You would want both objects saved with one command to ensure the transaction. As it ia nw, if storeModel fails you no longer have a default store.


One thing you could improve is to remove the jQuery dependency and just use addEventListener directly. This should be fine as all modern browsers support this already. Although, the tradeoff would be to normalize your keycodes yourself.

Also, I would suggest separating the code that updates codeCount from the code that checks if you achieved all keys in sequence. This way, there's clear separation in logic. The one problem I often come across with code not clearly separating logic is that in the long run, code becomes hard to untangle. Kill this habit while still early.

Taking it a bit further, you can assign the key values to an object. This way, you can represent the key in code using a enum-like structure and avoid hardcoding keycodes all over your code. This also allows you to change the keycode value without having to dive in to the code to find and change keycodes everywhere.

var codeCount = 0;

var Keys = {
  UP: 38,
  DOWN: 40,
  LEFT: 37,
  RIGHT: 39,
  B:66,
  A: 65,
  START: 13,
];

//[up, up, down, down, left, right, left, right, b, a, start]
var contraCode = [
  Keys.UP,
  Keys.UP,
  Keys.DOWN,
  Keys.DOWN,
  Keys.LEFT,
  Keys.RIGHT,
  Keys.LEFT,
  Keys.RIGHT,
  Keys.B,
  Keys.A,
  Keys.START,
];

window.addEventListener('keydown', function(event){

  var key = event.keyCode? event.keyCode : event.charCode;

  codeCount = contraCode[codeCount] === key ? codeCount + 1 : 0;

  if(codeCount === 11) alert('You got 30 lives!');

});


Generic Stack implementation in C-style C++

Naming seems inconsistent.

Consider prefixing all exported names with Stack, e.g. StackPush, StackPop, StackDestroy (Destory is definitely a typo).

The entity named first in a stack context is traditionally referred to as top.
Memory management is overengineered.

Every time a value is pushed memory is allocated. That's justifiable for ownership reasons (make sure to document it). However every time a value is popped memory is allocated again. This is very strange. A simple

return s->first->value;

would suffice.

Along the same line Destroy doesn't free memory (re)allocated for individual stack entries. Consider

while(s->length > 0)
    free(Pop(s))

You've mention the problem with strings; I believe it is stemmed from elemSize being a property of the stack itself. Making it a property of an element would solve the problem.
As mentioned in the comments, the C code shall not include C++ headers.


Sort all the characters according to their brightness

You may want to separate the logic to determine if a character is printable into a method and rewrite the brightness calculation using streams:

Map<Character, Float> brightness = IntStream.range(0, max)
        .mapToObj(x -> (char) x)
        .filter(Main::isPrintable)
        .collect(toMap(c -> c, Main::getBrightness));

Your sort algorithm is very inefficient, and there isn't a need to write your own.  Streams API makes it nice and clean:

List<Character> order = brightness.entrySet().stream()
        .sorted(comparingByValue())
        .map(Map.Entry::getKey)
        .collect(toList());

Above snippets assume static imports

import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;


Overall your implementation is fine, I would just suggest a few things:

Naming - move_rings and helper are not very descriptive. Give them better names, and give them good docstrings (I like NumpyDoc, but personal preference is fine)
move_rings shouldn't both do calculations and print to stdout. Instead, move_rings should return the information, and the caller should decide what to do with it
move_rings doesn't need the number_rings == 1 special case; your API handles it just fine
Instead of the hard-coded number approach, you can make a little Peg class that makes things a bit cleaner - subclassing namedtuple is a nice way to do this
Using f-strings makes printing easier
You can yield from instead of appending to the default argument list, which is easier to read and doesn't waste time reallocating space for the list
I added a (honestly pretty bad) visualization function to see the movements as well.

This is what I came up with (didn't do all of the things I mentioned above)

from math import ceil
from collections import defaultdict, namedtuple
from typing import Iterable, Generator, List, Tuple

class Peg(namedtuple("Peg", "id name")):
    pass

SOURCE_PEG = Peg(0, "A")
TARGET_PEG = Peg(2, "C")
WORKER_PEG = Peg(1, "B")
PEGS = [SOURCE_PEG, TARGET_PEG, WORKER_PEG]

def helper(
    number_rings: int, origin: Peg, target: Peg, spare: Peg
) -> Generator[Tuple[Peg, Peg], None, None]:
    """
    Helper function for performing the recursive call when solving the tower puzzle.

    Parameters
    ----------
    number_rings : int
        Number of rings in the puzzle
    origin : Peg
        The peg that we're moving from
    target : Peg
        The peg that we want to move to
    spare : Peg
        The other peg, that we can use as a helper

    Yields
    ------
    move : tuple
        The movement(s) (from-Peg, to-Peg) we determined were ncessary
    """

    if number_rings == 1:
        yield (origin, target)
    else:
        # Move all but 1 ring from ORIGIN tower to SPARE tower
        yield from helper(
            number_rings - 1,
            origin=origin,
            target=spare,
            spare=target,
        )
        # MOVE the last ring from ORIGIN tower to TARGET tower
        yield from helper(
            1, origin=origin, target=target, spare=spare
        )
        # MOVE the remaining rings from the SPARE tower to TARGET tower
        yield from helper(
            number_rings - 1,
            origin=spare,
            target=target,
            spare=origin,
        )

def move_rings(
    number_rings: int
) -> Iterable[Tuple[Peg, Peg]]:
    """
    Finds the optimal number of moves when solving a Tower of Hanoi puzzle
    with `number_rings` rings, starting on the first ring.

    Parameters
    ----------
    number_rings : int
        The number of rings in the Tower of Hanoi puzzle

    Returns
    -------
    move_list : iterator
        An iterable of the Peg movements
    """

    return helper(
        number_rings, SOURCE_PEG, TARGET_PEG, WORKER_PEG
    )

def draw_tower_of_hanoi(ring_map: List[int]):
    """
    Pretty dumb drawing tool that visualizes current peg state.

    Parameters
    ----------
    ring_map : list
        List of rings and their pegs. Format for a 3-ring puzzle start would be
        [0, 0, 0]. The index represents ring size (size = i+1), and the value at
        that index represents the peg (0, 1, or 2).
    """

    largest_ring = len(ring_map)
    peg_to_ring = defaultdict(list)
    for ring, peg in enumerate(ring_map, 1):
        peg_to_ring[peg].append(ring)

    peg_to_ring = {
        peg: sorted(ring_list, reverse=True)
        for peg, ring_list in peg_to_ring.items()
    }
    height_per_ring = {
        peg: len(ring_list)
        for peg, ring_list in peg_to_ring.items()
    }

    total_width = largest_ring * 6 + 7
    total_height = len(ring_map) + 2

    peg_centers = [
        1 + largest_ring,
        3 + largest_ring * 3,
        5 + largest_ring * 5,
    ]

    # fill it out
    drawing = [
        [" " for _ in range(total_width)]
        for _ in range(total_height)
    ]

    # Draw the pegs
    for i, row in enumerate(drawing):
        for center in peg_centers:
            drawing[i][center] = "P"

    # Draw the base
    drawing[-1][:] = ["G"] * total_width

    # Draw the rings
    for peg in peg_to_ring:
        for i, ring in enumerate(peg_to_ring[peg], 2):
            index = -i
            center = peg_centers[peg]
            drawing[index][center - ring : center] = [
                "R"
            ] * ring
            drawing[index][
                center + 1 : center + ring + 1
            ] = ["R"] * ring

    print("\r\n".join(["".join(row) for row in drawing]))

def visualize_tower_movements(
    number_rings: int, moves: Iterable[Tuple[Peg, Peg]]
):
    """
    Visualization tool for drawing the movement of rings in a Tower of Hanoi puzzle.

    Parameters
    ----------
    number_rings : int
        The number of rings in the puzzle
    moves : iterable
        The set of moves performed while working on the puzzle
    """

    visualizer = [0] * number_rings
    draw_tower_of_hanoi(visualizer)
    for move_from, move_to in moves:
        # Get the smallest ring on the peg, as that is the only one that can move
        move_from_index = min(
            ring
            for ring, value in enumerate(visualizer)
            if value == move_from.id
        )
        visualizer[move_from_index] = move_to.id
        draw_tower_of_hanoi(visualizer)

if __name__ == "__main__":
    moves = list(move_rings(5))
    print(f"Took {len(moves)} moves")
    for move_from, move_to in moves:
        print(
            f"Move from {move_from.name} to {move_to.name}"
        )
    visualize_tower_movements(5, moves)


Processing a collection of objects, one at a time, with an asynchronous method.

You're basically there, I would say. If the validateSongById function works as  expected, it'll call its callback when it's done, and you then do it again for the next video.

function processVideos(videos, callback) {
    var results = [], i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                results.push(result);
                i++;
                processNext();
            });
        } else {
            callback(results); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}

With this, you call processVideos with the videos array and a callback. The callback is called with a new array of all the results.

Alternatively, you can attach the result to the video-object directly, so the video and the result are tied together:

function processVideos(videos, callback) {
    var i = 0;
    function processNext() {
        if(i < videos.length) {
            validateSongById(videos[i].videoId, function (result) {
                videos[i].result = result;
                i++;
                processNext();
            });
        } else {
            callback(); // when called, all the videos have been processed
        }
    }
    processNext(); // start the processing
}


Looks fine, except for polluting the namespace, you could consider using a self executing anonymous function.

javascript:(function(){x=document.createElement("script");x.src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"; document.getElementsByTagName("head")[0].appendChild(x);copy(1);})();


Generating the sequence of the digits that appear in the sequence of natural numbers

The one where you return a generator is easier to read were it the case that there was only one for. Also, as OP pointed out, the associativity of nested for loops is not what you'd expect in Python.

The top one may be slightly easier to read for some people; it would be MUCH easier to read if there were comments or if the variables were semantically named, and the indented structure allows for comments much better. With semantically-named variables, the first version is easier to read; I'd only use single-letter variable names as the pattern in list comprehensions.


This kind of navigation is usually referred to as tabs or tabbed navigation. There are loads of ready scripts on the net for this - for exampe - since you are using jQuery - jQuery UI. But since this is really a quite trivial functionality, it's quite okay to implement it yourself.

To make the implementation cleaner, you can add a direct reference to the matching panel in the link. I would use the href attribute and refer to the panel using a URL hash. This has the advantage, that it will work without JavaScript or CSS by scrolling to the chosen panel.

You can drop the ids on the links and use a direct reference to them in the function.

1

2

Consider using the CSS :target pseudo class for the functionality:

.panel { display: none; }
.panel:target { display: block; }

And add JavaScript, for browsers that don't support it and to set the classes:

$("#type-select li a").click(function(){return switchType(this)});

function switchType(link){
    var hashPos = link.href.indexOf("#");
    if (hashPos >= 0) {
      // Parsing out the hash and removing '#', in case the href
      // attribute contains a complete URL, and in case some other
      // method than a CSS selector is used to find the panel
      var panelId = link.href.substring(hashPos + 1);

      $("#type-select li a").removeClass("selected-type");
      $(link).addClass("selected-type");
      $(".panel").removeClass("selected-panel");
      $("#" + panelId).addClass("selected-panel");
    }
    return false;
}

Don't forget to return false so the the default action of the link (which will lead to unnecessary scrolling) is canceled.


Copying and pasting from MS Project to MS Excel

A few things here:

Read this. Its lists things to do when copying large amounts of data
Did you set Application.Calculation = xlCalculationManual? Your manually calling Calculate, but you never turn off autocalcualtion.
Did you set Application.ScreenUpdating = FALSE? That can speed things up.


First, I don't quite understand what you mean with not using repeat-until, because in order to split string you have to use some kind of loop.

I assume that you want to have some speed improvements of your code.

If you are not changing string parameters passed to routine you should declare them as const parameters to make call run faster

function Split(const Texto, Delimitador: string): TSarray;

You are reserving way too much memory with SetLength(Result, Length(Aux)); You can freely increase length of resulting array as you go SetLength(Result, Length(Result) + 1); and it will also run faster.

And finally, copying string you are splitting and then deleting parts of the string is not optimal implementation. You should be using overloaded version of Pos function where third argument is offset from which it starts searching, and eliminate Aux string completely.

Also, using o as variable name is not recommended because it can easily be misread as 0, so I replaced it with i, that is commonly used as index variable.

So final code with all optimizations implemented might look like this:

function Split(const Texto, Delimitador: string): TSarray;
var
  i: integer;
  Len: integer;
  PosStart: integer;
  PosDel: integer;
begin
  i := 0;
  SetLength(Result, 1);
  Len := Length(Delimitador);
  PosStart := 1;
  PosDel := Pos(Delimitador, Texto);
  while PosDel > 0 do
    begin
      Result[i] := Copy(Texto, PosStart, PosDel - PosStart);
      PosStart := PosDel + Len;
      PosDel := Pos(Delimitador, Texto, PosStart);
      inc(i);
      SetLength(Result, i + 1);
    end;
  Result[i] := Copy(Texto, PosStart, Length(Texto));
end;


Finding cointegrated pair with minimal t-score

1. Review

As Mathias Ettinger points out in comments, it is hard to review this code because we have no idea what the global variables stockList, linear_model, data, datesIterable, startTrain, endTrain, ts, hurst, pairsOnlyStocks and pairs mean.
There's no docstring. What does this function do? What parameters does it take? What does it return? What side effects does it cause?
Code that depends on global variables is hard to understand, hard to test, and hard to parallelize. It would be better to turns some of these variables into function parameters, or into attributes on objects belonging to a class for which findMinimal is a method.
The code filters stockList on i[0] != stock to get stockListLocal. But then it iterates over stockListLocal and filters again on the same condition. This is wasted work.
Each time findMinimal is called, it looks at all the stocks and filters on i[1] == industry. If you maintained a list of stocks by industry then you would could save a lot of work.
pairsOnlyStocks seems to be a list (it has an append method). Lists do not have an efficient membership test: Python has to compare the item against each list member in turn. So (stockPair,stock) not in pairsOnlyStocks will be slow. It would be better to use a set.
minimalTscore starts at zero, which requires the code to have a special case if minimalTscore == 0:. Better to use Python's built-in min function and avoid the special case.
Instead of indexing:

stock = tup[0]
industry = tup[1]

use tuple assignment:

stock, industry, *_ = tup

But note that this only works in Python 3. In Python 2 you can write:

stock, industry = tup[:2]

and I think this is still clearer than indexing.
Similarly, instead of:

cadf = ts.adfuller(residuals)

use tuple assignment with wildcards:

score, _, _, _, critical_values, *_ = ts.adfuller(residuals)

There's duplicated code of the form:

data[stock][datesIterable[startTrain:endTrain]]

Putting this in a function would reduce duplication and make the code easier to follow, and it would be another place to add a docstring.
Instead of:

.reshape(len(X),1)

write:

.reshape(-1, 1)

The computation of residuals:

Y - beta_hr*X - alpha

suggests that X and Y are already NumPy arrays and so you don't need to call np.array on them.
The array Y gets computed each again for each stock in the list. It could be computed just once by moving it out of the loop.
The arbitrary values '1%' and 0.4 should be given names and documented, for example by turning then into optional function parameters.

2. Revised code

This code implements some of the suggestions above:

def stock_data(stock):
    """Return stock data for [explanation here]."""
    return data[stock][datesIterable[startTrain:endTrain]]

def add_best_pair(stock_tuple, significance='1%', max_hurst_exponent=0.4):
    """Given a tuple (stock0, industry, ...), find the tuple (stock1,
    industry, ...) in the global stocks such that the pair
    (stock0, stock1) has the smallest Augmented Dickey-Fuller score
    among all such pairs, and add it to the global pairs if not
    already present in either order.

    Optional parameter significance gives the required significance
    level for the Augmented Dickey-Fuller test, and max_hurst_exponent
    gives the maximum Hurst exponent for the autocorrelations of the
    residuals.

    """
    stock0, industry0, *_ = stock_tuple
    Y = stock_data(stock0)
    clf = linear_model.LinearRegression()
    def scores():
        for stock1, industry1, *_ in stocks:
            if industry0 == industry1 and stock0 != stock1:
                X = stock_data(stock1)
                clf.fit(X.reshape(-1, 1), Y.reshape(-1, 1))
                beta_hr = clf.coef_[0]
                alpha = clf.intercept_[0]
                residuals = Y - beta_hr*X - alpha
                score, _, _, _, critical_values, *_ = ts.adfuller(residuals)
                if (score <= critical_values[significance]
                    and hurst(residuals) <= max_hurst_exponent):
                    yield score, stock1
    try:
        _, stock1 = min(scores())
    except ValueError:
        # None of the candidate pairs passed the statistical tests.
        return
    if stock1, stock0 not in pairs_set:
        stock_pair = stock0, stock1
        pairs.append(stock_pair)
        pairs_set.add(stock_pair)

3. Performance

It's hard to see how to implement this without carrying out the linear regression and Augmented Dickey-Fuller test on all pairs of stocks in each industry. But here are some ideas on speeding it up:

Are the statistical tests symmetric? That is, do we expect to get the same score when comparing stock A with stock B as we do when we compare stock B with stock A? If so, it would be possible to cache the score computed for (A, B) and look it up when computing (B, A). That would save half the work.
It might be possible to use a rough test to quickly reject pairs of stocks that won't pass the statistical tests. For example, you could start by testing daily/weekly/monthly averages, and only if those test pass do you go on to test the high-resolution data.
It might be straightforward to parallelize the computation of statistical tests, using concurrent.futures.ThreadPoolExecutor in Python 3, or the concurrent.futures backport in Python 2.


Flask route to pull data from database for getJSON to process

I don't really get the purpose of the get_db function. Why not simply initialize the database at the very beginning like so:

db = connect_db()

And then use db in failed_access directly. It seems you wanted to do lazy initialization, but is it really worth it? Sooner or later, the database will be used anyway. Initializing upfront is straightforward, simple, and less error prone.


Rather than memoizing the applicable portion of Pascal's triangle, you could calculate the value much faster either along the row or along the diagonal.

Let \$n\$ represent the row and \$k\$ represent the column.  We know that \$\tbinom{n}{0}=1\$ and \$\tbinom{1}{k} = k\$.  To compute the diagonal containing the elements \$\tbinom{n}{0}\$, \$\tbinom{n+1}{1}\$, \$\tbinom{n+2}{2}\$, \$...\$, we can use the formula

$$
{n+k\choose k}= {n+k-1\choose k-1}\times \frac{n+k}{k}, ~ k > 0.
$$

To calculate the diagonal ending at \$\tbinom{7}{2}\$, the fractions are \$\tfrac{6}{1}\$, \$\tfrac{7}{2}\$, and the elements are

$$
\begin{align*}
\tbinom{5}{0}&=1,\\
\tbinom{6}{1}&=\tbinom{5}{0}\times\tfrac{6}{1}=1\times\tfrac{6}{1}=6,\\
\tbinom{7}{2}&=\tbinom{6}{1}\times\tfrac{7}{2}=6\times\tfrac{7}{2}=21.\\
\end{align*}
$$

Looking up on the table to verify, \$pascal(7,2) = 21\$.

Applying this,

def pascal(row, column):
    """
    >>> pascal(0, 0)
    1
    >>> pascal(5, 4)
    5
    >>> pascal(0, 1)
    0
    """
    if column == 0:
        return 1
    if row == 0:
        return column
    return (row * pascal(row-1, column-1)) / column

Other things you may want to consider are recognizing that there are bounds.  column and row must be positive and column is bounded to row+1.

Indexing tricks on the column value could be employed to reduce the amount of calculations on the diagonal.

When a control structure interrupts the flow of a program like return does in your program, do not use elif or else.  This helps with readability (less of the control path to keep track of and reduces indentation on else) and improves maintainability.  Semantically both are equivalent, but in larger codebases, multiple control paths become a pain.


Join strings from a List while also formating them

String.Join can work with IEnumerable<T> so its not necessary to pass list to it. Same goes for foreach: you do not have to call ToList() at the end of your first query, you can loop through initial enumeration.
With LINQ you can join strings like that:

//you can call `ToList()` at the end, if you need to cache query results, but you dont have to
var fields = db.sda(sql).Rows.OfType<DataRow>().Select(dr => dr.Field<string>("txt"));
//you can merge this Select with the previous one, if you are not going to re-use `fields` enumeration
var ou = fields.Select(f => "OU=" + f);
var dc = someOtherFields.Select(f => "DC=" + f);

var result = String.Join(",", ou.Concat(dc));


This strictly depends on the use case. If your list:

Doesn't change
Holds a lot of data
Is being searched many times
And you don't care about where the element is

Then it may be worth keeping a cached sorted copy of the list and using Arrays.binarySearch() on it.

If those conditions are not met, then you're better off just doing a linear search. Of course you can't go lower than O(n) time, because you have to check every element if the list is not sorted.


Merging multiple sorted arrays into one sorted array

The built-in facilities should take care of this for you.
You can just merge them with concat and then use Array's sort method, which takes an optional custom comparator (in your case, "compare by offset").  This should run in O(n log(n)):
function merge(arrays) {
  return arrays.reduce((m,x) => m.concat(x), [])
               .sort((a,b) => a.offset - b.offset);
}

NOTE: This doesn't take full advantage of the fact that the individual arrays are already sorted (which will give an O(n) solution), but it's so much simpler it's worth checking if it meets your needs before optimizing further.
UPDATE
I went ahead and did a rewrite with some guesses at micro-optimizations that might help (or might not).  Try it on your sample data and see what happens.
The code is a bit more compact than your original, but still not what I consider highly readable.  I had to sacrifice some readability to write this in an optimized, procedural way:
function merge(arrays) {

  var indexes = Array(arrays.length).fill(0);
  var result  = [];
  var minIndex, minValue, minObject; // for minByOffset method

  const totalLength    = arrays.reduce((sum, arr) => sum + arr.length, 0);
  const infiniteOffset = {offset: Infinity};
  const nextUnusedElm  = (arr,i) => arr[indexes[i]] || infiniteOffset;

  while (result.length < totalLength) {
    var candidates = arrays.map(nextUnusedElm);
    minByOffset(candidates);
    indexes[minIndex]++;
    result.push(minObject);
  }

  return result;

  function minByOffset(arr) {
    minValue = Infinity;
    arr.forEach((x,i) => {
      if (x.offset >= minValue) return;
      minIndex = i;
      minObject = x;
      minValue = x.offset;
    });
  }
}

A final optimization you could make (again, it may or may not have much of an effect) is to remove an array once all of its elements have been used up.  That is, restructure the code to avoid some unnecessary comparisons.  In your code, it would avoid:
if (state[i] >= arrays[i].length) {

In my version, it would avoid:
arr[indexes[i]] || infiniteOffset;

That is, an extra array lookup and a comparison inside the loop.  These are fast operations, so the optimization may not matter...


Use filter_var_array on whole array, or inside iteration

Is this really the bottleneck in you application? If not choose the readable one. See Effective Java, 2nd Edition, Item 55: Optimize judiciously I know that this is a Java book but this chapter (and many others) is useful for every developer.

Some other notes:

I'd call the filtered variable something which shows that the data has been filtered, like $filtered_row. It would improve readability and help maintainers.
The code prints the first name and the last name without any separator character. I'd consider printing a separator there:

print '<p>' . $sql_row['first_name'] . ' ' . $sql_row['last_name'] . '</p>';

If you use only the first_name and the last_name maybe you should only filter these fields not the whole array. (I don't know whether it contains other values or not.)
Consider memory usage too. If I'm right the first one have to store the input and output array in the memory during the filtering which needs two times of the array size of memory temporarily. In the second case it's much smaller since it filters only one row at a time so it needs memory for the array once and two times of the size of a row during the filtering.


Writing it like this makes it look the render returns a meaningful value that is then returned by create and used by the code that calls create, which is not the case. So instead I would write:

render is_admin? ? 'new_admin' : 'new'
return

This makes it clear that render is solely used for its side effects and create does not return a value (other than nil).


I'm not sure of everything (worked with notepad) but:

protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e)
{
    using (NoavaranModel.NoavaranEntities1 dbContext = new NoavaranModel.NoavaranEntities1())
    {
        var userId = int.Parse(Session["UserId"].ToString());

        var user = dbContext.Users.FirstOrDefault(p => p.UserId == userId);
        var countOfSms = user.CountOfSMS.Value;
        var j = 0;
        foreach (var row in grdStudents.Rows)
        {
            var cells = row.Cells;
            var MobileNumbers = cells[2].Text;
            var stID = int.Parse(cells[0].Text);

            var student = dbContext.Students.FirstOrDefault(p => p.Id == stID && !p.IsRecivedSMS);

            var Ckbox = (CheckBox)row.FindControl("chkSelectStudents");
            if (Ckbox.Checked)
            {
                j++;
                if (j <= countOfSms) {
                    Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);
                    student.IsRecivedSMS = true;

                    user.CountOfSMS = countOfSms - 1;
                }
            }
        }

        dbContext.SaveChanges();
        ListBox1.Items.Add(sendCount.ToString());
    }
}

This is a cleaner version of your code with less query (the first was unneccesary) and inside the loop you are making a lot of small query which can be really bad but first you have to modify your code to not work directly with the context in you page code but through an interface (first iterate through the rows and get all data then pass them to the worker (which can work with the context) and return the result & update the UI).


Function to test for different conditions in input data

Similar to @Peilonrayz, I would map each of the comparators to a function, but I'd go further.

Function design: check_if_condition_was_met(…) is an awkward name, partly because of the unusual use of past tense.  But why make it so wordy?  Couldn't you just call it verify(…)?

Furthermore, it would be customary to put the condition parameter first, and the row second.  It would certainly read more naturally in English, especially after the function rename.  Also, based on the observation that verify(condition) could be considered as a test, it's a general functional-programming principle that the condition parameter should be considered more tightly associated with the verification process and should therefore be put first.
Use all(…):  You want to express the idea that a function should return True if all of the conditions must be met, and False if any condition fails.  You can do that using all() with a generator expression.   It's a lot less cumbersome than your condition_met, for, continue, and break.  The entire function can be simplified down to a single expression!
Naming:  I think that "key" and "val" are not quite descriptive enough.  I suggest the following renamings:

key → comparator
val → criteria
condition_key → key
condition_val → desired_val

I'm also skeptical about some of the behaviour when given anomalous input:

Why are there int(…) casts with 'min' and 'max'?  Is it for parsing strings as numbers?  None of your example cases needs such parsing, though.  Is it for truncating floats towards zero?  Probably not, but it might have that unintended effect, if the thresholds or data are already numeric.
What happens if the row is missing a key that is specified in the condition?  Maybe it's not a concern to you, but it might be more appropriate to have the function return False rather than raise a KeyError, as your code does?

Consider writing doctests to explain what the function does.  This is a situation where examples are more expressive than words.

Suggested solution

COMPARATORS = {
    'in':       lambda v, lst: v in lst,
    'not in':   lambda v, lst: v not in lst,
    'min':      lambda v, n: (v is not None) and (v >= n),
    'max':      lambda v, n: (v is not None) and (v <= n),
}

def verify(condition, row):
    """
    Verify that the specified criteria are all true for the given row.

    >>> rows = [
    ...     {'Flag1':'Y', 'Flag2':'Canada',        'Number':35},
    ...     {'Flag1':'Y', 'Flag2':'United States', 'Number':35},
    ...     {'Flag1':'N', 'Flag2':'United States', 'Number':35},
    ...     {'Flag1':'N', 'Flag2':'England',       'Number':35},
    ...     {'Flag1':'N', 'Flag2':'Canada',        'Number':35},
    ...     {'Flag1':'N', 'Flag2':'Canada',        'Number':5},
    ... ]

    >>> [verify({'in': {'Flag1': ['N'], 'Flag2': ['United States']}}, r)
    ...  for r in rows]
    [False, False, True, False, False, False]

    >>> [verify({'not in': {'Flag1': ['Y']}, 'min': {'Number': 7}}, r)
    ...  for r in rows]
    [False, False, True, True, True, False]

    >>> [verify({'not in': {'Blah': ['whatever']}}, r) for r in rows]
    [True, True, True, True, True, True]
    """
    return all(
        all(
            COMPARATORS[comparator](row.get(key), desired_val)
            for key, desired_val in criteria.iteritems()
        )
        for comparator, criteria in condition.iteritems()
    )


Most of my comments on your previous question apply here too, so I'll just summarize them quickly:

Debugging code that you forgot to remove.
Docstring written from the implementer's point of view.
Variable name respelled to avoid shadowing a built-in.
Test case not organized into a unit test.
Test case not very stringent (just 9 items).

In addition:

Given an array of length n, your algorithm makes n passes over the array, and in pass i it finds the ith largest item in the array (which at that point in the algorithm is the largest item in the first n − i positions) and swaps it into the position n − i − 1. This ought to be simple, but it's implemented in a very complex way, via the list val_list of indexes.

Here's a much simpler implementation:

def selection_sort(seq):
    """Sort the mutable sequence seq in place and return it."""
    for i in reversed(range(len(seq))):
        # Find the index of greatest item in seq[:i+1].
        greatest = 0
        for j in range(1, i + 1):
            if seq[j] > seq[greatest]:
                greatest = j
        seq[i], seq[greatest] = seq[greatest], seq[i]
    return seq

Note that I've avoided testing seq[greatest] > seq[i] before doing the swap, because I know that the only way this condition can fail is if greatest == i, and then the swap has no effect. So it's simplest to skip the test.

I could simplify this still further using Python's built-in function max:

def selection_sort(seq):
    """Sort the mutable sequence seq in place and return it."""
    for i in reversed(range(len(seq))):
        greatest = max(range(i + 1), key=seq.__getitem__)
        seq[i], seq[greatest] = seq[greatest], seq[i]
    return seq

But this seems like it's avoiding the spirit of the exercise: I mean, if I can use max, then why not sorted?


Invoking subscribers of an action in parallel c#

I think that unless benchmarking proves otherwise, you should simply OnData?.BeginInvoke() and just let the thread pool handle it for you.


for comparison

Here are some other ways I've found to parse indentation sensitive language:

Use Text.Parsec.Indent Here is a blog post containing an example: (link)
Have a look at the language-python package. It's lexer is built using alex: (link)
Purescript handles indentation via the mark, checkIndentation, indented and same functions: (link) Grep the rest of the source code for these functions to see how they are used. Its lexer defines a Indent token (link) but from what I can tell it is never returned, i.e. see (link). The indentation level is kept track of by the parser (link) via the mark function.

returning a list of tokens?

I'm not sure there is a lot of value in parsers which return [PositionedToken] except, perhaps, for testing purposes.

Most of the time you want to run a token parser incrementally, but parseTokens has to consume the entire file before it can return anything.

There should be a function which just returns the next token. This will come in handy in conjunction with the next comment I have...

handling dedents at eof

I would find another way to handle implicit dedents at the end of the file. I'm sure this can be handled at the grammar level. The code to add them is extremely messy - don't you agree?

Have a look at how the language-python package does it:

https://github.com/bjpop/language-python/blob/master/src/Language/Python/Version2/Parser/Lexer.x#L229-L242

The function lexToken returns just a single token.
The lexer has state, so when it reaches EOF it checks the current indentation level. If the indentation level is > 1, it decrements it and returns a dedentToken. Otherwise it returns an EOF token.


Copy a directory from source to destination

Overall, it is good, but I would apply the following changes:

Use const for read only function parameters. All the char* pointers you are passing to the functions are actually only read from, so you should use const char* to document that.
Personally, I'm not a big fan of returning -1, 0, 1, etc. This kind of error codes are popular with UNIX system calls, but I find them rather error prone. It is easy to make a mistake with the return value of a function if you don't carefully read the documentation. If the function has only two possible outcomes, success and failure, then include <stdbool.h> and return true or false. There is no chance of misunderstanding it this way.
A few magic numbers that could be named constants. For example, why did you choose 512 and 256 for buffer sizes? That is not obvious. Named constants would be better for these cases. Also, even though the 0700 constant on mkdir is well known for UNIX users, it might not be so for others less familiar with the architecture. I would also make that a named constant.
I suggest keeping the parameter names on function prototypes. In int copyFile(char*, char*); which one is the source file and which is the dest? Can't tell for sure just by reading the function prototype. Parameter names would make that clear without having to look at the implementation.
I suspect you have too many #includes for such a tiny program. <time.h> is certainly not used here. Make sure to only import the dependencies that your program actually requires.
A few system calls are not being checked for failure, so your program is not as robust as it could be.


This problem is an instance of Integer Linear Programming. ILP is NP-hard, so an algorithm to find the optimal solution will not be much faster than brute-force. However, a common technique to find an approximate optimum is to solve it as a Linear Programming problem without the integer restrictions, then round the results up or down as necessary. Fortunately, many libraries exist to solve non-integer LP quite efficiently.


Note: I checked binary tree pruning and the structure of class TreeNode is not modifiable as I expected:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

It's possible to shorten your code with constraints of the class, your method containsOne is the following:

private boolean containsOne(TreeNode node) {
    if (node == null) return false;
    if (node.val == 1) return true;
    return containsOne(node.left) || containsOne(node.right);
}

Because the third line will be executed when the condition node.val == 1 is false put directly this condition in the or expression in the third line:

private static boolean containsOne(TreeNode node) {
    if (node == null) return false;
    return node.val == 1 || containsOne(node.left) || containsOne(node.right);
}

About your method PruneTree you can shorten the following lines inside the method:

if (node.left != null && !containsOne(node.left)) {
    node.left = null;
}
if (node.right != null && !containsOne(node.right)) {
    node.right = null;
}
if (node.left != null) {
    queue.offer(node.left);
}
if (node.right != null) {
    queue.offer(node.right);
}

The code can be rewritten like below, two equal blocks and not so elegant to see but the original structure in the site cannot be modified, so I haven't thought about other alternatives:

if (node.left != null) {
    if (!containsOne(node.left)) { node.left = null; }
    else { queue.offer(node.left); }
}

if (node.right != null) {
    if (!containsOne(node.right)) { node.right = null; }
    else { queue.offer(node.right); }
}

I checked the code on the site passing all tests.


I was able to improve on my previous code by making sure all the return statements were returning the same type of response (String / StatusCode). This allowed the 20 methods calling this one must smaller since I didn't have to check what response contain.

private function getSIS($url, $session, Application $app)
{
    if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
    {
        $client = new Client(['base_uri' => $app['fomservices']['sis']]);
        $token = 234561;

        // Calling the external API which multiple errors could occur.
        try {
            if (!empty($session)) {
                $response = $client->request('GET', $url.'/'.$session, [
                    'headers' => [
                        'token' => $token
                    ]
                ]);
            } else {
                $response = $client->request('GET', $url, [
                    'headers' => [
                        'token' => $token
                    ]
                ]);
            }
            return new Response($response->getBody(), 200);
        } catch (ClientException $e) {
            $response = $e->getResponse();
            return new Response($response->getBody()->getContents(), $response->getStatusCode());
        } catch (ServerException $e) {
            $response = $e->getResponse();
            return new Response($response->getBody()->getContents(), $response->getStatusCode());
        } catch (BadResponseException $e){
            $response = $e->getResponse();
            return new Response($response->getBody()->getContents(), $response->getStatusCode());
        }
    }

    return new Response("You don't have permission to access this!", 401);
}

public function getMedAction(Application $app)
{
    return $this->getSIS('med', '', $app);
}

public function getMedSessionAction($session, Application $app)
{
    return $this->getSIS('med', $session, $app);
}


"Remove Friends" problem time efficiency too slow

Hint: The problem statement asks you to remove friends from the end of the list as necessary. Think carefully about this.

   You don't actually have to remove the remaining friends to delete. Instead, just don't print them.

 Change your while and for to the following code.

Spoiler tags and code blocks don't interact nicely, so the solution code is base 64 encoded.

Zm9yIChpbnQgaiA9IDAsIGptYXggPSBpbnB1dExpc3Quc2l6ZSgpIC0gZnJpZW5kc0RlbGV0ZTsgaiA8IGptYXg7IGorKykgew0KICAgICBTeXN0ZW0ub3V0LnByaW50KGlucHV0TGlzdC5nZXQoaikgKyAiICIpOw0KfQ==

I believe @EmanuelePaolini is correct in that you're likely getting TLE because of I/O. You're using Scanner, which is way too slow. Try a different input method.

   You can try switching to BufferedReader. String.split() is still slow, so you can combine it with StringTokenizer. Here's a sample on ideone.

Encoded:

c3RhdGljIEJ1ZmZlcmVkUmVhZGVyIGJyID0gbmV3IEJ1ZmZlcmVkUmVhZGVyKG5ldyBJbnB1dFN0cmVhbVJlYWRlcihTeXN0ZW0uaW4pKTsNCnN0YXRpYyBTdHJpbmdUb2tlbml6ZXIgc3QgPSBuZXcgU3RyaW5nVG9rZW5pemVyKCIiKTsNCnN0YXRpYyBpbnQgbmV4dEludCgpIHRocm93cyBJT0V4Y2VwdGlvbiB7DQoJd2hpbGUgKCFzdC5oYXNNb3JlVG9rZW5zKCkpDQoJCXN0ID0gbmV3IFN0cmluZ1Rva2VuaXplcihici5yZWFkTGluZSgpKTsNCglyZXR1cm4gSW50ZWdlci5wYXJzZUludChzdC5uZXh0VG9rZW4oKSk7DQp9


JavaScript Tic Tac Toe Win Checker is Wet

I think the nicest thing to do is to split your task into three bits, essentially you want to see if a row, column or diagonal has all the entries the same.

A row, column or diagonal can all be thought of just as a (1D) array.

In fact, these things are all the 'lines' (pictorially) that you can find in a 2D array (which span the whole array).

Now given a 2D array A, there's several ways to define a line, for instance the line which corresponds to the second row we can say is the pairs (i, j) such that i === 1 (and j can be anything). Similarly the left diagonal is the pairs (i, j) such that i === j.

Ok so I want to think of a line as a function, for instance I will think of the second row as the function

(i, j) => i === 1

OK, now given a line (which we represent as a function), I want to extract the elements of A which lie on that line, so I should traverse A, and for each element (i, j) I check if that element is in my line (i.e. if my function returns true for it) and if so include it in my result.

How to do this? Well I /want/ to be able to loop through a 2D array gracefully, sadly we can't do that in JS, so I'll just look at each row in turn, determine which elements of that row are in my line and keep them, something like.

function getSectionOf2DArray(arr, lineFunc) {
    return arr.map((row, i) => row.filter((_, j) => lineFunc(i, j)));
}

So now I have a 2D array still, the element at position i of the array is an array consisting of the things in row i which are in my line. If I flatten it I'll have the array of things in my line. I'm not sure if you're using node or are in the browser, so I'll write a flatten to be safe.

function getSectionOf2DArray(arr, sectionFunc) {
    return Array.prototype.concat.apply(
        [],
        arr.map((row, i) => row.filter((_, j) => sectionFunc(i, j)))
    );
}

Nearly there now, let me define the lines of a 2D array.

First the rows, well given a 2D array A, these are just the things (i, j) => i === k for k up to the length of the array.

const rowLines = array =>
    Array(array.length)
        .fill(0)
        .map((_, k) => (i, j) => i === k);

Now the columns, similar story just with a slight reversal, now it's (i, j) => j === k

const colLines = array =>
    Array(array.length)
        .fill(0)
        .map((_, k) => (i, j) => j === k);

Finally the diagonals, the left diagonal (i.e. starting in the top left) is (i, j) => i === j, while the right diagonal is (i, j) => i + j === A.length - 1

const leftDiag = array => (i, j) => i === j;
const rightDiag = array => (i, j) => i + j === array.length - 1;

(I have made leftDiag continue to be a function defined in terms of array just for consistency, it will make our life nicer later).

Great, so now if we do

const ourLines = array =>
    rowLines(array)
        .concat(colLines(array))
        .concat(leftDiag(array))
        .concat(rightDiag(array));

Then ourLines is a function which takes an array and returns an array of lines (aka functions).

Now we just need to define a function which says whether an 'evaluated' (as in I have the actual elements rather than the function) line corresponds to a win, this is easy, it's just if all the elements are the same and not equal to undefined. If all the elements are the same then when we turn the array into a set it will have just one element

const win = evalLine => new Set(evalLine).size === 1 && evalLine [0] !== undefined;

OK, now we should just go through our lines, get the actual array of elements in A they correspond to, and check if any is a win.

const winResults = array =>
    ourLines(array).map(line => win(getSectionOf2DArray(array, line)));

const isThereAWin = array => winResults(array).includes(true);

In summary,

const winChecker = squares => {
    const getSectionOf2DArray = (arr, sectionFunc) =>
        Array.prototype.concat.apply(
            [],
            arr.map((row, i) => row.filter((_, j) => sectionFunc(i, j)))
        );

    const rowLines = array => Array(array.length).fill(0).map((_, k) => (i, j) => i === k);

    const colLines = array => Array(array.length).fill(0).map((_, k) => (i, j) => j === k);

    const leftDiag = array => (i, j) => i === j;
    const rightDiag = array => (i, j) => i + j === array.length - 1;

    const ourLines = array =>
        rowLines(array)
           .concat(colLines(array))
           .concat(leftDiag(array))
           .concat(rightDiag(array));

    const win = evalLine => new Set(evalLine).size === 1 && evalLine[0] !== undefined;

    const winResults = array => ourLines(array).map(line => win(getSectionOf2DArray(array, line)));

    const isThereAWin = array => winResults(array).includes(true);

    return isThereAWin(squares);
};

I hope you agree this pattern is nice. There are ways to write more concise things for your specific use case but this is simple and extendable.


Long running in-process Publish/Subscribe class

It seems that you have a global static logger methods. It is not a good practice, as you're loosing the possibility to tune logging levels for different areas of your application (e.g. setting log level for EmailMessageNotification to DEBUG while keeping INFO level everywhere else. I recommend to follow the logging patterns suggested for your logging framework (see Creating loggers for NLog for example).
The code is not thread-safe, so you may get issues if your application publishes, subscribes or unsubscribes in different threads. Use either locking around Observers collection or ConcurrentDictionary.
Fatal logging level should be used only when the application encounters a critical error after which it usually cannot continue to run. In your case I would suggest to use Error log level when email cannot be sent.
NotificationService is static, which means that you will have a strong dependencies in your code on this class. I suggest to introduce IoC framework (check out Autofac or StructureMap).
The response of INotification.Notify(string, string) is not used, so it can be void.
Your current code requires spinning up threads per each observer per each notification. I suggest to switch to asynchronous processing model, changing the return type of INotification.Notify(string, string) to Task.
Most likely you would want to wrap the notification of each listener in try..catch to avoid side effects when buggy INotification subscribes to your service

As a result:

INotification:

public interface INotification
{
    string NotificationName { get; }

    Task NotifyAsync(string title, string requester);
}

EmailMessageNotification:

public class EmailMessageNotification : INotification
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    public EmailMessageNotification(EmailNotificationSettingsService settings)
    {
        EmailNotificationSettings = settings;
    }

    private EmailNotificationSettingsService EmailNotificationSettings { get; }

    public string NotificationName => "EmailMessageNotification";

    public async Task NotifyAsync(string title, string requester)
    {
        var configuration = GetConfiguration();
        if (!ValidateConfiguration(configuration))
        {
            return;
        }

        var message = new MailMessage
        {
            IsBodyHtml = true,
            To = { new MailAddress(configuration.RecipientEmail) },
            Body = $"User {requester} has requested {title}!",
            From = new MailAddress(configuration.EmailUsername),
            Subject = $"New Request for {title}!"
        };

        try
        {
            using (var smtp = new SmtpClient(configuration.EmailHost, configuration.EmailPort))
            {
                smtp.Credentials = new NetworkCredential(configuration.EmailUsername, configuration.EmailPassword);
                smtp.EnableSsl = configuration.Ssl;
                await smtp.SendMailAsync(message).ConfigureAwait(false);
            }
        }
        catch (SmtpException smtp)
        {
            logger.Error(smtp);
        }
        catch (Exception e)
        {
            logger.Error(e);
        }
    }

    private EmailNotificationSettings GetConfiguration()
    {
        throw new NotImplementedException();
    }

    private bool ValidateConfiguration(EmailNotificationSettings settings)
    {
        throw new NotImplementedException();
    }
}

NotificationService:

public interface INotificationService
{
    void Publish(string title, string requester);
    void Subscribe(INotification notification);
    void UnSubscribe(INotification notification);
}

public class NotificationService : INotificationService
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    private ConcurrentDictionary<string, INotification> Observers { get; } = new ConcurrentDictionary<string, INotification>();

    private static async Task NotifyAsync(INotification notification, string title, string requester)
    {
        try
        {
            await notification.NotifyAsync(title, requester).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            logger.Error(ex, $"Notification '{notification.NotificationName}' failed with exception");
        }
    }

    public async void Publish(string title, string requester)
    {
        IEnumerable<Task> notificationTasks = Observers.Values.Select(notification => NotifyAsync(notification, title, requester));

        await Task.WhenAll(notificationTasks).ConfigureAwait(false);
    }

    public void Subscribe(INotification notification)
    {
        Observers.TryAdd(notification.NotificationName, notification);
    }

    public void UnSubscribe(INotification notification)
    {
        Observers.TryRemove(notification.NotificationName, out notification);
    }
}


Responsive horizontal scroll on mouse position

Your project is looking great! But I have a few thoughts on how to improve the clarity of your javascript code:

Unused code

Your window.resize handler doesn't end up doing anything. Functions create a new scope for variables, so since you're redeclaring docWidth and slidesWidth with var, you don't actually affect the initially declared variables. The reason why all your code still works is that the body's width and the slide's width don't actually change when the window is resized. I'm not sure if this is different on mobile or even why the widths aren't changing (maybe it has something to do with your css) but you ought to either change the handler to something like:

$(window).on('resize', function() {
  docWidth = $('body').width();
  slidesWidth = $images.width(); // stay consistent with this variable
  rangeX = slidesWidth - docWidth;
})

Or just remove it to prevent confusion if the widths aren't affected by resizing.

You also don't end up using rangeX in your code. Consider removing it.

More straightforward calculation

I think you could simplify the way you calculate the offset in your document.mousemove handler by eliminating the mousePercent variable:

$(document).on('mousemove', function(e) {
  var mouseX = e.pageX,
    offset = mouseX / docWidth * slidesWidth - mouseX / 2;

  $images.css({
    '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
    'transform': 'translate3d(' + -offset + 'px,0,0)'
  });
});

This way you don't multiply by 100 and then divide by it right after, and you also have fewer variables to worry about.

Unnecessary functionality

You don't use the 3d aspect of translate so why not just use the 2d version:

$images.css({
  '-o-transform': 'translate(' + -offset + 'px, 0)', // opera 11.5
  '-ms-transform': 'translate(' + -offset + 'px, 0)', // IE9
  '-moz-transform': 'translate(' + -offset + 'px, 0)', // firefox 3.5-15
  '-webkit-transform': 'translate(' + -offset + 'px, 0)',
  'transform': 'translate(' + -offset + 'px,0)'
});

More concise and direct jquery syntax

Another option would be to use jquery's built in methods for creating events instead of using on:

$(document).ready(function() {
  var docWidth = $('body').width(),
    slidesWidth = $('#imgs').width(),
    rangeX = slidesWidth - docWidth,
    $images = $('#imgs');

  $(window).resize(function() {
    var docWidth = $('body').width(),
      slidesWidth = $('#imgs').width(),
      rangeX = slidesWidth - docWidth;
  })

  $(document).mousemove(function(e) {
    var mouseX = e.pageX,
      percentMouse = mouseX * 100 / docWidth,
      offset = percentMouse / 100 * slidesWidth - percentMouse / 200 * docWidth;

    $images.css({
      '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
      'transform': 'translate3d(' + -offset + 'px,0,0)'
    });
  });
});

Once again, great work so far! I wish I could have helped more with the snapping issue. I have a few ideas--mouseenter, jquery.stop().animate()--but none that are fully developed. Good luck figuring it out!


Method to return the lowest filename number not being used

When you don't need indexes or ordering, it is generally a good idea to use a set over a list because its membership testing is more efficient.  That means, use nums = set() instead of nums = [], and use nums.add(...) instead of nums.append(...).  That's all you need to change.

I'm not sure why you are accessing the special method directly.  Why not use unicode(f) instead of f.__unicode__()?

Python has its own version of something that is often called a ternary operator.  Its format is truth_value if some_condition else false_value.  Therefore, you can replace your first if and else blocks with this:

nums.append(int(match[0]) if match else 0)

(It would be nums.add(...) if you decide to use a set.)

and your second if and else blocks with this:

return "" if i == 0 else str(i)


for var i = 5; i <= maxPrime; i += 6 {
    if number % i == 0  || number % (i + 2) == 0 {
        return false
    }
}

We can implement some Swift syntax here:

for i in stride(from:5 through:maxPrime by: 6) {
    if number % i == 0 || number % (i + 2) == 0 {
        return false
    }
}

I don't know how this would compare in terms of performance however.  I suspect it's the same or better however.


Is there any way to stop the lag in this Gif opener?

Your problem may be similar to this one:
https://stackoverflow.com/questions/50904093/gif-animation-in-tkinter-with-pill-flickering-on-every-other-frame
I tried your code on gif which has a 2nd disposal method.
Works, but loops over frames too quickly. GIFs with the 1st disposal method fail.
Also pay attention to the frame delay/frame rate. Different GIFs can have different values.
You can use third party libraries like Pillow to get file information.

from PIL import Image

f = Image.open("tenor.gif")
print(f.info) # duration in ms
print(f.disposal_method)
print(f.n_frames) # number of frames

Output example:
{'version': b'GIF89a', 'background': 140, 'transparency': 140, 'duration': 160, 'extension': (b'NETSCAPE2.0', 795), 'loop': 0}
2
12

You can use some custom label classes.
https://stackoverflow.com/a/43770948/8349697
Consider using the PyQt5 library. I tried some test gifs with QtWidgets, and it works much better than tkinter. PyQt can display animated gifs using QMovie.


My attempt at Dijkstra's Algorithm in Python 3

Those comments are very difficult to read.

j = list(set(j)) #someone warned that the problematic test case gives the same edge many times, so this is to remove duplicates

Format this properly:

# The problematic test case gives the same edge many times,
# so this is to remove duplicates
j = list(set(j))

Then remove fluff:

# Remove duplicates. Helps some test cases.
j = list(set(j))

In this case just remove the first comment, because list(set(...)) is already known to mean deduplicate. And remove the second since it's implied by the fact you've written the code.

j = list(set(j))

Another pair is

a = [] # for input purposes
b = [] # for output purposes

Don't do this. Just call them

descriptive_name_1 = []
descriptive_name_2 = []

so you don't need the comment in the first place.

Then there's q = .... So I wrack my brain thinking about what word contains q. But it turns out you just meant to write num_test_cases. What does that have to do with the letter q?

Worse than that is when you outright lie. What would you expect the variable node to contain? A node, right? Nope - it contains the total number of nodes.

And you write

node = 0

so we expect the total number of nodes to be 0 at that point, right? Nope, you immediately change your mind and write

node, edge = list(map(int, input().strip().split()))

But OK, fine. At least we know what nodes contains, then: multiple nodes, so a list (or other collection) of lengths of nodes.

Nope, it actually means exactly the same thing as node.

A similar comment goes for edge, which should be num_edges.

Then there's adj, which you label "adjacency matrix". Why not just call it adjacency_matrix then? But it's not even a dense matrix like that would imply, it's actually a list of per-node adjacencies, so call it adjacencies.

Then there's starting and start, which are the same thing named differently. Call them start_node or at least be consistent.

Going back to b, you have

b = []

but again this is a lie, because actually

b = shortest(start_node, num_nodes, adjacencies)

So just write that.

distances = shortest(start_node, num_nodes, adjacencies)

For a, initialize it as close to usage as possible and call it edges.

If you write

for j in range(num_edges):

you're misleading me into thinking you're going to use the index. When you're not going to, write

for _ in range(num_edges):

And what's up with that, followed by

for j in edges:

followed by

for j in adjacencies:

Is j just your general "this is a thing" variable? Most people use x, elem and item for that. Instead, write

for _ in range(num_edges):
for edge in edges:
for adjacent in adjacencies:

The middle can be

for start, end in edges:

The comment

#edges are 6

Isn't coherent. Try

# Edges are length 6

Instead, though, don't put this information in shortest - use 1 and multiply out when using the results.

Don't call variables temp. It's a poor name.

You've double-indented the part where you update the neighbours.

Note that

num_nodes, num_edges = list(map(int, input().strip().split()))

is just

num_nodes, num_edges = map(int, input().strip().split())

Why do you do this?

for i in adjacencies[current-1]:
    neigh = i

Just write

for neighbour in adjacencies[current-1]:

And the content can be

for neighbour in adjacencies[current-1]:
    distance[neighbour-1] = min(distance[neighbour-1], distance[current-1] + 1)

Do you not think this whole -1 thing is getting a bit silly? When reading, just decrement the edge values and starting edge correctly:

edges = []
for _ in range(num_edges):
    start, end = map(int, input().strip().split())
    edges.append((start - 1, end - 1))

start_node = int(input()) - 1

while loops and if statements don't need their condition parenthesized, and operators should be spaced properly:

while (len(unique)>0):   # before
while len(unique) > 0:   # after

Then this is better as just while unique.

Don't put spaces before the parentheses in function calls or indexing.

minDist should be min_dist. You can also start with it set to num_nodes, and the same for distance's initialization.

unique is a horrible name, and has nothing to do with the variable's purpose. Try unvisited instead. It can be initialized as

unvisited = [i for i, adj in enumerate(adjacencies) if adj]

distance, unsurprisingly, does not mean distance but instead distances. Fix that.

This code:

min_dist = num_nodes
for i in unvisited:
    if distances[i] <= min_dist:
        min_dist = distances[i]
        distIndex = i
current = distIndex

is just

min_dist = num_nodes
for i in unvisited:
    if distances[i] <= min_dist:
        min_dist = distances[i]
        current = i

and current should be called closest. It is simplifiable to

closest = min(unvisited, key=lambda x: distances[x])

This is faster if you write

closest = min(unvisited, key=distances.__getitem__)

but the difference isn't vital.

One last thing with shortest - rename it to shortest_distances.

Put the rest of the code in a main function.

If you write

def read_pair(decrement):
    x, _, y = input().partition(" ")
    return int(x) - decrement, int(y) - decrement

then you can initialize num_nodes, num_edges and edges with

num_nodes, num_edges = read_pair(0)
edges = [read_pair(1) for i in range(num_edges)]

Note my use of partition instead of split as IMO it's a better description of the operation here.

Then

for adjacent in adjacencies:
    adjacent = list(set(adjacent))

doesn't actually work! adjacent = only affects the local scope! Instead, you want

adjacencies = [list(set(adj)) for adj in adjacencies]

which is even better as

adjacencies = [set() for _ in range(num_nodes)]
for start, end in edges:
    adjacencies[start].add(end)
    adjacencies[end].add(start)

as you never have the large intermediates then, and there's no real point converting back from a set.

This stuff:

distances.remove(0)
for i in range(len(distances)):
    if distances[i] == num_nodes:
        distances[i] = -1
    else:
        distances[i] *= 6
print(" ".join(str(e) for e in distances))

is just

print(*(-1 if i == num_nodes else i * 6 for i in distances if i))

Nice, that seems to have made it fast enough, but more important the code is more readable.

We can improve speed further by avoiding input, using sys.stdin directly to get buffering.

def main(lines):
    def read_pair(decrement):
        x, _, y = next(lines).partition(" ")
        return int(x) - decrement, int(y) - decrement

    ...

main(sys.stdin)

Note that this change is sufficient on its own to beat the time limit: you can apply it to your original code to pass the test. Note also that you shouldn't mix input with next; at least on Python 2 this throws an error saying

ValueError: Mixing iteration and read methods would lose data

Though this error is gone in Python 3, that doesn't leave me feeling good about it.

I'd finish off with

from __future__ import print_function

to make it Python 2 compatible.

from __future__ import print_function

import sys

def shortest_distances(start_node, num_nodes, adjacencies):
    distances = [num_nodes] * num_nodes
    unvisited = [i for i, adj in enumerate(adjacencies) if adj]

    distances[start_node] = 0
    while unvisited:
        closest = min(unvisited, key=distances.__getitem__)
        unvisited.remove(closest)

        # Update the distances of each neighbour
        for neighbour in adjacencies[closest]:
            distances[neighbour] = min(distances[neighbour], distances[closest] + 1)

    return distances

def main(lines):
    def read_pair(decrement):
        x, _, y = next(lines).partition(" ")
        return int(x) - decrement, int(y) - decrement

    num_test_cases = int(next(lines))
    for i in range(num_test_cases):
        num_nodes, num_edges = read_pair(0)
        edges = [read_pair(1) for i in range(num_edges)]
        start_node = int(next(lines)) - 1

        adjacencies = [set() for _ in range(num_nodes)]
        for start, end in edges:
            adjacencies[start].add(end)
            adjacencies[end].add(start)

        distances = shortest_distances(start_node, num_nodes, adjacencies)

        print(*(-1 if i == num_nodes else i * 6 for i in distances if i))

main(sys.stdin)


Generating sequence that uses the previous outcome for the current

Using while would be idiomatic in almost any language. while is basically the way to iterate, uh, while a condition is true. Hence the name - it's practically plain English.

You can postfix the while and save a couple of lines, but that's about it

puts value = value**2 while value < 10000

or use until if you want, but same difference

puts value = value**2 until value >= 10000

If you were dealing with a fixed or known number of iterations, you could do something like

4.times.inject(2) do |memo, _|
  puts memo = memo ** 2
  memo
end

but the whole point here is really that you don't know the number of iterations.


I think your overall approach is sound: read data into a buffer, update the hash, and repeat until the whole file has been processed.

Buffer size may have some impact on performance, so that may be worth experimenting with (I'd probably expose it as a parameter).

Having that said, there are a few odd things going on in your code:

Disposing algorithm is somewhat surprising - it's an argument, so I'd expect the calling code to be responsible for it. If anything, such behavior should be documented. You may also want to provide an overload that allows calling code to disable this - for example, StreamReader and StreamWriter have a constructor that takes a leaveOpen parameter.
Don't call Dispose when you're already using a using statement.
Successive using statements are usually not nested. Personally I think nesting them makes code a little less readable.
stream.Flush() isn't necessary because you're not writing to the stream.
Setting those local variables to null does nothing useful. It doesn't trigger the garbage collector, those variables will go out of scope shortly afterwards anyway, and since they're parameters they're also most likely not the only reference to the object they're referencing.
After removing those unnecessary lines, you can immediately return the result of algorithm.Hash.ToHex() - no need to store it in a local variable. If you do want to use a variable (to ease debugging or to improve readability of the code), then I would declare it as close to where it's used as possible. Currently, it appears at the top, middle and near the end of the method, so you have to look all over the place to see how it's used. That's no big deal for a small method like this, but it's not as easy to understand as it could be.


You are not using any stored data in the RevereseString [sic] object, so you do not actually need to create the object.  Changing reverseStr() to a static method, (optionally private as well) and you can remove RevereseString reverseStr = new RevereseString(); to save one line of code.

There is no need for a midIndex.  You just need to reverse characters until the startIndex and lastIndex meet or cross.  Thus you can remove int midIndex = 0 + (oldArray.length - 0)/2 ; and save another line of code.

Finally, you are not returning a new array; you are returning the original oldArray and assigning that object to newArray.  In other words, as main() finishes, oldArray == newArray is true.  You have reversed the oldArray in place; there is no need for a return value from reverseStr(), so you can eliminate at least another two lines of code.


Yeah, without snprintf and sprintf it gets a bit tedious, but I think this code is actually quite clear. You use your horizontal and vertical whitespace very well, and it's clear what you're doing with each block of code. You have also controlled for any possible issues that might come up (null pointer, insufficient buffer length, etc). Maybe there's a more concise way to do it, but in terms of clarity and maintainability I think this code will suffice.


I'm only going to review the C++ code here, as all I could suggest for the Python code also applies to the C++, so is included in this review.
Firstly, the interface is quite limiting - the inputs need to be converted to vector of string-view objects, which is inconvenient if I have a linked-list of strings, or an input stream yielding QStrings.  I recommend changing to accept a pair of iterators, or in sufficiently modern C++, a std::ranges::range object.
This test is inefficient:
word.find(common, 0) != 0

If we don't find common at position 0, find() will continue searching the rest of the string (the Python code is better here).  We need an implementation of starts_with() (which is in C++20's std::string) - or better, we could use std::mismatch() to directly find how much of the strings are common, eliminating the loop where we repeatedly remove a single character.
Here's my attempt at that, also with a simple optimisation to return early when the common string becomes empty:
#include <algorithm>
#include <iterator>
#include <string_view>
#include <vector>

namespace
{
    template<typename String>
    String common_prefix(const String& a, const String& b)
    {
        using std::begin;
        using std::end;
        auto end_iter = std::mismatch(begin(a), end(a), begin(b), end(b));
        if (end_iter.first == end(a)) { return a; }
        if (end_iter.second == end(b)) { return b; }
        return String(begin(a), end_iter.first - begin(a));
    }
}

template<typename Iter, typename IterEnd = Iter>
std::string_view get_common_prefix(Iter first, IterEnd last)
{
    if (first==last) { return ""; }
    std::string_view common = *first;
    for (auto it = first;  it != last;  ++it) {
        common = common_prefix(common, *it);
        if (common.empty()) { return common; }
    }
    return common;
}

template<typename Container>
std::string_view get_common_prefix(const Container& words)
{
    using std::begin;
    using std::end;
    return get_common_prefix(begin(words), end(words));
}


Replace sequence of strings in binary file

A few issues with the code:

You're comparing the string length for both, but then replacing the bytes. In UTF-8 encoding, as you're using, it's possible that the two will be different: if find = "aeiou" and replace = "áéíóú" you'll have findBytes.Length == 5, and replaceBytes.Length == 10
You don't need to pass the position parameter by reference to SearchBytePattern, since you're not changing the reference, only calling methods on it.
On SearchBytePattern, you don't need the outermost loop to go all the way to bytes.Length, it only needs to go to bytes.Length - pattern.Length + 1 (and that would simplify the inner "if"
stream.Read doesn't necessarily return the count of bytes you asked for - it can return less than that. Your code should be ready to handle that situation.


Not all compilers support #pragma once

#pragma once

There are C++ equivalent of most C libraries that put the appropriate interface into the standard namespace.

#include <time.h>

// Prefer

#include <ctime>

My pet peeve (OK second after using namespace std;); because everybody thinks they know the rules but get it wrong all the time:

_Message

DO NOT USE IDENTIFIERS WITH A LEADING UNDERSCORE. Even if you know the rules most people get it wrong (such as this case) as a result it leads to maintenance problems. https://stackoverflow.com/a/228797/14065 An identifier with a leading underscore and a capital letter is reserved in all scopes (i.e. the implementation is potentially going to use a macro with that name and Message seems like a prime candidate).

Your three versions of the constructor can be written as a single constructor:

    MyException( const std::string& _Message
               , unsigned            int id = 0             // Use default values
               , MyException*        innerException = NULL) // That way you do not have
        : std::runtime_error(_Message)                      // three versions of the
        , exceptionId(id)                                   // same constructor
        , innerException(innerException)
    {
        time(&ts);
    }

A class is its own friend.
So you don't need to call getter methods to access members of the object you are copying in the copy constructor; you can just get the values. When constructing the base class (std::runtime_error) why not take advantage of its copy constructor (it may have optimizations that you are failing to take use of by using the non standard version).

MyException(const MyException& exception)
    : std::runtime_error(exception)
    , exceptionId(exception.exceptionId)
    , ts(exception.ts)
    , innerException(NULL)

The inner exception is passed around as a pointer. So we have no ownership semantics associated with it. You attempt to take ownership but fail (because you do not implement the rule of 3 (5 in C++11)).

{
    if (exception.inner != NULL)
    {
        // Slicing problem if exception.inner is derived from MyException
        innerException = new MyException(exception.inner);
    }
    else
    {
        // Already set in the initializer list no need to set again.
        innerException = NULL;
    }
}

Also because of the way you implement it you can not subclass MyException because the copy constructor will slice your object on copy. You should probably use a smart pointer to handle ownership of the exception. Since sharing the same exception would solve most of your problems the easy way out is to use shared_ptr<X>. Personally I would make X a std::runtime_errornotMyException` thus allowing you to chain on standard exceptions (or anything derived from them).

In the handler:

void handleException(MyException *ex)

Why pass a pointer to the exception. Now you have to check for NULL. Pass it as a reference.


Consumer producer implementation involving POSIX, semaphores, and locks

General note

It is very hard to tell if this program works or not: I don't know what is supposed to be a correct behaviour. I can only speculate that you didn't want to see a semaphore value ever to exceed 4. If it is the case, than it is a pure coincidence -- caused by the large delays (try to remove sleep()). Absolutely nothing in the code prevents two or more producers to "simultaneously" test the value, and proceed to post the semaphore.

Particular problems

There is no reason to serialize consumers' access to a sem_wait(). In a sense it defeats the purpose of the semaphore.

stdio is not thread safe. The fact that printouts haven't messed up is another coincidence, also caused by the sleep() delays.

The code creates a multitude of threads, but joins only two. Not a problem in a toy program; a bad resource leak in general.

A minor note: since the thread functions ignore the argument, you should pass NULL. Passing anything else (like (void *) (intptr_t) value) is misleading.


Largest palindrome that can be made from a product of 2 3-digit numbers (Project Euler 4)

Speeding things up
There are several things you could do to speed things up:

Instead of looping from 100..999, go from 999..100 instead.  That way, if you find a palindrome, you can break from the j loop because any lower values of j will not beat the one you just found.
Once you loop backwards, you can also check i*j versus the best answer you've found so far.  If i*j <= best, you can break from the j loop.
You don't have to use log10 to find the number of digits.  Since you are already converting the number to a string, just use num_stringstream.length().
The j loop can start at i instead of 999, because any j higher than i will already have been tested.

Cleaning things up
It would make your program look a lot more readable if you moved all of the palindrome checking logic to its own function.
This line here is very hard to read:

num_to_test>ans?ans=num_to_test:ans=ans;

Putting it all together
Here is what I think your code should look like.  I removed the cin << quit part because I wanted to time the program without requiring user input.
#include <string>
#include <sstream>
#include <iostream>

bool is_palindrome(int num)
{
    ostringstream convert;
    convert << num;
    string num_stringstream = convert.str();
    int num_of_digits = num_stringstream.length();
    for (int i=0; i < num_of_digits; i++)
    {
        if (num_stringstream[i] != num_stringstream[num_of_digits-i-1])
            return false;
    }
    return true;
}

int main(void)
{
    int best = 0;
    for (int i = 999; i >= 100; i--)
    {
        for (int j = i; j >= 100; j--)
        {
            int num_to_test = i * j;

            if (num_to_test <= best)
                break;

            if (is_palindrome(num_to_test)) {
                best = num_to_test;
                break;
            }
        }
    }
    cout << best << endl;
}

Using gcc -O3, this program ran in 0.03 seconds on my computer as opposed to 1.06 seconds, for around a 30x speedup.


Displaying a user's social media information

Style (PHP)

At the beginning, the test seems pretty weird but in any case, I usually prefer

$var = (condition) ? val1 : val2;

over

if(condition) {
    $var = val1;
} else {
    $var = val2;
}

You can replace

if(condition1) {
    if(condition2) {
        stuff();
    }
}

with

if(condition1 && condition2) {
    stuff();
}

On top of that, the if(!$display_tweets || !$twitter_username) test would then be useless as it would correspond to the else case.

There's no point in closing php tags just before reopening them. Remove the ? > < ? php tags.

Style (HTML)

Do you really want to use the em markup inside the h2 one?

What you are actually doing/trying to do

The code at the beginning seems to be assuming that we have a least facebook or twitter (sometimes both).

If this is indeed the case, the
$width = ($facebook && !$twitter_username || !$facebook && $twitter_username) ? "490" : "930";
at the beginning could become
$width = ($facebook && $twitter_username) ? "930" : "490";
If it is not the case, could the beginning be behind an if (twitter || facebook) test as creating an empty div (and giving it an arbitrary width) might not be relevant. If you want to keep it, for the definition of the width, I'd rather have someting like :
$width = ($facebook && $twitter_username) ? "930" : (($facebook || $twitter_username) ? "490" : "1");

It might be interesting to use <a href="<?= $website_url; ?>" > or something like that to display the url as an actual link to make things easier from a user point of view (here I assumed that the input has been sanitized properly). On top of that, I don't understand why you hardcode the www. string (have a look at your current adress bar for more details). If there was anything to be hardcoded (and I personally wouldn't go for that), it's more likely to be the http:// part.


Putting a border around the selected list item

Are you required to have the .border-bottom class on the div elements?  I'd move those up to the li elements so you don't have to bother with the add/remove .border-bottom and you could use first-child to cleanly add a top border for the selected element if it's first (and avoid a double border for the other items).  See below snippet with the changes.

$("li").click(function() {
  //Remove the my-list--selected class from any elements that already have it
  $('.my-list--selected').removeClass('my-list--selected');
  //Add the my-list--selected class to the clicked element
  $(this).addClass('my-list--selected');
});
.border-bottom {
  border-bottom: 1px solid #ccc;
}

.my-list--selected {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}

.my-list--selected:first-child {
  border-top: 1px solid #ccc;
}

Content

Content

Content


pass argument to jQuery .on() event handler callback

It seems that what you want is a partially-applied function. One way this can be achieved is using Function.prototype.bind().:

$(SELECTORS.SUBMIT_BUTTON).on('click', userAddFlagToPost.bind(null, userId));

Pass null as the first argument unless the context needs to be set (e.g. to this for the same context?) and then userId as the second argument will pass that as the first argument to the function. Then note that userAddFlagToPost() would then receive the event Event eventobject argument per the `.on() method.

With this approach, the function is not invoked (as it would be with your proposed syntax) but instead the partially applied function is invoked when the click handler is applied.

See this demonstrated in the snippet below:

(function() {
  'use strict';

  var postId;
  var SELECTORS = {
    SUBMIT_BUTTON: '#submitButton',
    DISPLAY_ELEMENT: '#displayElement'
  };

  function userAddFlagToPost(userId) {
    var text = 'userId passed to userAddFlagToPost: ' + userId + ' count of arguments: ' + arguments.length;
    Array.from(arguments).forEach(function(argument, index) {
      text += '
 typeof arg[' + index + ']: ' + (typeof argument);
    });
    $(SELECTORS.DISPLAY_ELEMENT).html(text);
  }

  function init() {
    var userId = 1337; //hard code for now
    $(SELECTORS.SUBMIT_BUTTON).on('click', userAddFlagToPost.bind(null, userId));
  }
  init();
})();
#displayElement {
  border: 1px solid #0f0;
  margin: 4px;
  padding: 10px;
}

<button id="submitButton">Click this to see the partially function called</button>

Note that there is a jQuery shortcut method .click() that could be used in place of .on('click'):

$(SELECTORS.SUBMIT_BUTTON).click(userAddFlagToPost.bind(null, userId));


Inky pinky ponky game / Josephus problem

Sorry, but I don't think this code is very good.

In create_c_list, the first node is allocated twice, leaking memory, and there
are no checks for allocation failure.  Parameters n_k and n_w are badly
named and the latter is not used.  The loop should be a for not while.
new_p could just as well be n, for 'node'.  Also, it is not obvious that
the 'c' in the name means 'circular' and you should add spaces around
operators ('=' etc).

In elimination, the function name should be a verb.  The outer while(1) loop is often preferred as for (;;) , although that is a matter of personal preference. Indefinite loops are usually best avoided anyway.
Inside this loop is a for loop, which should define iter in the loop and call it i.  Parameter cntr means nothing - it could be
'counter' of 'center'.  Give it a better name.  It derives from a value
entered by the user called num which gives away no secrets, and the prompt
was "How many no. of words?" - so num and cntr are the number of 'words',
but the list created by create_c_list makes no mention of 'words'.  It is as
if you don't want the reader to understand what it does.  The for loop locates the node according to the cntr, which takes a long time if cntr is zero, as the loops starts from 1.  Then you do another
loop, this time a while in which you find the list entry before the one
(called it) that you located in the for loop.  You could have combined the two loops.  You then delete it using an unnecessary temporary
variable.
And so the outer loop continues until there is only one entry in the list - that condition could have been the condition for the outer while loop.

In printList (which uses camelCase while create_c_list doesn't)  you don't
modify the list, so it should be passed const.  Parameter list_tail is
inaccurate - a circular list has no tail.  Call it just list.

Also, putting main last avoids the need for prototypes, all functions except
main should be static and the names of struct ll_core and c_ll would
be better as struct node and value.


Validating a name with C#, ASP.NET Core 3.1 and Regex

From the separation of concerns perspective it seems fine that you do not want to validate against emptiness. On the other hand, one can argue that why do you treat an empty string as a valid name.
My suggestion is to create a ctor with a parameter, where the consumer of the attribute can define how should it behave in case of empty input.
public class NameAttribute : ValidationAttribute
{
    private static readonly Regex NameRegex = new Regex(@"^[a-zA-Z]+(?:['-][a-zA-Z\s*]+)*$", RegexOptions.Compiled);
    private readonly bool shouldTreatEmptyAsInvalid;
    public NameAttribute(bool shouldTreatEmptyAsInvalid = true)
    {
        this.shouldTreatEmptyAsInvalid = shouldTreatEmptyAsInvalid;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
            return shouldTreatEmptyAsInvalid
                ? new ValidationResult($"The name is invalid, it should not be empty.")
                : ValidationResult.Success;

        return NameRegex.IsMatch(value.ToString())
            ? ValidationResult.Success
            : new ValidationResult($"The name '{value}' is invalid, it should consist of only letters, and optionally spaces, apostrophes and/or hyphens.");
    }
}

I moved the creation of the Regex to a static variable, but you should take some measurements in order to be sure, which has the best performance. Please check this MSDN article for other alternatives.


You don't need to mock the Entity/DTO object . Good practice is to create a new instance of DTO object and set data using setters .


The begin returned by maxSubArraySub can be wrong as we update start after we've found a good candidate for the maximal sum. This can lead to potential bugs (I am way too lazy to find an actual case where it makes a difference but that should be possible). The solution from http://en.wikipedia.org/wiki/Maximum_subarray_problem introduces another variable to have a temporary starting point and one for the actual starting point of the maximum found so far.

You can make things much simpler by defining (very simple) classes for 3-tuple and 4-tuple. Make the members private and final and you won't need getters. As the point is just to return multiple values from a function, I don't think there a point in making things too specific and I'd rather have the class and the members have simple names.

You have a typo in your class name and it's especially annoying in Java where the file name has to match ;-)

You could make your code a bit more robust by asserting that all rows have same length.

In your code, the comment about complexity is wrong. The one is your stackoverflow question is right, it is indeed N*N*M :-)

Here's what I've done :

final class Tuple4 {
    public final int a;
    public final int b;
    public final int c;
    public final int d;

    public Tuple4(int a, int b, int c, int d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}

final class Tuple3 {
    public final int a;
    public final int b;
    public final int c;

    public Tuple3(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

/**
 * Returns the maximum rectangle in the matrix
 *
 * @author javadeveloper
 */
public final class MaximumSumRectangleInMatrix {

    // made this utility class non-instantiable
    private MaximumSumRectangleInMatrix() { }

    private static Tuple3 maxSubArraySum(int[] a) {
        assert a != null && a.length > 0;

        int max = a[0];
        int currSum = a[0];

        int start = 0;
        int start_tmp = 0;
        int end = 0;

        for (int i = 1; i < a.length; i++) {
            if (currSum < 0) {
                start_tmp = i;
                currSum = a[i];
            } else {
                currSum += a[i];
            }
            if (currSum > max) {
                max = currSum;
                start = start_tmp;
                end = i;
            }
        }
        return new Tuple3(start, end, max);
    }

    /**
     * Returns the Tuple4 object containing the maximum
     * rectangle in the matrix.
     *
     * @param  The input matrix.
     * @return The rectanglecoor object containing the coordinates of the maximum sub matrix
     */
    public static Tuple4 calMaxRectangle(int[][] m) {
        if (m.length == 0 || m[0].length == 0) {
            throw new IllegalArgumentException("The matrix should be non empty");
        }

        int max = Integer.MIN_VALUE;
        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;

        int lengthRow = m[0].length;

        for (int i1 = 0; i1 < m.length; i1++)
        {
            if (lengthRow != m[i1].length)
                throw new IllegalArgumentException("Matrix is not square");

            int[] temp = new int[lengthRow];
            for (int i2 = i1; i2 < m.length; i2++)
            {
                for (int j = 0; j < lengthRow; j++)
                    temp[j] += m[i2][j];

                Tuple3 maxSubArrayCoord = maxSubArraySum(temp);

                if (maxSubArrayCoord.c > max) {
                    max = maxSubArrayCoord.c;
                    a = i1;
                    b = maxSubArrayCoord.a;
                    c = i2;
                    d = maxSubArrayCoord.b;
                }
            }
        }
        return new Tuple4(a,b,c,d);
    }

    public static void main(String[] args) {
        int[][] m = {  {-20, -30, -40, -50,  50},
                       { 10,  20,  30,  50, -10},
                       { 50,  60,  70,  80,  30},
                       {-10, -20, -30, -40,  60},
                    };

        Tuple4 r = calMaxRectangle(m);
        System.out.println("(" + r.a + "," + r.b + ") ; (" + r.c + "," + r.d + ")");
    }
}


Define the functions that correspond to a given argument configuration separately:

const processStringNumber = (string, number) => console.log(number + ' is a number')
const processStringString= (string, string2) => console.log(string2+ ' is a string')

Put the argument configurations and the corresponding functions in a data structure:

const processingObj = [
  {
    argsTypes: ['string', 'number'],
    process: processStringNumber
  },
  {
    argsTypes: ['string', 'string'],
    process: processStringString
  }
]

Write a helper that does the checks and dispatches the corresponding function:

//Retrieve the types of an array of args (can have different implementations)
const getTypes = (args) => args.map((arg) => typeof arg)

//Calls the appropriate function from 'processingObj'
const process = (args, processingObj) =>
  processingObj
    .find((process) => _.isEqual(process.argsTypes, getTypes(args)))
    .process(...args)

Usage:

process(["aaa", 1], processingObj) // 1 is a number
process(["aaa", "aaa"], processingObj) // aaa is a string

Here is also an ES5 version (via Babel)


Is using beforeFind() event in background to dynamic update SQL queries a good practice?

It might lead to a ton of refactoring, but have you considered breaking up your code field into multiple columns, and simply ordering by them all?

Beyond that, magic in callbacks is always risky as you've pointed out. But with such a complex requirement for ordering, doing it manually each time doesn't make a lot of sense either.


Python Unit Coversion Code Optimization in terms of Space and Time Complexity

There is not much need for a class for what you are after. Storing all the conversion factors in a dictionary, you could simply do something like:

def convert_temp(val, from_, to_):
    if from_[0] == to_[0]:
        return val
    off1, mult, off2 = convert_temp.data[from_[0]][to_[0]]
    return (val + off1) * mult + off2
convert_temp.data = {'C' : {'F' : (0, 1.8, 32)},
                     'F' : {'C' : (-32, 0.555555556, 0)}}

And now:

>>> convert_temp(50, 'C', 'F')
122.0
>>> convert_temp(122, 'F', 'C')
50.000000039999996

You would of course have a larger dictionary with all possible conversions. You could get fancy and store only half the conversions:

def convert_temp2(val, from_, to_):
    if from_[0] == to_[0]:
        return val
    try:
        off1, mult, off2 = convert_temp2.data[from_[0]][to_[0]]
    except KeyError:
        off2, mult, off1 = convert_temp2.data[to_[0]][from_[0]]
        off1 = -off1
        off2 = -off2
        mult = 1 / mult
    return (val + off1) * mult + off2
convert_temp2.data = {'C' : {'F' : (0, 1.8, 32)}}

>>> convert_temp2(50, 'C', 'F')
122.0
>>> convert_temp2(122, 'F', 'C')
50.0