Design

You've got the right diagnosis: your functions are poorly designed, such that it is unclear what their inputs and outputs are.  We definitely need to fix your functions so that they act the way functions should.  Redesigning the code to be object-oriented would not necessarily improve the code further, though.

Let's consider your main loop:

loop = True

while loop:
    check_def()
    confirmed()
    placement_def()
    checks_def()
    if not loop:
        break
    user_def()

Looking at just that code, I can't tell what your functions do.  I can't even tell that it's code for a board game.  Compare that to the main() function in my solution below:

def main():
    board = [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
    ]
    print_board(board)
    for player in itertools.cycle([1, 2]):
        make_move(board, player)
        print_board(board)
        if is_winner(board, player):
            print("Player {0} has won".format(player))
            break
        if is_board_full(board):
            print("Board is full")
            break

if __name__ == '__main__':
    main()

This code makes it clear that it's a board game in which two players take turns making a move.  Each function has:

A purpose, and the name tells you what it does.  check_def doesn't mean anything, but is_winner does.  The fact that the name starts with "is_…" implies that it's a function that returns either True or False.
A useful return value.  If is_winner(…) returns True, then the if statement in the loop can use that information to end the game.  You don't want the information to be passed back indirectly by setting a global loop variable.
Inputs passed as parameters.  What information does is_winner(…) need to do its job?  Obviously, it needs to know the state of the board.  It's also helpful to know which player just moved, so that it only needs to consider the most recent player's coins.

To help enforce these good habits, you should write a docstring for every function that explains the purpose, the inputs, and the return value.

Bug

Your checks_def() function, which is intended to detect the end of the game, is buggy:

def checks_def():
    return check_def() and checkEmpty_def() and diagcheck_def()

check_def() (which detects horizontal and vertical wins) never returns True: it can either return False, or fall off the end of the function and implicitly return None.  Therefore, due to the way short-circuit evaluation works with the and operator, the code checkEmpty_def() (to detect a tie) and diagcheck_def() (to detect a diagonal win) will never be executed.

The logic in that line is further wrong in that you should check for diagonal wins before detecting that the board is full, because the last coin that fills the board might be a winning move.

Expressiveness

Python has some very powerful techniques to write loops with a lot less code.  In the solution below, my is_winner(…) and is_board_full(…) functions make use of the built-in functions all() and any() with generator expressions.

zip(*board) is a handy idiom for transposing row and columns.

Suggested solution

from itertools import cycle

def print_board(board):
    """
    Print the board.
    """
    print("\nCurrent board:")
    for row in reversed(board):
        print(row)

def make_move(board, player):
    """
    Ask the player for a column, and mark the move on the board if it is a
    legal move.  If it is an illegal move, ask again.
    """
    while True:
        try:
            c = -1 + int(input("Input a coin, player {0} (1-4): ".format(player)))
            if not (0 <= c < 4):
                print("Column number is out of range.")
            top_row = next(row for row in board if row[c] == 0)
            top_row[c] = player
            break
        except ValueError:
            print("Illegal move.")
        except StopIteration:
            print("This column is full.  Try another one!")

def is_winner(board, player):
    """
    Return True if a row, column, or diagonal consisting of four entries for
    the given player.
    """
    return (
        any(all(c == player for c in row) for row in board) or
        any(all(r == player for r in col) for col in zip(*board)) or
        (board[0][0] == board[1][1] == board[2][2] == board[3][3] == player) or
        (board[0][3] == board[1][2] == board[2][1] == board[3][0] == player)
    )

def is_board_full(board):
    """
    Return True if all elements of the board are non-zero.
    """
    return all(all(row) for row in board)

def main():
    board = [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
    ]
    print_board(board)
    for player in cycle([1, 2]):
        make_move(board, player)
        print_board(board)
        if is_winner(board, player):
            print("Player {0} has won".format(player))
            break
        if is_board_full(board):
            print("Board is full")
            break

if __name__ == '__main__':
    main()


Am I interfacing in a secure manner with rijndael?

CalculatePasswordHash is inadvertently reimplementing (and probably not as well) a standard primitive. You should use System.Security.Cryptography.Rfc2898DeriveBytes instead.
The code

    var desc = crypto.CreateEncryptor();
    ...
    desc.Dispose();

raises a red flag. Why isn't it using using?
You write to a memory stream and then write the contents of the memory stream unmodified to a file. It seems that you could simplify this just skipping the middle-man.


1. Answers to your questions

Callbacks. Why not use a return value intead?

def step(self):
    """Advance the game one step.
    Return a pair of Booleans (game over, ate food).

    """
    game_over = self.head in self.tail
    ate_food = self.head == self.food
    if ate_food:
        self.tail.insert(0, self.head)
        self.food = self._new_food_location()
    self._move_snake(*self._dir)
    return game_over, ate_food

(But see below for two bugs in this function.)
Getters are normally used in three scenarios. First, to provide a simple interface to a complex data structure. Second, to give the implementer freedom to change the implementation in future. Third, in combination with setters when writing a public API whose internal data structures have an invariant that needs to be preserved, so as to protect the internal data structures from corruption by a well-meaning but incompetent client.

None of these scenarios applies here. The internal data structures are straightforward, so the first scenario does not apply. And this is all your own code (not a public API) so the second and third scenarios do not apply.
Redundancy in _move_snake. It doesn't seem like a big deal either way. No opinion here.

2. Other comments on your code

There's a bug in step: you move the snake even if the game is over. Surely the snake should stop moving when it's dead?
Another bug in step, this time in the "eat food" logic. You insert the head into the tail:

self.tail.insert(0, self.head)

but then you call _move_snake which does the same thing. So the snake ends up containing two copies of the head location.

The usual way that "snake" games work is that when the snake eats some food, it does not grow a new tail segment immediately. Instead, it waits until the next time it moves and grows a new tail segment in the position where its old tail used to be. This is easily implemented by incrementing a counter each time the snake eats food:

self.growth_pending += 1

and then decrementing the counter instead of deleting the tail segment:

if self.growth_pending:
    self.growth_pending -= 1
else:
    self.tail.pop()

Note that these bugs would have been easy for you to spot had you actually finished writing the game and tried to run it.
Inserting an item at the beginning of a list:

self.tail.insert(0, (x, y))

takes time proportional to the length of the list (see the TimeComplexity page on the Python wiki). It would be better to use a collections.deque and call the appendleft method.
This line of code:

game_field = set([(x, y) for x in range(self.width)
                  for y in range(self.height)])

doesn't need the list comprehension, as you can pass a generator expression directly to set:

game_field = set((x, y) for x in range(self.width)
                 for y in range(self.height))

This avoids constructing a list and then immediately throwing it away again.
You can further simplify that line of code using itertools.product:

from itertools import product
game_field = set(product(range(self.width), range(self.height)))

In _new_food_location you convert possible into a list so that you can call random.choice on it. But if you used random.sample instead, you wouldn't have to do that.
In _new_food_location you build a set containing every location in the game not occupied by the snake. It would be better to build this set just once per game, and keep it up to date as the snake moves.

In detail, in reset you'd write something like:

self.growth_pending = 0
self.empty = set(product(range(self.width), range(self.height)))
self.empty.remove(self.head)
self.empty.difference_update(self.tail)

(Note the use of difference_update to avoid having to convert self.tail to a set.)

In _move_snake you'd write something like:

self.tail.appendleft(self.head)
self.head = newX, newY
self.empty.remove(self.head)
if self.growth_pending:
    self.growth_pending -= 1
else:
    self.empty.add(self.tail.pop())

And finally, in _new_food_location you'd write:

new_position = random.sample(self.empty, 1)[0]


Python class that implements the Newton method

Pathological cases exist where Newton's method will not converge on a solution.  Yet, there is no obvious way for the caller to tell whether convergence was achieved.  You should distinguish between whether the loop terminated via the break (success) or by exhaustion of the loop condition (failure).

for _ in range(self.num_iter):
    x_tplus1 = x_t - self.step_size * np.dot(np.linalg.inv(H(x_t)), g(x_t))
    #check for convergence
    if abs(max(x_tplus1-x_t))<self.tol:
        break
    x_t = x_tplus1
else:
    raise SolutionNotFound, "No convergence after %d iterations" % (self.num_iter)


Line by line analysis
public class Util {

Util is not a good class name. It does not describe what the responsibility or function of the class is. If it did, it would describe the top desktop drawer of code, where all random code snippets are dumped because the authors could not be bothered to think of a proper place. Suffice to say, those kinds of classes don't exist in well maintained code bases. Use something like TabularToXmlConverter instead.
/*/
DOC Generation -> XML with ArrayList String elements
 */

You should have an extremely good reason for creating your own specialized format for documenting your classes and methods. Java platform comes with JavaDoc which is a standardized way of formatting documentation. Programmers know how to read it and expect to see it. When encountered with your style they literally get angry because they have to learn a new (and most likely inferior) format.
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();

Because your method created the DocumentBuilderFactory, it became responsible for managing it's own dependencies. If you wanted to use the converter to create a bit different kind of XML document, you couldn't do it without changing the class and breaking all code that already uses it. You might want to pass a DocumentBuilder reference to the class and thus employ dependency injection.
Document xmlDoc = xmlBuilder.newDocument();

What is the reason why you build the document in memory? Most often when I have worked with XML, the biggest problem has been memory consumption caused by handling large XML documents that have been loaded into memory. Since you also provided a transformDocToFile it might make more sense to just write the document directly to an OutputStream using the Streaming API for XML (StAX).
boolean headerDefined = false; //First while will be to define header

Do not use end-of-line comments. They are difficult to read, hard to maintain and force you to compress your thoughts into fewer words that make sense. I, for example, have no idea what this comment means. And you should strive to use variable names that describe the purpose of the variable. From the variable name alone I already guessed it's a flag that tells if the header row has been generated. So there isn't any need for a comment here at all. The other end-of-line comments also just tell what the preceding code does adding no additional value. Comments should desribe why something is being done, not repeat what the code already tells. If the code isn't clear, first priority should be making it clearer instead of duplicating it in free verse.
public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {

One of your methods is static and the other is not, requiring the caller to create an unnecessary instance of the Util-class.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

You catch one of the possible exceptions and continue happily even though in this particular case you cannot even write to the file.


I would only change a few things around.  First, this is all one big monolithic function. Break it apart into smaller individual functions and try to have each function do one job only.

Second, I would convert from using the success callbacks to using Promises. That might be a matter of taste; Feel free to ignore. Third, I would encapsulate your code inside an IIFE to create a private scope. It also insures that $ is going to be jQuery.

Next, I would move all of the individual functions out of the document.ready event.  There is no reason to wait until then to load the functions.  Lastly, I would change to using the submit event instead of the click event. I would guess that is really when you need to do your call.

(function( $ ) {
  // IIFE for a private scope

  function getData( search ) {
    return  $.ajax({
       url: 'https://api.github.com/legacy/repos/search/' + search,
       dataType: 'json'
    });
  }

  function searchGit( event ) {
    //grab value of search field
    event.preventDefault();
    var search = $('#search').val();
    // Validates entered value
    if ( search.length ) {
      $.when( getData( search ) ).done( function( data ) {
        processData( data );
      });
      /* could also be written like this:
         var call = getData( search );
         call.done( function( data ) { ... });
                  OR
         getData( search ).done( function( data ) { ...});
      */
    } else {
      alert( "Please enter repo name" );
    }
    return false;
  }

  function processData( data ) {
    // use the results to template the html using _
    var results = data.repositories,
        resultsTemplate = _.template($("#results-template").html()),
        resultingHtml = resultsTemplate({results : results});

    // place the generated data into the html
    $("#results-container").html( resultingHtml );
  }

  $(function(){
    $('#submit').on( 'submit', searchGit );
  });

})( jQuery );

Eventually, I would recommend replacing all of the DOM selectors with variables.  That way it would be less coupled together.  For example, in the process data function:

  function processData( data , templateName, resultsElement ) {
    // use the results to template the html using _
    var results = data.repositories,
        resultsTemplate = _.template( $( templateName ).html() ),
        resultingHtml = resultsTemplate( {results : results} );
    // place the generated data into the html
    $( resultsElement ).html( resultingHtml );
  }

Hope that helps.


longestword should be named using an interCaps naming convention.  Also, replaced and final aren't exactly helpful variable names.  However, if you were to have an intermediate result called words, it would be quite clear what that stands for.

It's good practice to terminate all statements with semicolons, even though JavaScript allows them to be omitted.

function longestWord(str){
    var words = str.replace(/[^A-Za-z\s]/g, "").split(" ");
    var wordsByDescendingLength = words.sort(function(a, b) {
        return b.length - a.length;
    });
    return wordsByDescendingLength[0];
}

Note that hyphenated words will have their hyphens dropped, both when comparing lengths and when returning the result.


First of all you should rename your function, it doesn't perform just a search then DirSearch() is not appropriate. What about, for example, RenameAllPngFiles()? More context may suggest a better name, rename how? According to which rules? That should be clear.

Parameter names are usually camelCase and they're not prefixed, sDir should then be searchFolder or even simply path.

You do not validate inputs. An I/O error or an invalid argument because calling logic is broken are completely different and they should be handled differently.

public static void RenameAllPngFiles(string path)
{
    if (path == null)
        throw new ArgumentNullException(nameof(path));

    if (String.IsNullOrEmpty(path))
        throw new ArgumentException("Path cannot be empty.", nameof(path));

    // ...
}

Note that a null argument and and empty argument are different (eventually path may even be empty to use current directory) and as such they should handled separately. First test is to throw ArgumentNullException instead of a generic ArgumentException if path is null. Second test may be rewritten to path.Length == 0 but I find IsNullOrEmpty() much more explicative then I accept the price of the redundant null-checking (at least until I'll need IsNullOrWhiteSpace()).

We're now at the core of your function. First of all drop ToList() because you do not need it.

GetFiles() search all files and then you can start processing. If folder is big or you will change to include sub-directories then application will lag until operation is completed, you should experiment using Path.EnumerateFiles() which iterates file by file while search proceeds.

100 I/O parallel operations might be too much, you will find a balance only with real-world testing but a reasonable value may be around 4 (especially because each operation is very short and threading overhead may be too high). Not to mention that hardly  .NET scheduler will really start so many threads for your loop then probably you will not note any difference.

Do not catch Exception but appropriate exceptions you know may happen: IOException and UnauthorizedAccessException, anything else is a programming error that should be fixed during development. Also your second catch block is useless because function itself will never throw (you catch and swallow everything). Do not discard the whole batch if one operation fails.

var images = Directory.GetFiles(path, "*.png", SearchOption.AllDirectories)
    .AsParallel()
    .WithDegreeOfParallelism(MaxParallelIOOperations)
    .ForAll(TryRenameImage);

That's all, note that you can pass function directly without wrapping inside (another) anonymous delegate. SearchOption.AllDirectories already search inside all sub-directories. If you do not have circular hard-links then it's way faster than your recursive implementation. If you need it to handle fine granted access permissions then code will be much more complex than this and you should definitely catch relevant exceptions (Directory.EnumerateFiles() will easily let you handle this problems case-by-case, see this SO post).

Change your Rename() function to handle I/O errors:

private static void TryRenameImage(string path)
{
    try
    {
        // Your logic
    }
    catch (IOException e)
    {
        // You may retry few times after a small delay,
        // file might be in use elsewhere.
    }
    catch (UnauthorizedAccessException e)
    {
        // Log?
    }
}

See also IOException: The process cannot access the file 'file path' because it is being used by another process.

If you write errors to console then you should use System.Console.Error instead of System.Console. stdout is for program output and stderr is for its errors.


Well, I'd say that, apart from one or two things, you're going about it in exactly the right way.
A class, and all of its methods process data. If the data supplied poses an exceptional problem (ie, the data is invalid), then an Exception has to be thrown back to the code that passed that data.

The motto is: He who supplies the data, has to handle the errors.
By having methods simply return errors, your class is taking on too many responsibilities: Process data and error handling? No, that is in violation of the single most important SOLID principle: the SRP (Single Responsability Principle).

Here's why I am prepared to defend my statements on throwing exceptions from classes:

A class cannot check if the calling code is checking the return value of its method. You may return false or ERROR, but if the caller doesn't check it, you might aswell return a Shakespeare sonnet...
If you receive bad data, don't try to make sense of it, or don't try to make it work: the calling code has a bug in it, and should be fixed. The best way to spot the troubled bit of code is to throw new InvalidArgumentException and look at the stack-trace. Like I said before: bad arguments received often means bad code is calling your method: FIX IT.
If your class is well-tested, then it's safe to say that if ever it encounters a scenario where it can't do its job properly, something quite Exception-al has happened, treat it accordingly.
returning error-indicating values makes unit-testing harder, in a way. I, personally, like the odd @expectedException annotation, for example. If the test fails, it also yields more speceific output anyway.
You don't know what code is going to handle the problem. Returning an error-indicator is all well and good, provided that return value is caught, and indeed returned all the way through to the code that will eventually deal with it. An exception just keeps going until it is caught. If not, the whole application just grinds to a halt. Either way, returning false is less pressing, there's no real incentive to do something. An exception, however, must be handled for the program to go on.
You cannot register handlers for return false; or return null; statements, but you can register error and exception handlers. And you will do so in larger projects. This, certainly, is a huge advantage of exceptions.
Returning errors depending on the usage of your class limits the context/use-cases, in which you can use the class. A class should be a self-contained, portable unit of code. It should, therefore, just process data, or handle exceptional cases, not both.

Another quick hang-up of mine that I can't have go unmentioned: Please, please, please subscribe to the coding standards, as described by PHP-FIG.

Other niggles I have, and I'm really nit-picking here:

throw new Exception\TokenNotFound();

Ok, when I see this throw statement, I know that the TokenNotFound class is extending the Exception core-class (I hope), just like all other classes I might find in the Exception namespace. However, writing namespace Exception; at the top of a file could confuse PHP, if it doesn't already. Also, in files using the use keyword, the complementing catch statement just doesn't look right to me:

use Exception\TokenNotFound;
try
{
    //stuff
}
chatch(TokenNotFound $t)

Look at all Exception classes in common use: they all contain the word Exception (or Fault in SoapFault).TokenNotFoundcould be anything from a mock object, to a handler for just such an exceptional case, when in fact it is the exception object itself. Just appendException` to the exception class names. You may find this redundant at first, but at some point in time people using your code, or even yourself, will thank you for it.

use Exception\TokenNotFoundException;
try
{
    //stuff
}
chatch(TokenNotFoundException $t)


find the maximum occur number in an integer

You are passed an integer parameter, and you have to return an integer.  I do not see it as worthwhile converting to a string for the counting.  Better to count the digits directly from the original integer.  MOD (%) 10 will give you the last integer, and DIV (/) 10 will shift the remainder along one position.

You may have to be careful with 0 and negative numbers with this method, otherwise you might get unexpected results.

As will as finding the most common digit you also have to find if there are any other digits with the same frequency.  As you look for a new higher maximum, look for other digits with the same count and keep a note if they exist.

This is my code:

public static int maxOccurDigit(int a) {

    // Zero is a special case.
    if (a == 0) {
        return 0;
    }

    // Numbers != 0.
    int[] digitCounts = new int[10];

    // Ensure a positive
    if (a < 0) {
        a *= -1;
    }

    while (a > 0) {
        digitCounts[a % 10] += 1;
        a /= 10;
    }

    // Find max count and occurrences.
    int maxCount = digitCounts[0];
    boolean sameCounts = false;
    int digit = 0;
    for (int i = 1; i < digitCounts.length; i++) {
        if (digitCounts[i] > maxCount) {
            maxCount = digitCounts[i];
            sameCounts = false;
            digit = i;
        } else if (digitCounts[i] == maxCount) {
            // Digits with equal counts.
            sameCounts = true;
        }
    }

    // Check for multiple max counts.
    if (sameCounts) {
        return -1;
    }

    // Valid single max digit
    return digit;

} // end maxOccurDigit()


A couple of things.

Is the string conversions really necessary just for comparing 2 doubles?

Figuring the squared value on the fly seems to lead to a bit of repetition

Also, optional parameters make the initial calling simpler.

static double root(double x, double increment = 10, double num = 0)
{
    num += increment;
    double sqrdValue = num * num;
    if (sqrdValue == x)
        return num;
    else if (sqrdValue < x)
        return root(x, Math.Abs(increment), num);
    else if (sqrdValue > x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}

Since it appears that integers will introduce rounding errors, you filter for that by checking if the difference is less than or equal to 0.000000000000001, instead of just equal to, which gives the same degree of accuracy in the final answer as the built-in sqrt method of the Math class.

static double root(double x, double increment = 10, double num = 0)
{
    double maxError = 0.000000000000001;
    num += increment;
    double sqrdValue = num * num;
    if (Math.Abs(sqrdValue - x) <= maxError)
        return num;
    else if (sqrdValue < x)
        return root(x, Math.Abs(increment), num);
    else if (sqrdValue > x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}


Initializing a multidimensional with many default values

Yes, there's a better approach. The problem you have here is that each row is the same value, so a change to one row will be seen in all rows. For example, I added the following to your code to illustrate this:

console.log(JSON.stringify(defaultArray));
defaultArray[5][5] = "Fubar";
console.log(JSON.stringify(defaultArray));

This should change the value in the middle of the 'matrix', but instead the result is:

"[["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"]]"

You need to have a fresh array instance for each row.

Even though it is mundane, the logical way to do it is:

var defaultArray = [];

for(var x = 0; x < rowNumber; x++){
    var defRow = [];
    for(var y = 0; y < colNumber; y++){
        defRow.push(defaultValue);
    }
    defaultArray.push(defRow);
}

Edit: Based on the benchmarks for my browser (Firefox), a decrementing while-loop is much faster than alternatives. I would use:

var defaultArray = [];

for(var row = rowNumber - 1; row >= 0; row--){
    var defRow = [];
    for(var col = colNumber - 1; col >= 0; col--){
        defRow[col] = defaultValue;
    }
    defaultArray[row] = defRow);
}

By working backwards over the array you reduce the amount of space allocations that happen as the array grows. Here's the results of that benchmark for me:


As for being idiomatic, the only thing I'd change is the use of the variable g to f. Using g when f is available as a name is like using y when x is available.

There is significant redundancy in append, though. A sufficient implementation looks like this:

append :: Cons a -> Cons a -> Cons a
append Empty x           = x
append (Cons x xs) ys    = Cons x (append xs ys)

You could argue that your second pattern was an optimization in the case that the second list is empty, but the tradeoff is adding O(n) overhead every time the second list isn't empty. There's a reason (++) doesn't do that check for [a].  The third case was pure overhead, and always an improvement to remove.


Parsing string into hash-map with 2D coordinates as keys

Since there is no answers, I'll post my new version of code:

(defn line->cells
  "Converts string with cells to sequence of maps of Points
  It is str->cells helper, so it requires y argument."
  [str->value ^Long y ^String line]
  {:pre [(re-matches #"^((?:^| )(?:.+?| )(?= |$))+$" line)]}
  (map-indexed
    (fn [x value] {(Point. x y) (str->value value)})
    (str/split line #" ")))

(defn str->cells
  "Converts string with cells separated with
  delimiter and new lines to Points hash map"
  [^String s str->value]
  {:pre [(re-matches #"^((?:^|\s)(?:.+?| )(?=\s|$))+$" s)]}
  (->> s
       (str/split-lines)
       (map-indexed (partial line->cells str->value))
       (flatten)
       (into {})))


using namespace std;

See Why is using namespace std in C++ is considered bad practice on why you should avoid using directives at the global scope.

vector<int>split(string s){
    // ......
    while(getline(ss,item,' ')){
    // ......
}

Horizontal spacing helps readability by distinguishing language constructs.  Unless you are code golfing, you should write code for correctness and readability.

std::vector<int> split(const std::string& s){
    // ......
    while (std::getline(ss, item, ' ')) {
    // ......
}

Consider your function call that splits a sequence of digits.

    vector<int> nums = split(two);

How many allocations/reallocations are being made in split()?

Every time you call split(), you are passing the arguments in by value.  Prefer to pass by value when parameters are cheap to copy.  Otherwise, pass by reference (to const if immutable) when parameters are expensive to copy or have an unknown cost. Determining the cost is architecture dependent. For most systems today, anything more the two or three words (size of a double or reference) should be considered expensive.

When creating the sequence, elems.push_back() will do many reallocations.  The amount of reallocations is implementation dependant upon the std::vectors growth factor.  The sequence length is one of the input parameters of the problem.  Use that length to reserve the space before reading.

nums.erase(nums.begin());

Again, avoid unnecessary copies.  Every time nums.erase() is called, you are copying all the remaining elements in the sequence.  You could avoid the calls by just using i and j as the indices.

    for (int i = 0; i < args - 1; ++i) {
        for (int j = i + 1; j < args; ++j) {
            int temp = abs(nums[i] - nums[j]);
            if (temp >= k) {
                ++cases;
            }
        }
    }

  I tried to use the printf instead of std::cout, because I read somewhere that it is much faster than the latter, but the result was same. How can I overcome the TLE? I also tried some few more tricks but they somehow altered the algorithm as a result they were giving wrong outputs.

99% of problems on these code challenge sites will produce TLE's because of your algorithm and not the I/O method being employed.  In the case of scanf/printf vs std::cin/std::cout, I prefer the latter for these types of exercises.  If you really need the performance of C formatted I/O from C++ IOStreams, consider the following:

Disable synchronization

std::ios::sync_with_stdio(false);

Untie the streams.

std::cin.tie(nullptr);

Avoid unnecessary flushes (prefer '\n' to std::endl).

A better approach, avoid reading as a std::string and tokenizing.  Read the arguments as their intended type. Ensure you reserve space in your std::vector before reading values.

We can make improvements to the algorithm through sorting. The problem states as one of the preconditions that \$i < j\$.  With a sorted sequence (in ascending order), every element is guaranteed to be less than or equal to the elements that follow it.  When you find one element that meets the variation threshold, every element after that also meets the threshold.  To find the first element that meets that threshold, C++ provides both linear search (std::find_if()) and binary search (std::lower_bound()).  Since the sequence is sorted, binary search should be the faster search for any meaningful sized sequence.  Use std::distance to find the counts, use std::accumulate to sum those counts.  Just using the standard library produced a top-10 time on codechef for c++14.


Reading environment variables of various types

Go is statically typed. Every variable has a static type, that is, exactly one type known and fixed at compile time. You are not in dynamically typed Python anymore.

You could use reflection, BUT DON'T!

  Common difficulties with
  reflection

  If people are new to Go, they shouldn't be using reflection at all.

  -rob

Your functions are specializations of os.Getenv. Revise the function names to getenvStr, getenvInt, and getenvBool.

  os.Getenv retrieves the value of the environment variable named
  by the key. It returns the value, which will be empty if the variable
  is not present.

There is often nothing wrong when an environment variable is empty. Instead of panicing, return a named error.

For example,

package main

import (
    "errors"
    "os"
    "strconv"
)

var ErrEnvVarEmpty = errors.New("getenv: environment variable empty")

func getenvStr(key string) (string, error) {
    v := os.Getenv(key)
    if v == "" {
        return v, ErrEnvVarEmpty
    }
    return v, nil
}

func getenvInt(key string) (int, error) {
    s, err := getenvStr(key)
    if err != nil {
        return 0, err
    }
    v, err := strconv.Atoi(s)
    if err != nil {
        return 0, err
    }
    return v, nil
}

func getenvBool(key string) (bool, error) {
    s, err := getenvStr(key)
    if err != nil {
        return false, err
    }
    v, err := strconv.ParseBool(s)
    if err != nil {
        return false, err
    }
    return v, nil
}

func main() {}

References:

Package reflect

The Laws of Reflection


How can I refactor this into one line? Is that possible, even with ES6 syntax?

export const zeroBalance = (coin) => {
  coin.balance = 0;
  return coin;
};

Yes, that's easily possible. Newlines aren't required in ECMAScript:

export const zeroBalance = coin => { coin.balance = 0; return coin; };

Ruby has an implementation of the K Combinator as Object#tap for exactly that use case. ECMAScript doesn't, but it's easy to implement:

 function k(obj, f) { f(obj); return obj };

This would allow you to rewrite your code like this:

export const zeroBalance = coin => k(coin, c => c.balance = 0);


Magic number elimination:
make offsets 8, 16 of something constant in places like this:

'dot2': lambda x, y, r: c.create_oval(x + 16, y, (x + 16) + r, y + r, fill='black'),

you probably should make one function inside draw_dice instead of lambdas and use partial for partial application

def make_dot(x,y,r, color='black'):
    # actual code here
    pass

and then

'dot': partial(make_dot, x, y, x+8, y+8, r)


Code review for style, clarity and efficiency. Removing duplicates from linkedlist

LinkedList is designed to preserve the order in which elements were inserted into it above all other considerations.  It should only be used when you need to retrieve the items in the list in order, because there is a faster collection available for any other type of access.

It looks from your code like you want a sorted list of elements, in addition to duplicates removed as stated in your question.  Sets are designed to have no duplicates and TreeSet is designed to sort your items as they are inserted.  If you use a TreeSet instead of a LinkedList you don't need a rmDuplicates method at all!  If you are concerned about returning a Set instead of a List, you can always return a Collection because it has about the same signature.  Time the difference between your method and using a TreeSet with a hundred thousand elements.  I think you will be surprised how fast TreeSet is!

public static void main(String[] args) {
    TreeSet<Integer> list = new TreeSet<Integer>();
    list.add(1);
    list.add(1);
    list.add(1);
    list.add(4);
    System.out.println(list);
}

If you needed to preserve the insertion order, I'd use a LinkedHashSet:

public static Collection<Integer> rmDuplicates(Collection<Integer> list) {
    return new LinkedHashSet(list);
}

If you have tried this with a custom type of Object instead of an integer and it didn't work, then you need to implement equals(), hashcode(), and maybe compareTo() properly.


Since you need to roll many times in the chance_overlap function, you might want to optimize making n rolls, using random.choices (Python 3.6+):

from itertools import groupby

def roll(die, n=1):
    if n == 1:
        return random.choice(die)
    return random.choices(die, k=n)

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

def overlap_chance(*dice, n=1000):
    rolls = [roll(die, n) for die in dice]
    equal_rolls = sum(all_equal(roll) for roll in zip(*rolls))
    return equal_rolls / n

Here I chose to include it in your roll function, which is nice because you only have on function, but you do have different return types depending on the value of k, which is not so nice. If you want to you can make it into two separate functions instead.

I made chance_overlap take a variable number of dice so it even works for more than two (and also for one, which is a bit boring).

In addition, I followed Python's official style-guide, PEP8 for variable names (lower_case).

The all_equal function is directly taken from the itertools recipes.

Using a Monte-Carlo method to determine the chance for the dice to get the same values is fine, but you could just use plain old math.

Each distinct value \$j\$ on each die \$i\$ has probability \$p^i_j = n^i_j / k_i\$, where \$k_i\$ is the number of faces of die \$i\$ and \$n^i_j\$ the number of times the value \$j\$ appears on that die. Then the chance to have an overlap is simply given by

$$
P(overlap) = \sum\limits_j \prod\limits_i p^i_j = \sum\limits_j \prod\limits_i n^i_j / k_i,
$$

where \$i\$ goes over all dice and \$j\$ over all values present on any dice (with \$n^i_j = 0\$ if value \$j\$ does not appear on die \$i\$).

In other words dice rolls are independent events and e.g. the chance to get two heads or two tails with a fair coin (dice = [["H", "T"], ["H", "T"]]) are \$P(HH \vee TT) = P_1(H)\cdot P_2(H) + P_1(T) \cdot P_2(T) = 0.5\cdot0.5 + 0.5\cdot0.5 = 0.5\$.

from collections import Counter
from functools import reduce
from itertools import chain
from operator import mul

def overlap_chance_real(*dice):
    all_values = set(chain.from_iterable(dice))
    counters = [Counter(die) for die in dice]
    lengths = [len(die) for die in dice]
    return sum(reduce(mul, [counter[val] / length
                            for counter, length in zip(counters, lengths)])
               for val in all_values)

The nice thing about this is that we don't need to worry if not all dice have the same values, since Counter objects return a count of zero for non-existing keys.

For dice = [[1,2,3], [1,1,1]] it returns the correct (and precise) value of 0.3333333333333333. and 0.5 for dice = [["H", "T"], ["H", "T"]].

The execution time of the first function (overlap_chance)  increases linearly with the number of dice (all six sided) and it is in general slower than the second function (overlap_chance_real):

With two dice with increasing number of faces the first function is slower but basically constant in time while the second function is faster but the time increases with the number of faces. This plot also contains your function (since it can only deal with two dice it was not included in the previous plot), which is slower than both:


Rebase values in an array to match the chart scale

Even though there is not much code to review a few remarks:

returnable has a hard coded length. Should your input array ever need to be larger you'd have to remember to make this larger as well. A simple

var returnable = new long[count.Length];

would eliminate any need to worry about this ever again.
Given the current data constraints it's not really a problem but multiplying by max first could yield in an overflow. It might pay off to store the scaling factor as double instead (in which case it can also be pre-calculated).
Using LINQ would make the code a bit bit more concise.

Refactored method:

private long[] NormalizeDataset(long[] count, long max)
{
    double scale = max / (double)count.Max();
    return count.Select(x => x * scale).ToArray();
}

Given that scale is probably around the order of 100 and that the scaling is more or less an arbitrary choice you could just not use double for the scale.


You don't need to floor the result of an integer division: the result is exactly the same without it.

When getting the mid value, this is safer:

mid = lo + (hi - lo) / 2;

This way you'll be safe from integer overflows, which can happen when adding two very large integers. (Or long, you get the point)

As you notice, there is some redundancy in the logic of seeing the mid before the main while loop and then again inside the loop, and also in the conditions within the loop and after it. Probably you can refactor this without redundancies, with most logic inside the loop, and almost nothing outside. There should be a return statement inside the loop when the element is found. The empty check will become unnecessary, as the loop condition will never be true for empty input.

template<class T>
long binary_search(const std::vector<T>& v, const T& key){
    long lo = 0;
    long hi = v.size();

    while (lo < hi) {
        long mid = lo + (hi - lo ) / 2;

        if (v[mid] == key) {
            return mid;
        }
        if (v[mid] < key) {
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }

    return -1;
}


Checking whether a word satisfies a template with wildcards

Let's omit the first 3 conditions (for now).

wordFitsTemplate :: Template -> Hand -> String -> Bool
wordFitsTemplate (t:ts) hs []
    | t == '?'                      = wordFitsTemplate ts hs []
    | otherwise                     = False
wordFitsTemplate ('?':ts) hs (s:ss)
    | s `elem` hs                   = wordFitsTemplate ts (delete s hs) ss
    | otherwise                     = False
wordFitsTemplate (t:ts) hs (s:ss)
    | t == s                        = wordFitsTemplate ts hs ss
    | otherwise                     = False

First, we can see that if we have an empty array, we're going to just check if the rest of the string is full of question marks. Let's reduce that case first. (This gives us the additional benefit of covering the case where we are given an empty template and string)

wordFitsTemplate :: Template -> Hand -> String -> Bool
wordFitsTemplate ts hs [] = all (== '?') ts
wordFitsTemplate ('?':ts) hs (s:ss)
    | s `elem` hs                   = wordFitsTemplate ts (delete s hs) ss
    | otherwise                     = False
wordFitsTemplate (t:ts) hs (s:ss)
    | t == s                        = wordFitsTemplate ts hs ss
    | otherwise                     = False

This is sort of messy, so let's introduce a helper function which checks a char from the template and the string. It returns a boolean indicating if it matches and the hand.

charFitsTemplate :: Char -> Hand -> Char -> (Bool, Hand)
charFitsTemplate t hand c
    | t == '?' && c `elem` hand = (True, delete c hand)
    | otherwise = (t == c, hand)

Let's redefine our wordFitsTemplate function now.

wordFitsTemplate :: Template -> Hand -> String -> Bool
wordFitsTemplate ts _ [] = all (== '?') ts
wordFitsTemplate (t:ts) hand (c:cs) = isFit && wordFitsTemplate ts newHand cs
    where (isFit, newHand) = charFitsTemplate hand t c
wordFitsTemplate _ _ _ = False

It should be noted that when isFit evaluates to False, the function returns False; otherwise, when it evaluates to True, the result of the function depends on wordFitsTemplate ts newHand. Hence, we can combine them using &&.

This is the closest I could get to a nice solution. :) In functional programming, it's best to think of how to compartmentalize the problem and make it more elegant. In this case, we seperated the checking of whether a character matches (as well as the hand handling, no pun intended) with checking the template string. This gives us a rather elegant solution.


You're calling Math.sin() and Math.cos() twice as many times as you need to.

double cosine = Math.cos(radians)
double sine = Math.sin(radians)
Vector2 rotated = new Vector2(x*cosine - y*sine, x*sine + y*cosine)

If the angle never changes, then just save the values cosine and sine so you don't have to compute them over and over again.


Get the value of the precedent day in a pivot table

IIUC you can check for your conditions with pd.Series.where:
pt = raw.pivot_table(index=['GROUP_ID', 'DATE'], columns=['NAME'], values=['VALUE'])

s = pt["VALUE"].groupby(level=0)["C"].shift()

pt[("VALUE_PREV","C")] = s.where(s.notnull(), np.NaN)

print (pt)

                    VALUE            VALUE_PREV
NAME                    A     B    C          C
GROUP_ID DATE
123456   2020-07-01  10.0  25.0  0.0        NaN
         2020-07-02  17.0  23.0  NaN        0.0
789012   2020-07-02  11.0  19.0  NaN        NaN
         2020-07-03   8.0  21.0  NaN        NaN


Sending SMS through twilio from play framework

As I'm new to scala, I don't feel I could generate the appropriate code, but I wanted to make a couple points.
First, your method is doing way to much.  I see validation, I see messing with a request object, I see sending the SMS, I see response generation.  From my point of view, when looking at this method, you can't tell what is going on without a lot of effort.  So my recommendation would be to add more methods.  If I were writing this, I would have an outer method that abstracts away the HTTP portions of your code
sendSms should pull the string value from the request and then delegate to parseSmsPhoneNumber (or something like that) to perform the logic of validating the string.  My second suggestion with this method is that it not return a string, but a type safe object.  Now that you have a type safe smsPhoneNumber, you could write another method that does the status checks: is the number blocked?, ...  Now that we know everything is good, create a method that takes the smsPhoneNumber and actually sends it.  The last bit I would emphasis is that the JSON response generation should happen within sendSms.  The other methods will return values types or throw exceptions so signal when bad things happen.  Keep all of you HTTP related code isolated to sendSms.
Update:
Below is my take at trying to break your code apart.  It is completely untested and there is almost certainly no way that it compiles, but I think it does a reasonable job of demonstrating how you could break things down.  So, just think of it as pseudo code that looks similar to scala, but not actually scala.
First, note that I convert things from strings to a type safe type as soon as I possibly can with parseSmsPhoneNumber() and parseSmsDeviceId().  Note that they return an option instead of the actual types.  You probably could throw exceptions as well, but I preferred this.  The next thing I did was create a bunch of case classes.  This is to abstract out the status of situations from happening.  There could be a different way to do it, but I liked using case classes because they seem to work with within matches.  Next I isolate all of the sending of the sms to withing doSendSms; notice how the exceptions stay within this method.  There really isn't any benefit of having the API specific exceptions spill out.  If you ever need to change service used to send SMS, then you would only need to modify this one method.  Lastly, notice how all of the HTTP related objects (request and response) are isolated to within sendSms.  Perhaps you want to do a similar process but without being attached to a request (such as a timed job), with the HTTP information isolated, then this is nearly trivial.
I agree that my pseudo code below still needs more work (i don't like the if/else plus two matches in sendSms, I feel it should be "flatter"), but this is the best I can do right now.  Hopefully, some of my points make more sense with some pseudo code.
Completely Un-Tested/UnCompiled Code
val invalidEX = List(21211, 21614, 21608, 30006, 30005, 21604, 21601, 14101)
val reachEX = List(21612, 30004)

case class SmsPhoneNumber(value: String)

def parseSmsPhoneNumber(valueAsString: String): Option[SmsPhoneNumber] = {
  if(valueAsString.length<=6||valueAsString.length>=18) {
    return Some(SmsPhoneNumber(valueAsString))
  } else {
    return None
  }
}

case class SmsDeviceId(value: String)

def parseSmsDeviceId(valueAsString: String): Option[SmsDeviceId] = {
  if(valueAsString.length<=8||valueAsString.length>=150) {
    return Some(SmsDeviceId(valueAsString))
  } else {
    return None
  }
}

sealed trait SmsPhoneNumberStatus
case class SmsNotNeeded extends SmsPhoneNumberStatus
case class NumberBlocked extends SmsPhoneNumberStatus
case class NumberTemporarilyBlocked extends SmsPhoneNumberStatus
case class Valid extends SmsPhoneNumberStatus

def checkSmsPhoneNumberStatus(smsPhoneNumber:SmsPhoneNumber) :SmsPhoneNumberStatus = {
  if (!smsNeeded(smsPhoneNumber)) {
    return SmsNotNeeded
  } else if (!numberBlocked(smsPhoneNumber)) {
    return NumberBlocked
  } else if (todayBlocked(smsPhoneNumber)) {
    return NumberTemporarilyBlocked
  } else {
    return Valid
  }
}

def buildMessageBody(code:String,appLang:String):String = {
  if (appLang.equals("en"))  {
    return Messages("sms_body", "\n", code)(Lang(appLang))
  } else {
    return Messages("sms_body", "\n", code)(Lang(appLang)) + "\n" + Messages("sms_body", "\n", code)(Lang("en"))
  }
}

sealed trait SentSmsResult
case class InvalidNumber extends SentSmsResult
case class UnreachableNumber extends SentSmsResult
case class Error(message:String) extends SentSmsResult
case class Success extends SentSmsResult

def doSendSms(recipient:SmsPhoneNumber,body:String):SentSmsResult = {
  try{
    TwilioAPI.sendSMS(recipient, body)
  } catch {
      case twilioEx: TwilioRestException =>
        if (invalidEX.contains(twilioEx.getErrorCode))
          return InvalidNumber
        else if (reachEX.contains(twilioEx.getErrorCode))
          return UnreachableNumber
        else {
          return Error(twilioEx)
        }
      case e: Exception =>
          return Error(e.toString)
    }
}

def sendSms = Action { implicit request =>
    val smsPhoneNumber = parseSmsPhoneNumber(request.body.asFormUrlEncoded.get("number").head)
    val smsDeviceId = parseSmsDeviceId(deviceId)//not sure where devideId came from

    if(smsPhoneNumber.isEmpty() || smsDeviceId.isEmpty()) {
      Ok(write(Map("result" -> "error")))
    } else {
      checkSmsPhoneNumberStatus(smsPhoneNumber.get) match {
        case SmsNotNeeded => Ok(Json.obj("response" -> "regular"))
        case NumberBlocked => Ok(Json.obj("response" -> "permanentblocked"))
        case NumberTemporarilyBlocked => Ok(Json.obj("response" -> "temporaryblock"))
        case Valid => {
          doSendSms(smsPhoneNumber,buildMessageBody(random6Digit,request.acceptLanguages(0).code.toString.splitAt(2)._1 )) match {
            case InvalidNumber =>  {
               Ok(Json.obj("response" -> "invalidNumber"))
            }
            case UnreachableNumber =>  {
               Ok(Json.obj("response" -> "unreachableNumber"))
            }
            case e:Error =>  {
              Future { models.LogFile.errorLogs(Json.obj("route" -> request.tags, "post" -> request.body.asFormUrlEncoded.toString, "address" -> request.remoteAddress, "error" -> e.message).toString) }
              Ok(Json.obj("response" -> "error"))
            }
            case Success =>  {
              Future {todayEntry(smsTo) }
              Ok(Json.obj("response" -> "success"))
            }
          }
        }
      }
    }
  }


Searching for selectors not using document.querySelector/document.querySelectorAll

Your method doesn't work because it fails to select elements outside the body.

I think what you were supposed to do is:

split the input into class / ID / tagName (using REGEX or whatever)
request elements using document.getElementByID() / document.getElementsByClassName() / document.getElementsByTagName()
return only the elements that match all 3 requests.

Essentially, you code your own querySelectorAll function.


Multi jQuery Sliders, Help me write this in better code

When you have code that repeats itself like that, you want to try and separate the logic from the values. Something like this would work, and you just have to add more to the settings object when needed. It's not jQuery that's badly written, you just have to change the way you're using it. http://jsfiddle.net/Sqg8A/5/

$(function() {
    var settings = {
        "yield" : {
            range: true,
            min : 15.2,
            max : 308,
            step : 0.3,
            values : [75.8, 241.4]
        },
        "tensile" : {
            range: true,
            min : 37.7,
            max : 345,
            step : 0.3,
            values : [81.2, 243.3]
        },
        "elongation" : {
            range: true,
            min: 1.0,
            max: 77,
            step: 0.1,
            values: [14.5, 43.2]
        } //Add more if needed
    }

    $.each(settings, function(key, value){
        var _key = key;
        $( "#" + _key ).slider(
            $.extend(value, {
                slide: function( event, ui ) {
                    $( "#" + _key + "-value" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
                }
            })
        );
        $( "#" + _key + "-value" ).val( $( "#" + _key ).slider("values", 0) + " - " + $( "#" + _key ).slider("values", 1));
    });
});


Call WebAPI then parse part of json result

HttpClient client = new HttpClient();

This needs to be disposed.

using (var response = client.GetAsync(urlParameters).Result)

Why don't you await this like you do with other awaitable APIs?

static async Task<List<Hero>> GetHero(string url, string urlParameters)
{
    ..
    return null;
}

Methods returning collections should return an empty collection instead of null this means you should

return Task.FromResult(new List<Hero>());

As far as the if block is concerned you don't need the heros variable. With LINQ can create the list inplace:

if (response.IsSuccessStatusCode)
{
    var jsonResult = await response.Content.ReadAsStringAsync();
    var deserializedjsonResult = JObject.Parse(jsonResult);
    var resultHeroes = deserializedjsonResult["result"]["heroes"];
    return resultHeroes.Select(x => x.ToObject<Hero>()).ToList();
}


Simple multiple producer and single consumer concurrency pattern

So currently the WaitGroup is not being used to wait for the producing to complete.  This means that it is possible for this programme to run without producing any results as each go produce() is done in it's own go routine so true can be sent immediately to dummy if the main go routine gets all the CPU time thus main exits with nothing being printed.

Personally I would use the WaitGroup to do the waiting and then close the msgs channel to indicate to the consume that it is done and use a further WaitGroup to then indicate to main that consume is done.

In addition to the concurrency parts, I also wouldn't use global variables but instead pass them into the functions that use them.   Putting this together then you get:

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

func main() {
    msgs := make(chan int)

    // Start the consuming go routine before producing so that we can then just wait for the producing
    // to complete on the main go routine rather than having to have a separate go routine to wait to
    // close the channel.
    var consumeWG sync.WaitGroup
    consumeWG.Add(1)
    go consume(msgs, &consumeWG)

    var produceWG sync.WaitGroup
    numberOfProducers := 10
    for i := 0; i < numberOfProducers; i++ {
        produceWG.Add(1)
        go produce(msgs, &produceWG) // Multiple producers
    }

    // Wait for producing to complete then tell the consumer by closing the channel.
    produceWG.Wait()
    close(msgs)

    consumeWG.Wait()
}

func produce(msgs chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    msgs <- getRandomIntegerNumber()
}

// Single consumer
func consume(msgs chan int, wg *sync.WaitGroup) {
    // Range of msgs, this will consume all messages in the channel then exit when the channel is closed.
    // This provides communication between the go routines when completion has happened as well as not
    // leaking the consuming go routine as would happen with an forever loop.
    for msg := range msgs {
        if msg%2 != 0 {
            fmt.Printf(" The number %d is odd \n", msg)
        }
    }
    wg.Done()
}

func getRandomIntegerNumber() int {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(1000)
}


Add "1" and overwrite the previous value

I think what you may be looking for is found on this page.

  This is happening because of the ++ being used as a post-increment
  instead of a pre-increment. Essentially what is happening is you're
  saying, "set $cookie to the value of $_COOKIE['count'], and then
  increment $_COOKIE['count'].

Go for ++$_COOKIE['mycookie']; instead and let us know how that works out.


Is it bad design if I create repostory with methods that returns generic types.

Not at all. It's very useful.

  Is this the proper way of doing that?

I'm not entirely sure because even though you use a generic return type you use the same User table for all of them:

this.context.User

However if the IRepository provides different User tables where each of the different users implement the TUser then I'd say it' fine. Otherwise it would not be that usefull and you could just return the normal User.


If you can go ES6, you can get a more concise version:

Object.keys(o).reduce((c, k) => (c[k.toLowerCase()] = o[k], c), {});

Now, if one or more strings lowercase into the same string, expect only one of them to remain.


Ideas for reducing repetition in control binding

I'd create an extension method that calculates the day by the name of the checkbox.

I'm using dynamic because I don't know the name of your domain class, just replace it with your name.

Also note, I'm using the web version of CheckBox, substitute ID with whatever version you are using.

Here is the class for the extension:

public static class CheckboxExtensions
{
    public static void DetermineStateFromModel(this CheckBox me, dynamic myModel)
    {
        if (!me.ID.Contains("chkValidDay"))
        {
            // Could throw an exception if required.
            return;
        }

        var dayOfWeek = DayOfWeekFromString(me.ID.Replace("chkValidDay", string.Empty));

        me.Checked = myModel.ValidDaysOfWeek.Contains(dayOfWeek);
    }

    private static DayOfWeek DayOfWeekFromString(string dayOfWeek)
    {
        switch (dayOfWeek)
        {
            case "Mon":
                return DayOfWeek.Monday;
            case "Tue":
                return DayOfWeek.Tuesday;
            // ...
            default:
                throw new ApplicationException("Invalid dayOfWeek specified.");

        }
    }
}

Then your calls would be

chkValidDayMon.DetermineStateFromModel(myModel);
chkValidDayTues.DetermineStateFromModel(myModel);
...

Another thing you might look into is to put the CheckBox objects into a list, then you could just iterate it:

dayCheckBoxList.ForEach(checkBox => checkBox.DetermineStateFromModel(myModel));

Another note, Hungarian casing on variables is not really accepted anymore.  It clutters up the code, and there are too many variable types to abbreviate them all to 3 letters.  Read this.  A better naming convention would be mondayIsValidCheckBox.  You would have to modify my extension method to use this new convention.


Displaying MySQL table data using Node.js

Some thoughts:

You should consider using const when declaring your dependencies instead of var
The listener function you are passing to your http.createServer() call should really only serve as a generic request handler which, as you grow your application, should probably hold request routing logic.  Your current approach limits what your server can do to only calling the fetchActors() function. Since it is such a key function, you also may want to consider making it a named function vs. a closure, such that you would have something like http.createServer(requestHandler);  This would make the requestHandler function itself much more easy to unit test if you get to the point of embracing that approach in your application development.
Consider setting a constant for your port that you can refer to and potentially change more easily than having to get to where the listen() function is called.
You should really not be using root mysql user in any application. Define a user for the application and use it.
You should ideally inject things like database credentials into the environment, rather than hard-coding them in your code.
You are kind of in an in-between state with regards to managing you DB connection(s).  Right now, you have a single connection that would be reused to satisfy all incoming requests, meaning that if you have high request concurrency, you could have a bottleneck of queries piling up against that connection.  I would suggest you  use a connection pool (something supported directly some mysql package) if you want to share connections across request (even if that "pool" consists of only a single connection right now), or you make per-request connections to your database (i.e. move the call to connect() into the request handling process).
I am not seeing what value you derive from your executeQuery() function. You are just throwing an error (something you are then not handling at all in your calling fetchActors() function, ans something you should probably not be doing anyway since you are working within an asynchronous function). You are not using fields parameter at all, so you are actually removing information that a caller may need or could have if they just worked with mysql query() function directly.
Since you are not handling errors at all either in executeQuery(), fetchActors(), or via listener for error event on the connection itself, you have introduced fragility in your application.  If you had an error at any of these stages in query execution, it would end up being uncaught, thus stopping your entire node process!!!  You need to understand the difference between synchronous and asynchronous error handling in NodeJs (this is a good resource for learning. Whenever you are working with a package, you should strive to understand it's error handling approach. Look at the error handling section of the documentation for mysql package.  Make sure you have facility in a web application like this to deal with unhandled errors (both synchonous and asynchronous) so that they won't inadvertently kill your process (unless that is desired behavior) and such that you can still deliver a meaningful message (i.e. HTTP 500 response) to the calling client.
You should strive to decouple the data retrieval/business logic portions of your application from the display rendering aspects.  Your fetchActors method here is really bad in this regard. Ideally, upon successful retrieval of data from database, you should hand the returned data structure to a separate method (ideally using some sort of display templating) for rendering to HTML.  That way you might ultimately get better reuse from your methods, for example is you wanted to return JSON, XML, HTML, etc. renderings derived from single method to retrieve the data.
Don't use SELECT * queries.  They are usually wasteful of bandwidth, and can actually introduce fragility into your application if you make changes to the table over time.
You have a bunch of unnecessary comments that you really should just drop, as the code should be (and generally is) self-explanatory.


Close what you open

words = [line.rstrip() for line in open('wordsEn.txt')]

Here you opened a file but you did not close it! In fact I suggest to use with that will handle closing automagically.

with open('wordsEn.txt') as f:
    words = [line.rstrip() for line in f.read()]

Let the user change the file

You should let the user input as an optional arg his own filename, I may have my own wordlist that is not called exactly: 'wordsEn.txt', the dafault file should be None (You read directly from the webpage).

set built-in operations

If you change the below line to be:

words = set([line.rstrip() for line in f.read().splitlines()])

You can then use set intersection:

legalwords = perms & words

To enhance both clarity and performance.

Allowing long words

The complexity of finding all the permutations of a word is O(N!): for a mere 20 characters word that means 2.432 * 10**18 combinations, I suggest comparing the sorted words for better efficiency if you need to run the script with long words.


Prevent multiple async calls from all attempting to refresh an expired OAuth token

What about modifying the return of _fetch()? Inside the if statement that checks you could have it return false or a custom error code at that point. And then back one scope, catch the return of _fetch() and test it against your error code or false then just handle it appropriately. Either escaping out with return or reauthorizing in between.


You've essentially created a "View Model" for your API requests, which there's nothing wrong with doing that. Sometimes you want to abstract away your internal Domain Model and not have it exposed as params in the request.

That being said, you can DRY things up a bit by creating a base class:

class ApiModel
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Naming

  EMAIL_FORMAT = /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i

  def initialize(attributes = {})
    attributes.each do |name, value|
      raise KeyError, "Attribute key '#{name}' is not supported" unless respond_to? "#{name}="
      send "#{name}=", value
    end
  end

  def persisted?
    false
  end
end

Now your EmailChecker class becomes a 4-liner:

class EmailChecker < ApiModel
  attr_accessor :email
  validates_format_of :email, :with => EMAIL_FORMAT
end

Next, I'd like to focus on the initialize method. In your version:

def initialize(attributes = {})
  attributes.each do |name, value|
    send("#{name}=",value)
  end
end

The send method call is left unguarded. You can specify keys in the Hash that do not correspond to setter methods in your object, leaving developers scratching their heads about why a method is not supported. Instead, this is an opportunity to fail early, and fail loud[er]. I would test to see if the attribute key is a valid setter, and then throw your own exception:

def initialize(attributes = {})
  attributes.each do |name, value|
    raise KeyError, "Attribute key '#{name}' is not supported" unless respond_to? "#{name}="
    send "#{name}=", value
  end
end

Raising a KeyError is more appropriate here, because the real problem is having an incorrect key in the attributes argument. The error message is informative to developers so they can fix the problem, yet does not give away any secrets.

For instance, if you send { foo: 'bar' } as the attributes, then you'll get the following error message:

  KeyError: Attribute key 'foo' is not supported

The persisted? method is kind of confusing to me. This object is not persisted, so why even have this method? Unless this is overriding functionality baked in from the ActiveModel mixins, I would just remove it.


One of Python's greatest strengths is its built-in capability to use sets directly. I don't feel you've used sets to their fullest extent here. I'd also like to point out the with statement, which you should probably use to handle file handles.

from __future__ import with_statement
import sys
from string import ascii_lowercase
filepath = sys.argv[1]
wholealphabet = frozenset(ascii_lowercase)

# Use with to handle file … handles
with open(filepath) as f:
    for line in f: # assume a line is a sentence, not exactly per spec?
        # sortedletters = list(set(line.lower())) # guaranteed to be *unsorted*
        missingletters = wholealphabet.difference(line.lower())
        if missingletters:
            print ''.join(sorted(missingletters))
        else:
            print 'NULL'

That's really all you need. Unless you want to reconsider the definition of a sentence. :)


Find the number of K-Complementary pairs in an array

Current algorithm

The time complexity of the current solution is O(N²): for a given array of length N, it needs to loop through its elements from 0 to its length, and then for each of those, loop again through the elements after it. Note that it is still O(N²), even with the logic of avoiding duplicate indexes (if the pair (0,1) was a solution, it always follows that (1,0) is one, so we don't need to test it).

About the code itself, the first for loop is deceiving:

for(int i=0;i<=arr.length;i++){
    for(int j=i;j<arr.length-1;j++){
        if(arr[i] + arr[j+1] == k){

It makes the reader think that i will go up to arr.length. What's worse, it makes the reader think the algorithm fails because we fetch arr[i] later on, which cannot work for arr.length (and would fail with an ArrayIndexOutOfBoundsException). In reality, it won't, because there is a second inner loop of j going from i to arr.length-1, so when i is greater than arr.length-1, nothing will happen anyway.

I suggest making that clear in the bounds used. Consider having:

for(int i=0;i<arr.length-1;i++){
    for(int j=i;j<arr.length-1;j++){
        if(arr[i] + arr[j+1] == k){

In the same way, instead of reasoning with j+1, you could have j loop through its natural bounds and reason with j:

for (int i = 0; i < arr.length - 1; i++) {
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] + arr[j] == k) {

With those bounds, it's clear to everyone reading the code that no out of bounds exception can happen. Note also how I added white spaces around the different operators and calculations: it adds to clarity.

Also, maybe I wouldn't make this method an instance method, rather a static one that is directly invoked in main.

Better performance

It would be possible to solve this problem in O(N) time complexity, instead of O(N²), at the expense of also being O(N) in terms of memory.

The idea is that we want to avoid looping through the array again and again. Here's another approach:

Go through the array once, and store in a Map the difference of the wanted sum and the current element mapped to how many times it occured. Effectively, this map remembers how much we're missing for an element at a given index so that the sum can be reached.
Go through the array a second time, and check whether the map contains this element. If it does, then it means that our map contains an element e for which e = sum - arr[i], so it means that we've found a matching pair. And the number of matching pair we found, is the number of times this element appears in the array, which is the value of the map.

That's how it would look like with the example in the question where the sum to look for is 1:

          arr =  4   5   6   3   1   8  -7  -6
1st pass, map = -3  -4  -5  -2   0  -7   8   7  <-- how much we need to add to find the sum
    2nd pass  =  x   x   x   x   x   o   o   x  <-- the initial array only contains the element marked o

This shows that there are 2 such pairs, and that is the answer. As an example of putting this into code, and using Java 8, you could have:

public int noOfComplementaryPairs(int arr[], int k) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < arr.length; i++) {
        map.merge(k - arr[i], 1, Integer::sum);
    }
    return Arrays.stream(arr).map(element -> map.getOrDefault(element, 0)).sum();
}


A classic solution to this problem is to use a data table - in your case probably in form of a dictionary. It depends of what type your values are - I assume they are some sort of view models? I'm also going to assume they have a common base class:

One time setup:

Dim dict As New Dictionary(Of String, ViewModelBase)
dict.Add("dashboard_home_vm", _Locator.DashboardHome_VM)
...

You can look them up simply by

Dim vm As ViewModelBase
If (dict.TryGetValue(Param.ToLower, vm)) Then
    return vm
End If
return Nothing

Adding a new view model would be achieved by simply adding a new entry to the dictionary.


Implement a boto3 RDS generator in Python

Your code is a little hard to read, mostly due to you moving what should be an inner for loop, to be two ifs in an infinite while loop.
If you were to instead for loop over pool, then you could make the code easier to understand.

I'd also make page_size be a keyword argument, so the user can change the page size if they wish. And I'd change config to region, as it makes little sense to me, why you're passing a dictionary to extract a single key.

def all_rds_instances(region, page_size=20):
    """
    Gets all the RDS instances in a generator (lazy iterator) so you can implement it as:
    `for instance in all_rds_instances(region):`

    page_size [explain what this does] should be bound between 20 and 100.
    """
    client = boto3.client('rds', region_name=region)
    marker = ""
    pool = []
    while True:
        for instance in pool:
            yield instance

        if marker is None:
            break
        result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
        marker = result.get("Marker")
        pool = result.get("DBInstances")

This makes reading the code easier, you know that it will exhaust the pool straight away when reading it, and it makes understanding how you infinitely loop a little easier too.


Creating a Deprecated/Obsolete behavior for methods in a JavaScript library

From looking at your fiddle, the first thing I would do is make sure that your function is not anonymous:

// new function implementation
var Chart = function Chart(name, data) { //See what I did there?
    this.name = name;
    this.data = data;

    console.log("Chart > constructor");
}

Then, to keep it KISS, I would

// obsolete helper function
var ObsoleteWithReplacement = function( f ) {
    var wrapper = function() {
       console.warn("This function is now called " + f.name );
       f.apply(this, arguments);
    }
    wrapper.prototype = f.prototype;
    return wrapper;
}

Because the function is no longer anonymous, you can now use f.name, you no longer have to provide it. The drawback is that the new old function name is not logged, I think any JS developer could figure that one out.

Then you can do this:

// old deprecated function
var chart = ObsoleteWithReplacement(Chart);

The name ObsoleteWithReplacement is unfortunate, I would use simply Obsolete. Also I think function Obsolete(){..} makes more sense than var Obsolete = function Obsolete(){..}, var Obsolete = function (){..} should be avoided since it creates an anonymous function.

I forked this to http://jsfiddle.net/konijn_gmail_com/8a5Ax/


Here's my take, with explanations below:

def print_calendar(offset, month_length)
  puts "Mon Tue Wed Thu Fri Sat Sun"
  dates = [nil] * offset + (1..month_length).to_a
  dates.each_slice(7) do |week|
    puts week.map { |date| date.to_s.rjust(3) }.join(' ')
  end
end

I'd call the first parameter offset rather than day_of_week. For one, day_of_week would seem to imply that you can use a Date object's wday as the offset, but wday's range is 0-6, with zero being Sunday, so that won't work. Also, with day_of_week I wonder if you mean a day's name, or its number? Oh, and which week are we talking about? The name offset is a lot more generic, but that might be a good thing here.
I've also spelled out print_calendar and month_length entirely. While those names weren't too confusing, there's no reason to skip a few letters.
Also note that the offset behaves slightly different from yours: In your method, the minimum offset is 1. That makes sense if you think "start on the 1st day", but it makes less sense if you think "offset everything by 1". So here, the minimum offset is zero.
Array#join is a nice method to know when you have to print lists of stuff (in any language, not just Ruby).  You could have done puts %w(Mon Tue Wed Thu Fri Sat Sun).join(' ') instead of your first 3 lines. But the end result would be no different than simply printing a hard-coded string, so that's what we're doing here instead.
In Ruby, you rarely have to use while loops. Generally, it's easier to construct and manipulate arrays using the built-in methods in Array and those mixed-in by the Enumerable module. (Seriously, if you're learning Ruby, go read as much as you can from those two links; it's some the most useful stuff in Ruby, and you'll be using it a lot.)
Here, we're constructing a dates array of nils that's offset items long by using Ruby's nifty ability to multiply an array by a number. Then we use + to concatenate that array with an array that's just the numbers 1..month_length.
In other words, dates consists of zero or more "blanks" (the offset) followed by the date numbers of the month.
each_slice should be fairly self-explanatory: Go through an array, X items at a time. In this case we go through it 7 items at a time (i.e. a week), which is what we need for each row/line of text.
Each of these weeks are just arrays of nils and/or numbers, so we convert each of them, using map, to an array of strings. Each blank/number is first converted to a string, and then padded with spaces using rjust. Finally, this mapped array is joined and output.

And that's it, really.

Calling print_calendar(2, 31) will print the following:

Mon Tue Wed Thu Fri Sat Sun
          1   2   3   4   5
  6   7   8   9  10  11  12
 13  14  15  16  17  18  19
 20  21  22  23  24  25  26
 27  28  29  30  31

However, it'd be even more idiomatic to let the method simply return the text without printing it. That could be done like so:

def format_calendar(offset, month_length)
  lines = [ "Mon Tue Wed Thu Fri Sat Sun" ]
  dates = [nil] * offset + (1..month_length).to_a
  dates.each_slice(7) do |week|
    lines << week.map { |date| date.to_s.rjust(3) }.join(' ')
  end
  lines.join("\n")
end

After which you can do something like

puts format_calendar(2, 31)

to print it.

Edit: As Naklion's answer rightly points out, it'd be even nicer to return an array of strings (the individual lines of text). In this case, you can do so by simply omitting the .join("\n") on the last line of the method above. That'll give you more structured data to work with, instead of a text blob.
As for printing, you don't need to change anything, since puts automatically adds linebreaks when printing an array.


Similar to this one: Minimalistic mysql db class

To answer your question: NO!

The short answer: Throw away your code, burn it, do whatever you want with it but never use it in a production enviroment. Just don't.

The long answer: Again, don't use this code, ever. You are even violating nearly every SOLID rule

As far as I can see you are trying to write some wrapper around the mysqli object. But the question remains: why? and what problem are you trying to solve?

As far as I can see, you are trying to solve 2 problems with one solution. Oh oh, this is doomed to fail. You want to solve the problem of always having to check wether an instance of mysqli exists or not and you want to not have to worry about connecting and creating a mysqli instance and query-ing/sanitizing the database with a given query. 3 different things.

Then you start designing the solution to that problem. When that is done, you should take a step back and ask the question 'Is my code easy to use?' and 'Is it easy configurable and extendable?' and most important 'is it easy to debug?'.

The answer to those 3 questions is simple: NO!

If you want to change a connection parameter you have to change the
code of the class itself, bad bad bad.
If something goes wrong (an exception) you echo an error message. So
what if I first get an instance of your database and it echo's some
error message, and then my code sends a header(); . Ooeehh, a nice
header allready sent error. Hf debugging that error...
...

But in fact, that isn't your real problem. The real problem you have is that you are writing code without designing it.

If your problem is that you want only one instance to exist you should only create one instance instead of relying on a get_instance() function or Singleton pattern. If a class needs a database connection, pass it in in the __construct(). More on this topic:

http://www.slideshare.net/go_oh/singletons-in-php-why-they-are-bad-and-how-you-can-eliminate-them-from-your-applications
https://stackoverflow.com/questions/1812472/in-a-php-project-what-patterns-exist-to-store-access-and-organize-helper-objec

To sum up, sometimes the problems we are solving tend to be meta-problems. The solution we make is actually a fix. A good article on this: http://thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx

On a complete diffrent note, instead of using mysqli. use PDO.
This is a realy nice OO way of using a database. more on pdo:

http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
http://www.php.net/manual/en/class.pdo.php


Directly initialize variable from std::istream

There are corner cases where this will not work or even worse produce silent errors.

The function as it is, depends on the client to check for errors on the stream (either by calling std::cin.exceptions(std::ifstream::failbit); or by checking the stream state, after the call to get).

Ideally, I would want to write:

if(auto a = get<int>(std::cin))
    // use a here

Maybe you could add something like this to your solution:

template<class T>
boost::optional<T> get_optional(std::istream& in){
    T tmp;
    in >> tmp;
    return (in) ?
        boost::optional<T>{ std::move(tmp) } :
        boost::optional<T>{};
}


In itself, there's nothing wrong with this code. There really isn't. But there are some things you need to consider:

The method is private, so it's an internal kind of factory, why not use a lazy-loading getter?
The method is private, that makes this method a dead-end in a scenario where, for example, the content-type needs to be changed
If you have access to the HttpPost class, why not add a method setEndPoint, so you don't need to create a new instance time and time again

On the whole, I'd start with changing the access modifier to protected, so that in a child class, you can do something like:

protected function createHttpPost($endPoint, array $options = null)
{
    if ($options === null)//default, use parent version
        return parent::createHttpPost($endPoint);
    $httpPost = new HttpPost($this->baseUri.'/'.$endPoint);
    $httpPost->setContentType($options['contentType'])
        ->setAccept($options['accept']);
    //and so on...
}

If you can alter the HttpPost class, I'd also encourage you to add methods that reset the instance to a pristine state (a state that allows another request). Then you can lazy-load this instance as a property, and reuse it:

protected function createHttpPost($endPoint, array $options)
{
    $httpPost = $this->getHttpPost();//see below
    $httpPost->setContentType($options['contentType'])
        ->setAccept($options['accept'])
        ->setEndPoint($this->baseUri.'/'.$endPoint);
    //and so on
}
/**
 * Lazy-loader for HttpPost instance
 * @return HttpPost
 */
protected function getHttpPost()
{
    if ($this->httpPost === null)
        $this->httpPost = new HttpPost;
    else
        $this->httpPost->resetInstance();
    return $this->httpPost;
}

This way, the constructor will only be called once, and only when the instance of HttpPost is required. Then, you can re-use the instance for each request.
If the instance of HttpPost is passed around, or a request is not made instantaneously, then there could be a risk of this request object losing its state, before a request is made. If this is possible, then of course, you don't use a lazy-loader like the one above, but just use a getter function, or keep doing what you do (ie: create an instance ad-hoc).


A GapHelper static class to create unique (non-existing) size restricted names

Possible Bug

Since Func<int, string> transform is not guarded against collisions (different int values may yield the same string result), the next line is wrong. It only checks for unique elements in the already available data items, not in the new results fetched from transform.

 if (hashSet.Contains( text )) {

This could be solved by trying to add each element to the set instead:

if (!hashSet.Add( text )) {

LINQ

Furthermore, I would use an IEnumerable to allow for some LINQ chaining.

public static IEnumerable<string> GetNextName(
  int maxSize, IEnumerable<string> items, Func<int, string> transform) {

So we could just call:

public class ProcessingTask : IProcessor {
    public void Execute( FileContent fileContent ) {
        GapHelper.GetNextName(5, fileContent.Components
            .Select(c => c.Name)).Take(20).Select(x
                => new Component { Name = x, Content = "Foo" })
            .ToList().ForEach(fileContent.Components.Add);
    }
}

Which yields better readability. Also a fun fact about disposing an enumerator from the initial code:

 using (var nameGenerator = // ..


Calculating exponential moving averages with multiples threads

Javadoc, Javadoc, Javadoc

Your variable names are all sub-par. Why the unnecessary abbreviations (f.e. Avg)? Why the odd prefixes (f.e. lValue)?

Here is my simple and ultimate tip when it comes to names:

  Name things after what they are doing or what they contain.

And my ultimate rule:

  You're never allowed to use one letter variable names, with the only exception being dimenstions.

/** The alpha. */
private static final double ALPHA = 0.9;

That is a prime example of an unhelpful comment.

Overall, I don't see why your class is static. It seems like it will be used like an instance class but you don't want to pass the reference around, you simply created a singleton here.

Consider creating an instance class and then pass the reference/instance to the threads which share that instance.


entab program which replaces 4 spaces with a tab

The biggest thing you can do to improve your C style (and this also goes for any curly-brace language) is to learn to love the for loop.

foo(i);
while (bar(i)) {
    something;
    baz(i);
}

should almost always be recast as

for (foo(i); bar(i); baz(i)) {
    something;
}

Examples from your code:

char *linep = line;
while (...) {
    while (*linep) {
        // body
        linep++;
    }
    printf("%s", line);
    linep = line;
}

should be

while (...) {
    for (char *linep = line; *linep != '\0'; ++linep) {
        // body
    }
    printf("%s", line);
}

(Notice that I added an explicit comparison with '\0' for clarity — since it doesn't affect the generated code — and I changed your statement "linep increment" to the more readable "increment linep." There's another reason to use preincrement over postincrement, but it doesn't matter until you get to C++.)

Here's another example:

void kick(char *x, char val) {
    char *sp = x;
    int i = 1;
    while (*x) {
        if (*x == val) {
            while (countx(sp) - i != x - sp) {
                swap(sp, x - sp, countx(sp) - i);
                i++;
            }
            *(sp + countx(sp) - 1) = 0;
            return;
        }
        x++;
    }
}

should be

void kick(char *sp, char val) {
    for (char *x = sp; *x != '\0'; ++x) {
        if (*x == val) {
            for (int i = 1; countx(sp) - i != x - sp; ++i) {
                swap(sp, x - sp, countx(sp) - i);
            }
            sp[countx(sp) - 1] = '\0';
            return;
        }
    }
}

Let's keep working on the kick function. The next thing I notice is that you repeatedly call this function countx(sp) inside a tight loop. Surely that's a performance hit; it would make more sense to cache the value once in a local variable and then use the variable. But let's see what countx(sp) actually does.

int countx(char* x) {
    int i;
    for (i = 0; x[i]; i++);
    return i;
}

Well, that's just strlen(x) (modulo some const-incorrectness). You should write

int countx(const char *x) {
    return strlen(x);
}

and then get rid of the countx function altogether. So now we have

void kick(char *sp, char val) {
    const int n = strlen(sp);
    for (char *x = sp; *x != '\0'; ++x) {
        if (*x == val) {
            for (int i = 1; n - i != x - sp; ++i) {
                swap(sp, x - sp, n - i);
            }
            sp[n - 1] = '\0';
            return;
        }
    }
}

Next, I notice that if (*x == val), we just do a bit more processing and then return. So we don't actually need that extra bit of processing to happen inside the loop; it makes more sense to say "loop until we find a val; then break the loop; then do more processing and return." Also, there's another convenient library function for the looping part of that: it's called strchr.

So the next most productive thing you can do for your programming skill is to learn to love the standard library.

void kick(char *sp, char val) {
    const int n = strlen(sp);
    char *x = strchr(sp, val);
    if (x != NULL) {
        for (int i = 1; n - i != x - sp; ++i) {
            swap(sp, x - sp, n - i);
        }
        sp[n - 1] = '\0';
    }
}

Okay, let's look at the remaining complexity in that kick function. What's this three-argument swap routine? I'm familiar with the idea of swapping two objects... does this rotate the three of them, or something?

...Ah, no, it's just doing some unnecessary array operations. Let's write it the normal two-argument way:

void swap(char *x, char *y) {
    char tmp = *x;
    *x = *y;
    *y = tmp;
}

... swap(&sp[x - sp], &sp[n - i]); ...

Ah, wait, that call can be just

... swap(x, &sp[n - i]); ...

So now what do we have?

void kick(char *sp, char val) {
    const int n = strlen(sp);
    char *x = strchr(sp, val);
    if (x != NULL) {
        for (int i = 1; i < sp + n - x; ++i) {
            swap(x, sp[n - i]);
        }
        sp[n - 1] = '\0';
    }
}

Well, that's a lot of calls to swap. Let's see what's actually happening here... aha, I see, you're trying to bubble *x from the first position all the way to the end of the array. (But doing it in a very odd way where the value *x actually pops into the right place immediately, and then you spend the rest of the O(n) time just trying to get all the other elements back into their proper places.)

Okay, why do we want *x at the end of the array? (After all, we know its value is val, so we wouldn't even technically need to swap it.) ...Aw, really?

sp[n - 1] = '\0';

All that work, just to null it out? Okay, seems like we don't care about *x; all this loop is really trying to do is bump the remaining elements down by one position in the array. Again, there's a library function for that.

void kick(char *sp, char val) {
    const int n = strlen(sp);
    char *x = strchr(sp, val);
    if (x != NULL) {
        memmove(x, x+1, sp + n - x);
    }
}

Notice that since the sp + nth character of sp is '\0', we can just memmove it with the rest of the characters; we don't need to treat it specially.

And now we can see that n is used in only one place, as a part of the expression sp + n; and now we know about strchr, so we can reuse it and move the expensive computation inside the if so that we won't waste time computing it if it's not going to be used.

void kick(char *sp, char val) {
    char *x = strchr(sp, val);
    if (x != NULL) {
        char *end = strchr(sp, '\0');
        memmove(x, x+1, end - x);
    }
}

Now we can go back up and look for the callers of kick. Turns out there's only one — kick(tmp, ' ') — so we don't need val to be a parameter; in fact we should inline the entire three-line body of kick straight into the one place it's called.

...And of course there's much more to clean up, but at this point I'll call it a day. I hope that by reading and studying answers like these, you'll learn how to apply the same kinds of thinking to your own code. A particularly good book on the subject is Kernighan and Plauger's The Elements of Programming Style. (Don't worry that it deals in languages that may be unfamiliar to you. That's part of the point: the techniques of programming are largely language-independent.)

Oh, I suppose I should also point out some problems starting from the top and working down. First, look up strstr. Then, try your program on the input "hello\tworld\nhello    world" (that's four spaces after the second "hello") and observe the trouble with it.

I vaguely recall that a working entab/detab program is one of the programs developed in Kernighan and Plauger's Software Tools, which I recommend not as highly as The Elements of Programming Style but it's still pretty good. I also have a working version here.


python segment tree - count of smaller numbers after self

So, the time complexity of the solution posted in the question is O(n^2 log(n)).

Answering each query takes n log(n), and we have n queries in total.

We don't necessarily need to merge the left and right subtrees to find the inversion count; given that the sublists are sorted, we can exploit binary search.

import bisect

from functools import lru_cache

def merge(left, right):
    res = []
    i, j = 0, 0
    while i<len(left) and j<len(right):
        if left[i]<right[j]:
            res.append(left[i])
            i+=1
        else:
            res.append(right[j])
            j+=1

    while i<len(left):
        res.append(left[i])
        i+=1
    while j<len(right):
        res.append(right[j])
        j+=1
    return res

class SegmentTree:
    def __init__(self, nums):
        self.nums = nums
        self.tree = {}
        if len(nums)>0:
            self._build(0, len(nums)-1, 1)
    def _build(self, l, r, index):
        if l==r:
            self.tree[index] = [self.nums[r]]
            return self.tree[index]
        else:
            mid = (l+r)//2
            left= self._build(l, mid, index*2)
            right = self._build(mid+1, r, index*2+1)
            self.tree[index] = merge(left, right)
            return self.tree[index]

    def get_range(self, l,r, target):
        def get_range(left_boundary, right_boundary, l, r, index):
            if l>r:
                return 0
            if left_boundary == right_boundary or (left_boundary == l and right_boundary==r):
                return bisect.bisect(self.tree[index], target)
            else:
                mid = (left_boundary+ right_boundary)//2
                left = get_range(left_boundary, mid, l, min(r, mid), index*2)
                right = get_range(mid+1, right_boundary, max(l, mid+1), r, index*2+1)
                return left+right
        return get_range(0, len(self.nums)-1, l, r, 1)

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        s = SegmentTree(nums)
        result = []
        for i in range(len(nums)):
            res = s.get_range(i+1, len(nums)-1, nums[i]-1)
            result.append(res)
        return result