Searching a dictionary of words using difflib

Using difflib is probably the best choice. So the problem comes down to the size of your word list. If we can pare down the number of words difflib needs to compare, then we could get a faster time.

One idea to implement, is take only words that are near-enough in length:

# Returns the min and max thresholds for word length
def get_thresholds(word, min=3, max=3):
    length = len(word)
    return max(1, length-min), length+max

# Returns only words whose length is within a certain range
def filter_word_list(min, max):
    return [word for word in words_list if min <= len(word) <= max]

So the call to get_close_matches() would be:

closeMatches = difflib.get_close_matches(termL,
                       dictionaryFile.filter_word_list(*get_thresholds(termL)))

Another idea would be to filter words that begin with a letter that is spatially related to the word's first letter on the keyboard. However, this suggestion is not as plausible due to different keyboard layouts.

As some general comments:

Take a look at your variable names. They are descriptive (for the most part) but the official Python style guide recommends using underscores_between_words instead of camelCaseNames.
Same basic idea for module names. Pythonic module names are written as MyModule instead of myModule. Also, each different module import gets its own line:

# Not `import os, sys`
import os
import sys


Spaces-to-tabs converter, updated version

A chunk of memory that is used to temporarily queue up content before it is eventually flushed is typically called a buffer.  A typical variable name would be buffer or buf.

You defined constants TABVALUE and ARRAYSIZE.  It looks like ARRAYSIZE is dependent on TABVALUE, so you shouldn't hard-code both 4 and 3.  You also shouldn't hard-code 3 in the for loop.

The program outline is basically

while ((c = getchar()) != EOF) {
    if (c == ' ') {
        /* Huge chunk of buffer manipulation code here... */
    } else {
        if (c != EOF) putchar(c);
    }
}

You've already ascertained that c is not EOF in the while loop, so if (c != EOF) is pointless.  I would also recommend inverting the test so that there isn't a huge chunk of code before the else.  This outline is equivalent to your logic:

while ((c = getchar()) != EOF) {
    if (c != ' ') {
        putchar(c);
    } else {
        /* Huge chunk of buffer manipulation code here... */
    }
}

The first space encountered gets stored as c, but subsequent spaces get written to the savedChars buffer.  The code would be simpler if you just wrote the first space to the buffer too.

I'm not convinced that you need a savedChars buffer, though.  The buffer will only contain a string of spaces, possibly followed by a non-space character at the end.  You should be able to do the job using just the s count and the final character d.


Function to alternate players' turns, unless a player has won

You could return the same player if win is true, otherwise return the other player, this is done with only 2 tests:

function whoseMove(lastPlayer, win) {
    if (win) return lastPlayer;
    return lastPlayer == "black" ? "white" : "black";
}


Using finally with return statement or not

Return statement in the finally block is almost always a very bad idea.....

The sematics of the finally block are complicated, but, if there is a return statement the try block, or in a catch block, then those will be called, and then the finally block will run, and it will change the return value.

IDE's, and the compiler, will complain about this:

Code like the following, will return 2 .... always:

private static int doSomething() {
    try {
        .... something here....
        return 0;
    } catch (Exception e) {
        return 1;
    } finally {
        return 2;
    }

}

The point is that it is very bad practice to have returns in the finally block. Don't.....

EDIT: Update to include a better solution.... Use Java try-with-resources (since Java7).

private static final String VERSION_QUERY = "Select VERSION()";
private static final String VERSION_NOT_FOUND = "";

public String getVersion() {

    try {
        Helper.println("Getting driver...");
        Class.forName(_driver);
    } catch (ClassNotFoundException e) {
        Helper.printErrln("Driver Error: " + e.getMessage());
        return VERSION_NOT_FOUND;
    }

    Helper.println("Connecting to database...");
    try (Connection con = DriverManager.getConnection(_url, _user._username, _user._password);
         Statement stmt = con.createStatement();) {

        Helper.println("Executing query...");
        try (ResultSet rs = stmt.executeQuery(VERSION_QUERY);) {
            rs.next();
            return rs.getString(1);
        }
    } catch (SQLException se) {
        Helper.printErrln("SQL Error: " + se.getErrorCode() + ' ' + se.getMessage());
        return VERSION_NOT_FOUND;
    }
}


I think you're rather over-complicated this for yourself! A much better solution is to use the pattern matched results (which you are already creating (t)) (this requires C# 7.0 still, I believe).

foreach (Control c in form.Controls)
{
    switch (c)
    {
        case CheckBox cb:
            cb.Checked = false;
            break;
        case ComboBox cb:
            cb.Items.Clear();
            break;
        case CheckEdit ce:
            ce.Checked = false;
            break;
        default:
            c.Text = "";
            break;
    }
}

No dynamic here: Text is already a member of Control.
Foreach loops are easier to read than .Foreach (in my opinion, at least; even if they are a bit funny underneath)
Your original ToList was redundant: no need to cache a result you are going to stream immediately in single-threaded logic
I've renamed t to something slightly less terrible; since they are very local variables indeed, I personally wouldn't worry to much about the names.
Note that this code will also clear the text on labels, and buttons, and everything else... so it seems an odd thing to provide as a form-wide operation.


In Python 3.3 and later you can use one of

  time.perf_counter()
  Return the value (in fractional seconds) of a
  performance counter, i.e. a clock with the highest available
  resolution to measure a short duration. It does include time elapsed
  during sleep and is system-wide. The reference point of the returned
  value is undefined, so that only the difference between the results of
  consecutive calls is valid.

  time.process_time() Return the value (in fractional seconds) of the
  sum of the system and user CPU time of the current process. It does
  not include time elapsed during sleep. It is process-wide by
  definition. The reference point of the returned value is undefined, so
  that only the difference between the results of consecutive calls is
  valid.

Older Python versions offer timeit.default_timer(), which is now an alias of time.perf_counter().

The timeit module offers tools to get more reliable timings by running the code multiple times.


Sieve of Eratosthenes to print prime numbers in a given range

This is NO Sieve of Eratosthenes. Can you see any division in this algorithm description???

What you're doing is trial division. Worsened by

even checking things like "does 100 divide 2?"
using a list which does not allow efficient removal
using Integer rather than int

The complexity is something like \$O(n^3)\$ as there are 3 nested loops: 2 in your code and 1 in numbers.remove.

The complexity should be \$O(n^\frac32)\$ which comes from using an "indicator array"(*) and iterating up to \$\sqrt n\$ only.

(*) It tracks for each int the information if it's a prime or not. It can be implemented e.g. as a boolean[] or a BitSet. The point is that all you need is an indexed access, no search, no elements shifting....


Mixing Async and Sync in same HTTP request ASP.NET Core C#

Well, generally it is not a problem to call a sync method within async method.

You are actualy doing this in more then few instances (GetExtension, NewGuild, ToString, etc...)

But if you have an async method available it would be shame to not use it.
Which you have - IFormFile.CopyToAsync().

using (var bits = new FileStream(path, FileMode.Create))
{
  await file.CopyToAsync(bits);
}
await _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath);


Showing values from different fields in an array with ternary

I'm looking for a way to improve this nested ternary function

They keys to check could be iterated over - e.g.

function getArray(value) {
  var showValue = 0;
  for (let key of ['value1', 'value2', 'value3']) {
    if (value[key] > 0) {
      showValue = value[key];
      break;
    }
  }

  document.getElementById("demo").innerHTML += value.system + ": " + showValue + " ";
}

function myFunction() {
  var array = [
    {system:"Abba", value1:0, value2:1, value3:0},
    {system:"Mars", value1:0, value2:4, value3:0},
    {system:"Nexus", value1:0, value2:0, value3:6},
    {system:"Zeroes", value1:0, value2:0, value3:0}
  ];

  array.forEach(getArray);
}
<button type="button" onclick="myFunction()">Check</button>

And this could be simplified using the array method find() combined with logical OR - i.e. || for a fall-back value using Short-circuit evaluation for the case when no values are greater than zero:

function getArray(value){
  //find the key that has a value greater than zero
  const key = ['value1', 'value2', 'value3'].find(key => value[key] > 0);
  //return the value that is greater than zero, or else zero in case no value is greater than zero
  const showValue = value[key] || 0;
  document.getElementById("demo").innerHTML += value.system + ": "+ showValue + " ";
}

function myFunction() {
  var array = [
    {system:"Abba", value1:0, value2:1, value3:0},
    {system:"Mars", value1:0, value2:4, value3:0},
    {system:"Nexus", value1:0, value2:0, value3:6},
    {system:"Zeroes", value1:0, value2:0, value3:0}
  ];

  array.forEach(getArray);
}
<button type="button" onclick="myFunction()">Check</button>

Other review points
Improper use of map method
The map() method "creates a new array populated with the results of calling a provided function on every element in the calling array"1. For this code forEach() can be used (as it is in the two snippets above) since the return value of each iteration is not used after the callback is executed. .map() could be used to return a string for each object and then update the DOM element only once, which would be better for multiple reasons:

fewer DOM lookups - remember those aren't cheap
Array.join() can be used to separate each string with a space, without adding an excess space at the end of the output
the function would only have one responsibility - in-line with the Single Responsibility principle

function getArray(value){
  const key = ['value1', 'value2', 'value3'].find(key => value[key] > 0);
  const showValue = value[key] || 0;
  return value.system + ": "+ showValue;
}

function myFunction() {
  var array = [
    {system:"Abba", value1:0, value2:1, value3:0},
    {system:"Mars", value1:0, value2:4, value3:0},
    {system:"Nexus", value1:0, value2:0, value3:6},
    {system:"Zeroes", value1:0, value2:0, value3:0}
  ];

  document.getElementById("demo").innerHTML = array.map(getArray).join(" ");
}
<button type="button" onclick="myFunction()">Check</button>

Keep HTML and JavaScript separate
The HTML has an onclick attribute:

<button type="button" onclick="myFunction()">Check</button>

Instead of using that attribute, the event handling can be setup in Javascript - e.g. using document.addEventListener():
document.getElementById('checkBtn').addEventListener('click', myFunction);

this would require an id attribute be added to the element - e.g.
<button type="button" id="checkBtn">Check</button>

though other ways to detect it are possible (e.g. class name, elements of document.forms, etc. With this separation the JavaScript (logic) can be modified without ever needing to alter the HTML (markup) - especially helpful in larger projects where one person might update HTML and another the JS.


Seemingly complicated way of displaying page views

First I think that you need to reconcile your use of session vs. cookie.  In your answer you explain technically what is happening in your code, but not what the overall user experience requirement is.  You need to match your usage of cookies vs. sessions vs. HTML local storage (though not used here), which are all means to convey application state to what the actual user experience needs of the application are.

Does the cookie represent a default user preference?  If so, then should you be overriding it when the user passes parameters or otherwise changes mode setting in a session only context?

Why use session at all if you are always going to set a new "mode" cookie which overrides whatever is in session and there is not a session-specific override context?  Most likely you are propagating session ID by cookie anyway, so if user deletes cookies, you are going to lose state anyway.

If for example you remove session from the equation altogether, you may get something like:

$mode = 'wall';
if(!empty($_COOKIE['projects-sorting'])) {
    $mode = $_COOKIE['projects-sorting'];
}
if(!empty($_GET['mode'])) {
    $mode = $_GET['mode'];
}
if($mode !== $_COOKIE['projects-sorting']) {
    setcookie("projects-sorting", $mode, time() + (86400 * 30), "/");
}

You are doing nothing in code shown here to validate/sanitize the inputs. Both $_COOKIE and $_GET are use input and should be validated/sanitized accordingly before passing these values further into the application (or especially placing back into user cookie).

Maybe something as simple as validateMode() function.

function validateMode($array, $key) {
    if(empty($array[$key]) || !is_string($array[$key])) {
        return false;
    }
    switch($array[$key]) {
        case 'wall':
        case 'forum':
            return true;
        default:
            return false;
    }
}

And usage with my suggestion like:

$mode = 'wall';
if(validateMode($_COOKIE, 'projects-sorting')) {
    $mode = $_COOKIE['projects-sorting'];
}
if(validateMode($_GET, 'mode')) {
    $mode = $_GET['mode'];
}
if($mode !== $_COOKIE['projects-sorting']) {
    setcookie("projects-sorting", $mode, time() + (86400 * 30), "/");
}


Methods

The first thing that we can do is divide up the labor.  Consider

void static main(String[] args) throws JsonProcessingException {
    Map<String, List<String>> properties = parseProperties(getPropertyValue());
    Map<String, Map<String, List<String>>> payload = buildPayload(properties);
    String json = new ObjectMapper().writeValueAsString(payload);
    System.out.println(json);
}

Now we have the heavy lifting in parseProperties and buildPayload.

I also hid the propertyValue in a method, but that was mostly to avoid obnoxious horizontal scrolling.

parseProperties

    String[] dayParts = propertyValue.split(",");

    for (String string : dayParts) {
      String[] array = string.split("  -  ");
      if (map.get(array[0]) == null) {
        List<String> list = new ArrayList<>();
        list.add(array[1]);
        map.put(array[0], list);
      } else {
        List<String> tempList = map.get(array[0]);
        tempList.add(array[1]);
        map.put(array[0], tempList);
      }
    }

Consider

    for (String string : propertyValue.split(",")) {
      String[] parts = string.split("  -  ");

      List<String> hours = map.get(parts[0]);
      if (hours == null) {
        hours = new ArrayList<>();
      }

      hours.add(parts[1]);
      map.put(parts[0], hours);
    }

We don't need a separate variable for the results of the comma split.  We only use that for this loop, so we can do it directly.

We do need a separate variable for the parts of that string, as we use the parts separately.  Also, we use one of them multiple times.

In both branches of the original if, we do two of the same commands.  If we rewrite it this way, we can do those outside the if.

In the original if, we could have used contains, as we don't use the value otherwise.  But this way, we save the result.  If it is empty, we put an empty list there.  Otherwise, we can just use the previous value.

buildPayload

    Map<String, Map<String, List<String>>> payload = new HashMap<>();
    Map<String, List<String>> hrs1 = new HashMap<>();
    hrs1.put("Hours", new ArrayList<String>());
    payload.put("Sunday", hrs1);
    payload.put("Monday", hrs1);
    payload.put("Tuesday", hrs1);
    payload.put("Wednesday", hrs1);
    payload.put("Thursday", hrs1);
    payload.put("Friday", hrs1);
    payload.put("Saturday", hrs1);
    for (Entry<String, List<String>> entry : map.entrySet()) {
      Map<String, List<String>> hrs = new HashMap<>();
      hrs.put("Hours", entry.getValue());
      if (payload.containsKey(entry.getKey())) {
        payload.put(entry.getKey(), hrs);
      }
    }

So you want to create a map with the seven days of the week.  The same pattern can work here.

public static Map<String, List<String>> normalizeHours(Map<String, List<String>> hours) {
    if (hours == null) {
        hours = new HashMap<>();
        hours.put("Hours", new ArrayList<String>());
    }

    return hours;
}

And we'd use it like

    Map<String, Map<String, List<String>>> payload = new HashMap<>();
    payload.put("Sunday", normalizeHours(properties.get("Sunday")));
    payload.put("Monday", normalizeHours(properties.get("Monday")));
    payload.put("Tuesday", normalizeHours(properties.get("Tuesday")));
    payload.put("Wednesday", normalizeHours(properties.get("Wednesday")));
    payload.put("Thursday", normalizeHours(properties.get("Thursday")));
    payload.put("Friday", normalizeHours(properties.get("Friday")));
    payload.put("Saturday", normalizeHours(properties.get("Saturday")));

Instead of putting a dummy value into each day of the week and then replacing it, this puts the correct value in in the first place.

It's not shorter but is more reusable to have a container for the days of the week that you can use here.

    for (String dayOfTheWeek : dayNames) {
        payload.put(dayOfTheWeek, normalizeHours(properties.get(dayOfTheWeek)));
    }

It's not much longer even for this single problem.  Once you have the container, it shortens the code.


Creating a thread-safe list using a Lock object

Your new approach is much better than the previous one. Instead of deriving from List and using new to hide the base class implementations you create a wrapper around a List implementing IList - this is a much more robust way.

However there are a few oddities:

You don't need to capture the result of a function call in a local variable to return it outside of the lock. You can simply do:

lock (myLock)
{
    return SomeFunction();
}

The Clone implementation is using a ThreadLocal object which is not necessary. For example:

void DoSomething()
{
     var list = new List<int>();
}

If two threads call DoSomething at the same time they will not share list - each will get their own list.  So Clone can be shortened to:

public List<T> Clone()
{
    lock (lockList)
    {
        return new List<T>(internalList);
    }
}

(the LINQ ToList() extension method creates a new copy).

Update: As for your question whether using a ReaderWriterLockSlim would be better - it depends. Using a reader-writer lock is more complex because now you have to make sure you correctly obtain the read/write lock in the correct places. Using a plain lock will be sufficient in 99.99% of all cases and should only be optimized if you actually have proof that it causes a performance problem.

The lock statement also has nice compiler support which will generate the try-catch block around it to make sure it's released when anything throws - something you have to do yourself if you use another lock.

And last but not least I'm suspicious of your need for a thread-safe list. The main feature of IList is the random access capabilities for reading/writing/inserting/removing items at a specific index. However in a multi threaded world these features are less useful than you might think. For example doing this:

if (list.Count > indexImInterestedIn)
{
    DoSomething(list[indexImInterestedIn]);
}

is not thread safe because between the conditional check and the access something could have easily removed elements from the list. So the above code can fail even though the individual operations are thread-safe.

If you check your use-case for the thread-safe list you will probably find that you won't actually need an IList.


Rewritten code:

class TextManipulations
{
private const string AlphanumericWords = @"\b[\w']+\b";
public string[] WordsDist;

public void TextFormat(string sourcePath, string output)
{
    var textInput = File.ReadAllText(sourcePath).ToLower();
    var m = Regex.Matches(textInput, AlphanumericWords);
    var words = new SortedSet<string>();

    foreach (Match match in m)
    {
        words.Add(match.ToString());
    }

    WordsDist = words.ToArray();

    File.WriteAllLines(output, WordsDist);
}

public void SetLineNumbers(string sourcePath, string output)
{
    var lines = File.ReadAllLines(sourcePath).AsParallel().Select(x => x.ToLowerInvariant()).ToArray();

    var regExs = WordsDist.Select(word => new Regex("\\b" + word + "\\b")).ToArray();

    var wordsOut = new string[regExs.Length];

    Parallel.For(0, regExs.Length, j =>
        {
            var sb = new List<int>(15);
            var regEx = regExs[j];
            for (var i = 0; i < lines.Length; i++)
            {
                if (regEx.IsMatch(lines[i]))
                {
                    sb.Add(i + 1);
                }
            }

            wordsOut[j] = WordsDist[j] + "_______________________________" + string.Join(", ", sb);
        });

    File.WriteAllLines(output, wordsOut);
}

}

TextFormat

Using a SortedSet is better becouse we don't need additional Sort() or Distinct() calls becouse it will handle all these stuff by it's self.

SetLineNumbers

The main problem was is that the testing Regex was always created inside the second for loop instead of creating once and then using it in all the iterations. The parallel stuff isn't necessary but we can speed up the code a little bit with that.

Results

Your code was executed on my machine a little bit above 2 secs and my code is finishing around 0.25 secs.

Other things

Do not ever write comments at the line endings becouse they are really useless and  annoying.
I've added an additional parameter to each method which can be used to specify the output file. (But the code still isn't really reuseable or testable.)


Finding the use of the word 'Cthulhu' in tags on Stack Overflow

select t.TagName, count (*) 'Tainted'
  from Posts p
 inner join PostTags pt on (pt.PostId == p.Id)
 inner join Tags t on (t.Id == pt.TagId)
 where lower(p.Body) like '%cthulhu%'
 group by t.TagName
 order by Tainted desc, t.TagName asc

Notice the lower on the body, because like is (should?) be case sensitive.
The joins are also easier to read IMHO than the conditions in the where clause.
The formatting is based on right-aligning keywords and left-aligning clauses.


databaseName is a pointless local variable: you can simply delete all lines using it.

The same goes for sourceFile.

Arrline and s are poorly named variables, and s is lowercased twice:

String[] Arrline = line.split(" ");
for (String s : Arrline) {
    if (!s.toLowerCase().equals("create") && !s.toLowerCase().equals("database")) {
        return s;
    }
}

Cleaning these up the code becomes:

String[] segments = line.split(" ");
for (String origSegment : segments) {
    String segment = origSegment.toLowerCase();
    if (!segment.equals("create") && !segment.equals("database")) {
        return origSegment;
    }
}

The current method of extracting the database name is quite awkward and inefficient. Look at these steps:

lowercase the line
check if it contains a string
split the line to tokens
for each token

if the lowercased token is neither "create" nor "database" then return it

You can do much better using regular expressions:

Pattern DBNAME_PATTERN = Pattern.compile("create +database +(\\w+)", Pattern.CASE_INSENSITIVE);

private String extractDatabaseName(String input) {
    Matcher matcher = DBNAME_PATTERN.matcher(input);
    if (matcher.find()) {
        return matcher.group(1);
    }
    return null;
}

The initialization of line is unnecessary,
because it gets assigned on the next line anyway:

String line = null;

So a simple declaration is enough:

String line;


01 Matrix is too slow when solved using DFS

The algorithm is slow since it creates paths in all 4 directions at
each step. The algorithm is also using recursion, which is also slower
than a simple for loop.
Consider a 5x5 matrix A:
[[1 1 1 1 0]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 0 1 1 1]
 [1 1 1 1 1]]

to find the distance of the top-left cell, the algorithm first moves
down, then up, then right, and then left. It marks the cells it has
already visited by a -1 to avoid infinite loops. So the first five
steps will move down:
[[-1  1 1 1 0]
 [-1  1 1 1 1]
 [-1  1 1 1 1]
 [-1  0 1 1 1]
 [-1  1 1 1 1]]

now the algorithm cannot move further down since it has reached the
maximum row number, and it tries to move in the next direction which
is upwards. Here, it encounters a -1 and gives up on that direction since
a -1 indicates that it has already visited that cell. Now it tries to
move to the right instead:
[[-1  1  1  1  0]
 [-1  1  1  1  1]
 [-1  1  1  1  1]
 [-1  0  1  1  1]
 [-1 -1  1  1  1]]

In cell A(4,1) (i.e. bottom row, second column) it does the same
checks and finds that it cannot move down, then it tries to move
upwards and encounters a 0 in cell A(3,1). At this point,
we are 6 levels deep into the recursion and the distance from
A(0,0) to A(3,1) is hence found to be 6 for now. So ideally the algorithm should now reject any further paths that exceeds 6 levels of
recursion. Unfortunately this is not the case; first the algorithm steps
back to recursion level 5 in cell A(4,1) and continues with cell
A(4,2):
[[-1  1  1  1  0]
 [-1  1  1  1  1]
 [-1  1  1  1  1]
 [-1  0  1  1  1]
 [-1 -1 -1  1  1]]

from this cell it moves upwards all the way up to cell A(0,2):
[[-1  1 -1  1  0]
 [-1  1 -1  1  1]
 [-1  1 -1  1  1]
 [-1  0 -1  1  1]
 [-1 -1 -1  1  1]]

reaches a recursion level of 11. Here it can move either to the right or
to the left. Since the algorithm always tries right before left, it
moves to cell A(0,3) and then continues downward to cell A(4,3) :
[[-1  1 -1 -1  0]
 [-1  1 -1 -1  1]
 [-1  1 -1 -1  1]
 [-1  0 -1 -1  1]
 [-1 -1 -1 -1  1]]

The recursion level is now 16. Then it moves to right to cell A(4,4) and
then upwards to cell A(0,4).
[[-1  1 -1 -1  0]
 [-1  1 -1 -1 -1]
 [-1  1 -1 -1 -1]
 [-1  0 -1 -1 -1]
 [-1 -1 -1 -1 -1]]

The recursion level is now 21. A zero is
finally found in cell A(0,4) indicating a distance of 21 from cell
A(0,0). Still, the
algorithm continues to investigate useless paths (that is: paths
with recursion level more that 6 (remember that we have already found
a zero at distance 6) and moves back to cell A(1,4) at recursion
level 20. Here it tries the remaining directions (left and right) but
none of those works, so level 20 is done. Then it enters back into
level 19, 18, 17, 16, 15:
[[-1  1 -1 -1  0]
 [-1  1 -1 -1  1]
 [-1  1 -1 -1  1]
 [-1  0 -1 -1  1]
 [-1 -1 -1  1  1]]

notice that it replaces the -1 with 1 as it completes a level. So now
A(1,4), A(2,4), A(3,4), A(4,4), and A(4,3) are all reset to value 1. At
level 15, i.e. cell A(3,3), it has already tried to move down, so now
it tries to move up, but that does not work since cell A(3,2) has a
-1. Then it tries to move to the right, to cell A(3,4), which works
since A(3,4) is now 1 (and not -1). From cell A(3,4) it first tries to
move down and reaches cell A(4,4). From that cell the only alternative
is to move left and at recursion level 17 it reaches cell A(4,3):
[[-1  1 -1 -1  0]
 [-1  1 -1 -1  1]
 [-1  1 -1 -1  1]
 [-1  0 -1 -1 -1]
 [-1 -1 -1  1 -1]]

In this cell it cannot get further, there is a -1 in all directions,
and it gives up on level 17, (and moves back to level ...).
The procedure should be clear by now. I will not continue further with
this example, the point was just to
illustrate why the algorithm is so slow.
In fact, in order to find the distance for A(0,0) in this 5x5
matrix example it executes a whopping 22254 (!) calls to the recursive dfs() method.
This simply to determine that the distance is 4 (which btw is found easily
by moving horizontally to the zero in cell A(0,4)).
I think it is a fair guess that the algorithm has an exponential complexity. And it should take forever to run cases with more than say 100 cells (i.e. a 10x10
matrix).
Finally, here is an example of a much faster algorithm that should be
able to find a solution for a 100x100 matrix in a fraction of a second:
import numpy as np

class Solution:
    """ Solution to leetCode problem 542. 01 Matrix
    Given a matrix consisting of 0 and 1, find the distance of the
    nearest 0 for each cell. The distance between two adjacent cells is 1.
    """
    def __init__(self, A):
        self.A = A

    def get_dist(self):
        """ Get the distance matrix for self.A as defined in the
        problem statement for problem 542. 01.
        """
        A = self.A
        (N, M) = A.shape
        B = np.zeros(A.shape, dtype=int)
        for i in range(N):
            for j in range(M):
                if A[i,j] == 1:  # if A[i,j] == 0, B[i,j] is already set to 0
                    dist = 1
                    found = False
                    while not found:
                        for (x,y) in self.points(i, j, dist):
                            if A[x,y] == 0:
                                B[i,j] = dist
                                found = True
                                break
                        if not found:
                            dist = dist + 1
                            if dist > M+N:
                                raise Exception('Unexpected')
        return B

    def points(self, i, j, dist):
        """ Generate all valid points a distance 'dist' away from (i,j)
        The valid points will lie on the edge of a diamond centered on
        (i,j). Use a generator to avoid computing unecessary points.
        """
        (N, M) = self.A.shape
        for k in range(dist):
            if (i+k < N) and (j-dist+k >= 0):
                yield (i+k, j-dist+k)
            if (i+dist-k < N) and (j+k < M):
                yield (i+dist-k, j+k)
            if (i-k >= 0) and (j+dist-k < M):
                yield (i-k, j+dist-k)
            if (i-dist+k >= 0) and (j-k >= 0):
                yield (i-dist+k, j-k)


OOP php method - pass parameters in or get from inside object

Which is the better should not depend on mainly speed. I think you should post more code (at least the name of class and its responsibilities or the list of its functions).

Some other notes:

It's really hard to read code which contains one character long variable names:

$r = mssql_fetch_row($res);

You have to decode them. I'd rename it to $row. The same true for the SQL queries: logins AS l. I would let it be logins.
In the second version there are three variable naming convention: $skID, $prodId, $page_id. Try to be consistent and use just one: they should be $skId, $prodId, $pageId or $skID, $prodID, $pageID or $sk_id, $prod_id, $page_id. (I think the first, the camelCase version is the most readable.)
There is no error handling in the code. What happens when the query returns empty results?
Probably the code is vulnerable to SQL injections: http://en.wikipedia.org/wiki/SQL_injection
Try accessing database attributes with keys not numeric indexes.

$url = trim($r[0]);
$page_id = $r[1];

The following would be more readable:

$url = trim($r["url"]);
$page_id = $r["id"];


Pythonic way to read csv files from a folder in repository

It seems to me that: 1) the path should be a function argument 2) but the function as it stands is very short and does only one thing - you actually don't need a function for this because there is nothing particular that can be reused.
Since the file is going to reside in a specific path, use a constant, it can be defined inside a config file. Quite likely, you may have other options or hardcoded stuff, so it's good to use a config file to keep it all in the same place.
eg:
config.py
PLAYER_FILES_DIR = "/dev/player-assignment/src/player_test/player_test_input/"

And then in your code you import the config file and you can refer to the location path as config.PLAYER_FILES_DIR:
import config

df = pd.read_csv(config.PLAYER_FILES_DIR...)
# do something

pathlib can still possibly be used if you intend to read multiple files from the directory.


Python right position for a Error message in a class

class Grid(object):
    __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell","IDtiles")
    def __init__(self,xMin,yMax,nx,ny,xDist,yDist):

Python convention says that argument should be lowercase_with_underscores

        self.xMin = xMin
        self.yMax = yMax

The same convention holds for your object attributes

        self.nx = nx
        self.ny = ny
        self.xDist = xDist
        self.yDist= yDist
        self.ncell = nx*ny
        self.IDtiles = [j for j in np.ndindex(ny, nx)]

This is the same as self.IDtiles = list(np.ndindex(ny,nx))

        if not isinstance(nx, int) or not isinstance(ny, int):
            raise TypeError("an integer is required for nx and ny")

This would be more conventialy put at the top. But in python we prefer duck typing, and don't check types. You shouldn't really be checking the types are correct. Just trust that the user of the class will pass the right type or something close enough.


You are not doing dependency injection but using another pattern which is called service locator which isn't by the way so cool becasue classes using it depend on the Container:

cache = Container.Instance.Resolve<ICache>();

The CacheManager resolves an ICache from the Container. None of your classes should even know that the Container exists (but the one that configures it).

You should remove the CacheManager entirely and instead correctly inject the ICache to classes that require it.

class ThisClassRequiresCache
{
    public ThisClassRequiresCache(ICache cache) { .. }
}

Your dependency injection framework should handle the injection.

As far as the private Cache properety is concerned you should add another cache == null check to prevent unnecessary locks after the cache has already been created:

get
{
    if (cache == null)
    {
        lock (syncRoot)
        {
            if (cache == null)
            {
                cache = Container.Instance.Resolve<ICache>();
            }
        }
    }

    return cache;
}


Trigonometry Circle representation using Python and Pygame

A few remarks

CIRCLE_X = int(105)
CIRCLE_Y = int(285)

Python is a duck typed language, you don't need a type in order to invoke a method or variable. You could omit the int() call here

if __name__ == '__main__':

guards, use them!

pygame.init()
pygame.display.set_caption("SineRep v. 1.0")
screen = pygame.display.set_mode((SCR_WIDTH, SCR_HEIGHT), 0, 32)
font = pygame.font.SysFont("arial",STD_FONT_SZ)
frequency = 0.1
x_txt = font.render("x", False, (0,0,0))
y_txt = font.render("y", False, (0,0,0))

These should not be global, maybe a function? def setup_game()

You have a few PEP8 violations. A good style creates more readable code :)


Program to display a matrix in a spiral form

I would test it with a bigger array.  Since I created one to test it, I might as well post it here.  I put the numbers in the order I expected them to be printed, which makes checking easier.

const int array[][ARR_SIZE] = {
    { 1,   2,  3,  4,  5,  6,  7,  8,  9 },
    { 32, 33, 34, 35, 36, 37, 38, 39, 10 },
    { 31, 56, 57, 58, 59, 60, 61, 40, 11 },
    { 30, 55, 72, 73, 74, 75, 62, 41, 12 },
    { 29, 54, 71, 80, 81, 76, 63, 42, 13 },
    { 28, 53, 70, 79, 78, 77, 64, 43, 14 },
    { 27, 52, 69, 68, 67, 66, 65, 44, 15 },
    { 26, 51, 50, 49, 48, 47, 46, 45, 16 },
    { 25, 24, 23, 22, 21, 20, 19, 18, 17 },
};

Define ARR_SIZE at the top to 9 and replace each explicit 4 (apart from those in the array of course) with ARR_SIZE. Make each function static and each array parameter const.

Having done this I found that it really does work :-)

Each of your for-loops would be better written:

for (int y = starty; y <= endy; y ++) {
   printf("%d ", arr[startx][y]);
}

Notice that I defind the loop variable within the loop and called it y
instead of yCtr (the Ctr was just noise) and added some spaces. Note that it is normal to put a space after a comma (applies everywhere in your code - your use of spaces is occasionally inconsistent).  I prefer start_x to startx and print_row to printRow,  but that it just personal preference.

Also, a minor point, as the functions are named printRow and printColumn etc, it might be more natural to express the parameters in terms of rows and columns instead of x and y:

static void printRow(const int arr[][ARR_SIZE], int row, int col, int end_col)
{
    for (; col <= end_col ; ++col) {
       printf("%d ", arr[row][col]);
    }
}

The main loop would normally be expressed as a for-loop

int startx = 0;
int starty = 0;
for (int size = ARR_SIZE; size >= 1; --size) {...

Note that I defined the two start variables on separate line - again this is considered best practice.

Final point, your comments are mostly noise.


Formatting some data about some airlines

function reformat($data, $registration = false) {
    // Initializing aircompanies codes
    $iata = new iata;
    $block = array();
    for ($i = 0; $i < count($data); $i += 6) {
        $block[$i] = array(
            'airport'  => $this->prep_value($data[$i + 1]),
            'terminal' => substr(strrev($this->prep_value($data[$i + 2])), 2, 1),
            'shedtime' => $this->prep_value($data[$i + 3]),
            'facttime' => str_replace('&nbsp;', '', $this->prep_value($data[$i + 4])),
            'status'   => str_replace(';', '',
                              str_replace('&nbsp', '<br />',
                                  trim(
                                      strip_tags($this->prep_value($data[$i + 5]), '<img />'),
                                      '&nbsp;/r/n'
                                  )
                              )
                          ),
        );

        if ($registration) {
            $r = str_replace('<nobr>', '', $this->prep_value($data[$i]));
            $block[$i]['reis'] = str_replace('</nobr>', '', $r);
            $a = explode(' ', trim($block[$i]['reis']));
            $block[$i]['company'] = $a[0];
        } else {
            $r = explode('&nbsp;', $this->prep_value($data[$i]));
            $block[$i]['company'] = (strlen($r[0]) > 2) ? substr($r[0], -17, 2) : $r[0];
            $block[$i]['reis'] = $block[$i]['company'] . ' ' . $r[1];
        }
        $block[$i]['companyname'] = $iata->aircompanies[strtoupper($block[$i]['company'])];
        if (file_exists(ROOT_HTML_PATH . '/content/aircompanies/' . $block[$i]['company'] . '.png')) {
            $block[$i]['company'] = $block[$i]['company'] . '.png';
        } else {
            /**
             * @todo Write e-mail notifications, but only once;
             */
        }
    }
    return $block;
}

But it is many questions here:

$this->prep_value($data[$i + 2])

It is really bad idea. May be you need a little another cycle, like

for ($i = 0; $i < count($data) - 6; $i ++) { // or something for preventing array index overloading

It would be much better.
But I cannot know it for sure.


Run python File With get request flask API

To be honest this code looks pretty dangerous. exec is dangerous in its own right, and using it in conjunction with user-provided input makes an explosive combination.
One flaw is the path traversal vulnerability. For example, providing a file name like "../root/something/script.py" I should be able to invoke files outside your directory. The file has to exist to be executed, but a hacker might find some file lying on your system, that can be exploited in a way you did not foresee.
Your script also does not verify that the resulting path really exists (for this, simply use os.path.exists). Thus, validation of user input is lacking.
And probably this code can be exploited in ways I have not thought about.
But since you are reading files from a specific directory, you could simply run a dir of that location, using for example the os.scandir function, and then you can generate a whitelist of files that are allowed to run. Anything else should be disallowed outright.
Personally I would ditch this approach. It would be better to build a library of functions, and invoke only functions that are known and understood, rather than arbitrary files. The rule of thumb is that user input can never be trusted, so it has to be validated thoroughly.


Efficiently update string (in XML format) in MongoDb

One thing that I would probably do differently is move the const string EmptyTag outside of the foreach loop, I don't think that you need to recreate this string every time you loop, move it to the beginning of the method.

Another thing that I would do, make sure that my connections are properly disposed of in all cases by using a using block where ever I could.

Mongo doesn't make use of the IDisposable interface, so you can't use the using syntax to dispose of the connection

I also removed the comment block because I could see what was being done rather easily.

Here is what I came up with,

public async void Execute()
{
    const string EmptyTag = "<$1></$1>";

    var mongoClient = new MongoClient(connectionStringBuilder.ToMongoUrl());
    var db = mongoClient.GetDatabase(connectionStringBuilder.DatabaseName);
    var jobInfoDocuments = db.GetCollection<JobInfoRecord>("JobInfoRecords");
    var encryptedKeys = new[] { "AccountKey", "PrivateKey", "APIKey", "DefectiveKeyGracefulExpiration" };
    var keyPatternMatching = string.Format("({0})", string.Join("|", encryptedKeys));
    var regex = string.Format(@"(?si)<([^\s<]*password[^\s<]*|{0})>.*?</\1>", keyPatternMatching);

    var filter = Builders<JobInfoRecord>.Filter.Regex(x => x.SerializedBackgroundJobInfo, new BsonRegularExpression(regex));
    var requiredDocuments = await jobInfoDocuments.Find(filter).ToListAsync();
    foreach (var document in requiredDocuments)
    {
        var jobIdFilter = Builders<JobInfoRecord>.Filter.Eq("_id", document.JobId);
        var newInfo = Regex.Replace(document.SerializedBackgroundJobInfo, regex, EmptyTag);
        var update = Builders<JobInfoRecord>.Update.Set("SerializedBackgroundJobInfo", newInfo);

        jobInfoDocuments.UpdateOneAsync(jobIdFilter, update).Wait();
    }
}


Large number stored as vector, increase performance

Congratulations on having code ready to review!  Here are some thoughts on how you could improve this:

You have tagged this code as both C and C++. To me, this looks purely like C code. If so, please edit the tags. If this needs to work as both C and C++ code, you'll want to specify what other constraints apply.
C code is generally written using snake_case for function names. For a module of functions operating on a shared data type, a short prefix is often used. Since you are calling your objects "LongNum", I suggest you rename your functions to use a prefix of lnum_ or lngn_ or lnm_ or something.

char Add( char *Vin1, char *Vin2, char *Vout, unsigned N ) {...}

becomes

char lnum_add(char * ln1, char *ln2, char *lnout, unsigned N) {...}

Creating a LongNum requires allocating memory. That operation can and should be part of the library by default. (You might want to code a function for "initialize longnum from user-supplied memory" but I doubt you'll need it.) So you should not be doing malloc() or free() calls directly, but instead you should be calling lnum_new_random() and lnum_delete().
I don't see a reason to avoid the C++ naming scheme, so I suggest calling your creation/allocation functions new and your free functions delete.
Related to (4), I believe a good library should be able to create objects in various ways. Particularly, a random value, a fixed value like zero or one, an arbitrary integer value, a value from a double, and possibly values from strings, and/or values from an input stream.

lnum_new_random(unsigned max_digits)
lnum_new_zero(unsigned max_digits)
lnum_new_from_int(unsigned max_digits, long long init_val)
lnum_new_from_unsigned(unsigned max_digits, unsigned long long init_val)
lnum_new_from_double(unsigned max_digits, long double init_val)
lnum_new_from_string(unsigned max_digits, const char * str)
lnum_new_from_file(unsigned max_digits, FILE * input)
lnum_new_from_lnum(LNUM original)

Instead of passing a parameter N around to specify the maximum length of the data type, why not build a struct to store the information.

For starters, you could define a struct with your max_digits value and the pointer to the start of the digits buffer. A more advanced version would eliminate the pointer and allocate the digit buffer immediately after the max_digits value.

struct LNUM {
    unsigned max_digits;
    char * digits;
};

By doing this, you could decide whether passing the objects as pointers or struct values made more sense. So you would want a named type that you control, rather than just letting the user pass around a char * pointer:

typedef struct LNUM LNUM;     // if struct LNUM includes digits as pointer
typedef struct LNUM * LNUM;   // if struct LNUM includes digits as array

Your PrintNumber function provides the only way to extract the number. And it hard-codes the radix, the output stream, and the format. I'd suggest writing a function to emit an LNUM onto a stream, and one to write an LNUM into a string buffer in a provided radix.

size_t lnum_formatted_length(LNUM ln);
void lnum_format_to_string(LNUM ln, char * buffer, size_t max_chars);

Instead of treating N as a constant, would it be so wrong to have N dynamically computed? Your multiplication function returns two numbers, "low" and "high", each of size N. Why not simply return a single number that has the correct size as determined by your multiply function? Maybe it needs more digits, maybe it doesn't.


Swapping two elements of a singly-linked list

Run Rustfmt. It well automatically tell you such things as:

Idiomatic Rust uses 4-space indents.
Match arms without curly braces have trailing commas
You don't need to prefix paths in use with ::; that's the default.

You don't need #![allow(dead_code)] and it's better to not disable warnings that broadly.
It's usual to import only the module, not the free function, and then namespace the function. For example, mem::replace.
mem::replace(&mut /* ... */, None) is equivalent to Option::take
You can also replace some usages of mem::swap with Option::take and direct assignment. This means you don't need to use functions from mem at all.

#[derive(Debug)]
pub struct List<T> {
    list: Node<T>,
}

type Node<T> = Option<Box<Link<T>>>;

#[derive(Debug)]
struct Link<T> {
    head: T,
    tail: Node<T>,
}

impl<T> List<T> {
    pub fn push(&mut self, elem: T) {
        self.list = Some(Box::new(Link {
            head: elem,
            tail: self.list.take(),
        }));
    }

    pub fn pop(&mut self) -> Option<T> {
        match self.list.take() {
            Some(next_box) => {
                let next = *next_box;
                self.list = next.tail;
                Some(next.head)
            }
            _ => None,
        }
    }

    // First attempt: Use push+pop. Not perfect, as we move the values
    // in and out, and if they're larger, we waste resources.
    pub fn bubble(&mut self) -> bool {
        if let Some(first) = self.pop() {
            if let Some(second) = self.pop() {
                self.push(first);
                self.push(second);
                return true;
            } else {
                self.push(first);
            }
        }
        false
    }

    // Learning from the above attempt, I created another push+pop
    // functions that don't move values, just Boxes instead.

    // Any tail of 'singleton' is silently discarded.
    fn push_singleton(&mut self, mut singleton: Box<Link<T>>) {
        singleton.tail = self.list.take();
        self.list = Some(singleton);
    }

    fn pop_singleton(&mut self) -> Node<T> {
        match self.list.take() {
            Some(mut next_box) => {
                self.list = next_box.tail.take();
                Some(next_box)
            }
            _ => None,
        }
    }

    // Otherwise the implementation is very similar to 'bubble' above.
    pub fn bubble2(&mut self) -> bool {
        if let Some(first_box) = self.pop_singleton() {
            if let Some(second_box) = self.pop_singleton() {
                self.push_singleton(first_box);
                self.push_singleton(second_box);
                return true;
            } else {
                self.push_singleton(first_box);
            }
        }
        false
    }

    // Third attempt: Directly unpack the first two nodes and combine them
    // back together.
    pub fn bubble3(&mut self) -> bool {
        if let Some(mut first_box) = self.list.take() {
            if let Some(mut second_box) = first_box.tail.take() {
                first_box.tail = second_box.tail.take();
                second_box.tail = Some(first_box);
                *self = List {
                    list: Some(second_box),
                };
                return true;
            } else {
                *self = List {
                    list: Some(first_box),
                };
            }
        }
        false
    }
}

fn main() {}

For what it's worth, I prefer bubble2 as the implementation is better factored and has helper functions.

I'm not a big fan of the word "singleton" here, as that feels like a misuse of the term. I don't have a great alternative name other than {push,pop}_boxed though.


Constantly checking existence of dictionary elements in Python: a better way?

For Python >= 2.5 you can use defaultdict instead of dict:

 from collections import defaultdict
 words = defaultdict(int)
 corpus = ["your", "word", "corpus"]
 for a in corpus:
    words[a]+=1
 print words

For Python >= 2.7 you can use Counter:

from collections import Counter
corpus = ["your", "word", "corpus"]
words = Counter(corpus)
print words


A few additional points for your learning experience.

You're not using sys, so the import line is unnecessary.

In range(...), the default start is 0,
so instead of range(0, x) you can write simply range(x).

Don't use pointless comments like this:

# Return 1 if exponent is 0
if exponent == 0:
    return 1

Instead if this:

power = base
for j in range(1, exponent):
    power *= base

It would be better this way:

power = 1
for j in range(exponent):
    power *= base

Because in this version base is referenced only once,
and range is simplified by dropping 1 to use the default 0.

action="store" is unnecessary here:

parser.add_argument('binary_number', action="store")

main is not a good name for that function does.
It would be better to rename it to binary_to_decimal, for example.

And while at it,
it would be better to move the content from the if __name__ ... inside a new main method, like this:

def main():

    parser = argparse.ArgumentParser(description='Converts a binary to a decimal number.')
    parser.add_argument('binary_number')
    args = parser.parse_args()
    binary_to_decimal(args.binary_number)

if __name__ == '__main__':
    main()

Many people miss this point, actually.
The reason to do it this way is that code in the if __name__ ... block is in the global namespace.
So variables with the same name in the rest of the code will shadow those variables,
which can lead to nasty bugs.
By moving that code to a method,
this cannot happen.

PEP8

PEP8 is the official style guide of Python,
and you have a few violations:

Put 2 blank lines before each method definition and you only put 1.
Put 2 spaces in front of # inline comments
Lines should not be longer than 79 characters


Another method would be to check the board as each piece is added. This has an advantage of real time checking, but requires looping through the whole board.  Also you could use a Dictionary<Piece, int> to keep track of which pieces are added and check that instead of the board array.  Using the ContainsKey eliminates extra looping but requires an extra collection.


Creating my own flow control statements in C++. Is that acceptable?

Lisp has an uniform syntax, so it’s possible to create user defined flow control constructs that look exactly like the built in constructs. In C++, that’s generally not possible.

Your code is certainly clever, and it solves the problem of omitted breaks (I consider the other drawbacks you list less important). However:

Despite naming this a “switch”, you’ve essentially recreated an if-else chain. Notably, a compiler may have a bit more difficulty optimizing this than a traditional switch.
Your implementation does not seem to support range comparisons or a default case, although both of these seem to be doable in your conceptual framework.
When used in a disciplined way, falling through from one switch case to the next is not always devoid of merit.
I’m not sure that returning this boolean has a great benefit. It might be preferable to design a construct that ensures that one of the cases is always executed.
Be honest: do you really find this more readable than a traditional switch statement?


Database connection in constructor and destructor

You could use MySQLi (PHP extension) which is class based by default instead of MySQL. It
is very easy to set up multiple connections. You are, however, required to know the connection you are querying always.

Congrats with the first question.


Recommended improvements on beginner Linked List

There are a couple of things to consider.

Pythonic Attributes

Using built-in functions

You have defined your own version of list.length, but Python provides a built-in function __len__(). So you could change:

@property
def length(self):
    # some code

to:

def __len__(self):
    # some code

Also, you could override the built-in __str__() function to visualize your list:

def __str__(self):
     nodes = []
     temp = self.head
     for i in range(self.length):
         nodes.append(str(temp.value))
         temp = temp.next
     return ' --> '.join(nodes)

Also, you can implement an iterator:

def __init__(self):
    self.head = None
    self.iter_ref = self.head
    self.itered = False

def __iter__(self):
    return self

def __next__(self):
    if self.iter_ref is None and self.itered:
        self.itered = False
        raise StopIteration
    else:
        if self.iter_ref is None and not self.itered:
            self.iter_ref = self.head
            self.itered = True
        ret_val = self.iter_ref.value
        self.iter_ref = self.iter_ref.next
        return ret_val

Also, there is a built-in function for get() called __getitem()__. It takes, the same parameters as your function.

Convenience

One more thing, instead of taking in a Node as a parameter for your LinkedList functions, consider just taking in the raw data type. That means you just need to change the first two lines of the prepend() and append() to look like (for example):

def append(self, data):
    node = Node(data)
    # rest of the implementation

So now, to use your code, you can do the following:

ll = LinkedList()
ll.append(1)
ll.prepend(3)
print(len(ll))  # prints "2"
print(str(ll))  # prints "3 --> 1"
print(ll[0])    # prints "3"
print(list(ll)) # prints "[3, 1]"

Optimizations

If you decided to take in raw data types as mentioned above, you can now perform these optimizations:

Computation of Length

Rather than iterate through the entire list every time you need the length, just keep the length as a member variable and increment/decrement it accordingly. Make sure to initialize self.length = 0 in your constructor, then in your append() and prepend() methods, make sure to increment the length, and in your delete() method, make sure to decrement the length when you actually delete a Node. Then, your __len__() method can just look like:

def __len__(self):
    return self.length

Append

Also, your append() function could be optimized by keeping a pointer to the tail rather than iterating to the tail each time:

def append(self, data):
    node = Node(data)
    if self.head is None:
        self.head = self.tail = node
    else:
        self.tail.next = node
        self.tail = node
    self.length += 1

def prepend(self, data):
    node = Node(data)
    if self.head is None:
        self.head = self.tail = node
    else:
        node.next = self.head
        self.head = node
    self.length += 1

Make sure to add self.tail = None in your constructor as well.

Here is the code that I suggested:

class Node:
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return "Node Object : val {}".format(self.value)

class LinkedList:
    def __init__(self):
        self.head = self.tail = None
        self.length = 0
        self.iter_ref = self.head
        self.itered = False

    def __len__(self):
        return self.length

    def __str__(self):
        nodes = []
        temp = self.head
        for i in range(self.length):
            nodes.append(str(temp.value))
            temp = temp.next
        return ' --> '.join(nodes)

    def __iter__(self):
        return self

    def __next__(self):
        if self.iter_ref is None and self.itered:
            self.itered = False
            raise StopIteration
        else:
            if self.iter_ref is None and not self.itered:
                self.iter_ref = self.head
                self.itered = True
            ret_val = self.iter_ref.value
            self.iter_ref = self.iter_ref.next
            return ret_val

    def append(self, data):
        node = Node(data)
        if self.head is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
            self.tail = node
        self.length += 1

    def prepend(self, data):
        node = Node(data)
        if self.head is None:
            self.head = self.tail = node
        else:
            node.next = self.head
            self.head = node
        self.length += 1

    def __getitem__(self, index):
        current = self.head
        for i in range(index):
            if current.next is not None:
                current = current.next
            else:
                return None
        return current.value

    def delete(self, val):
        if self.head.value is val:
            self.head = None
            self.length -= 1
            return
        current = self.head
        while current.next is not None:
            if current.next.value is val:
                current.next = current.next.next
                self.length -= 1
                return
            current = current.next


Simplify definition of a dictionary with default return value

The same way that you would with dict.
From the documentation for collections.defaultdict it says:

  The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

This means we can use all, bar b, of: (from the dict docs.)

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

Since you're overwriting suzuki, I'd remove the first assignment,
as dicts are unordered, and so it's up to chance which it uses.
And as Alex points out, you should keep the value data type consistent.

REDUCE_VALUE = defaultdict(lambda: 0.9, {"honda": 0.95, "suzuki": 0.87})


Python already has built-in abstract base classes for sets and mutable sets — see the collections.abc module. There's even a recipe in the documentation for implementing an immutable set by inheriting from collections.abc.Set and storing the elements in a list.

Here's how you might extend the recipe to a mutable set:

from collections.abc import MutableSet

class ListBasedMutableSet(MutableSet):
    def __init__(self, iterable=()):
        self.elements = []
        for item in iterable:
            self.add(item)

    def __contains__(self, item):
        return item in self.elements

    def __iter__(self):
        return iter(self.elements)

    def __len__(self):
        return len(self.elements)

    def add(self, item):
        if item not in self.elements:
            self.elements.append(item)

    def discard(self, item):
        try:
            del self.elements[self.elements.index(item)]
        except ValueError:
            pass

It's also worth having a look at the implementation of the abstract base classes in _collections_abc.py.


Split an array of items into several arrays, given a condition

Always create a function
Its not really code if its not a function, you may as well just output the 3 arrays directly. (my personal view on global inline code).
You may say, "This is just an example". No it can not be just an example, a function has special powers and is written differently than inline code. Plus examples are boarder line off topic here, this question may get closed.
Part of a functions power is that it makes you think about how you solve the problem differently from inline code.
Look for change
When you write a function you look for the parts of the logic and data that change. You pass that to the function as arguments. The function uses these argument to process the data and return the desired results.
In this case you have

the array of items to split.
The number of days old to split the data, eg 1,2,and 7 days.

Thus we can have something like the following. The function is declared inside another so that all it needs is safely encapsulated and outside of unrelated scopes.
const splitByDaysOld = (() => {
    const MS_IN_DAY = 8.64e7;
    const sorter = (a, b) => a - b;
    return function(array, periods) {
        const now = Date.now();
        var start = 0;
        return periods.sort(sorter).map(day => {
            const res = array.filter(item => {
                const daysOld = (item.date - now) / MS_IN_DAY;
                return daysOld >= start && daysOld < day;
            });
            start = day;
            return res;
        });
    };
})();

It returns an array of arrays, one for each period.
Example below has 3 periods  0 to < 1, 1 to < 2, and 2 to < 7 days old.
const [today, yesterday, week] = splitByDaysOld(arr, [1, 2, 7]);

Note that the periods array is sorted from most recent to oldest and that the result will be in the same order


Here's a solution that only uses one extra data structure.  I use the heapq library to maintain a heap, where it easy to check the smallest item and remove it when it's not needed any longer.  You could also use SortedList from the wonderful sortedcontainers library.

The basic idea is to loop over the intervals sorted by start time. If some intervals have the same start time, then sort those by end time.  Fortunately, Python's sort() method or sorted() function will take care of that.

For each start-end interval, the end time is saved in the heap.

For any end times in the heap that are earlier than the current start time, we reduce the number of guests and remove the end time from the heap.

The start time represents the arrival of a guest, so increment the number of guests and check if it is a new maximum number.

After the last start time, the number of guests can only decrease, so we don't need to process any left over end times.

Here is the code:

import heapq

    def maxIntervalOverlap(intervals):
        guests = 0
        maxguests = 0
        maxtime = None

        heap = []

        for start, end in sorted(intervals):
            heapq.heappush(heap, end)

            # handle intervals that ended before 'start' time
            while heap[0] < start:
                heapq.heappop(heap)
                guests -= 1

            # add the guest that just arrived at 'start' time
            guests += 1
            if guests > maxguests:
                maxguests = guests
                maxtime = start

        print(f"Time with maximum guests is {maxtime}.")


Your code looks pretty good except for the static table. More about that later.

Unsafe code has a few things that can make code go faster, like pointers to arrays and arrays on the stack.

A pointer to array would make code only faster if the code is iterating through that array. ComputeChecksum does iterate trough data, so yes, this part could become a little bit faster. We are talking about microseconds.

You are also iterating through an the table array inside the constructor. So creation of this table could also become a littel bit faster.

Personally: I would not use unsafe code in your case.

About the static

You have a static table, but when you create a new instance of Crc16Ccitt it will recalculate all the (same) values. (Talking about performance loss!) If you have two instances of Crc16Ccitt with different polynomials, then one of your instances will calculate it CRC's wrong, because they both share the same table (since it is static).

How to solve this in a faster and safer way?

Use a static! (Huh?) Yes, a static but another one:

static private readonly Dictionary<Crc16Mode, ushort[]> _tables; This will store all calculated tables.

In your class use a local field: ushort[] _table; This one will hold the (already) calculated table. If the table was not calculated, it will be calculated and stored inside _tables.

You also use this mechanism to store hard coded calcaulated tables, as Jesse suggests. In that case you would assign your hard code table to the dictionary inside a static constructor.

Your code could become like this:

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16Ccitt
{
    #region Static members

    static private readonly Dictionary<Crc16Mode, ushort[]> _tables = new Dictionary<Crc16Mode, ushort[]>();

    static private ushort[] GetTable(Crc16Mode mode)
    {
        lock (_tables)
        {
            ushort[] table;
            if (_tables.TryGetValue(mode, out table))
                return table;

            ushort polynomial = (ushort)mode;
            for (ushort i = 0; i < table.Length; ++i)
            {
                ushort value = 0;
                ushort temp = i;
                for (byte j = 0; j < 8; ++j)
                {
                    if (((value ^ temp) & 0x0001) != 0)
                        value = (ushort)((value >> 1) ^ polynomial);
                    else
                        value >>= 1;
                    temp >>= 1;
                }
                table[i] = value;
            }
            _tables[mode] = table;
            return table;
        }
    }

    #endregion

    private readonly ushort[] _table = new ushort[256];

    public Crc16Ccitt(Crc16Mode mode)
    {
        _table = GetTable(mode);
    }

    public ushort ComputeChecksum(params byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ _table[index]);
        }
        return crc;
    }
}


Recursive find function in JavaScript / jQuery

Overal

I think the code looks too busy just to find a key/value match in an object tree-structure, it took a while to figure out which part(s) bothered me.

Doing it twice

You are doing the matching twice, once with (data[key] === match) and once with (v[key] === match), it would be cleaner to leave the second check to recursion.

Function in a function

I am assuming you use a function in a function to keep track of depth and parents, which isn't worth it. You can do this in a single function with an optional parameter.

Naming

match -> matchValue because match sounds like a boolean to me
childKey - childrenKey because the key really points to an array
result.parents -> avoid this, what if the object already has a property called parents ?

Counter proposal

If you think about it, result can be considered the parent of key, so I would build a function that returns all parents in an array, if you wish you can then have recursiveFind call that.

function findParents( data, key, matchValue, childrenKey, parents )
{
  var i , children , childrenCount;
  /* Prevent the need for an inner function by re-passing parents */
  parents = parents || [];
  parents.push( data )
  /* Return immediately if we find a match */
  if( data[key] === matchValue )
    return parents.reverse();
  /* Are there children to inspect ? */
  if( !data[childrenKey] || !data[childrenKey].length )
    return false;
  children = data[childrenKey];
  childrenCount = children.length;
  /* See if any children have it ? */
  for( i = 0 ; i < childrenCount ; i++ )
  {
    if( parents = findParents( children[i] , key , matchValue , childrenKey , parents.slice() ) )
      return parents;
  }
  /* Fail.. */
  return false;
}

Then recursiveFind becomes

function recursiveFind(data, key, childrenKey, match )
{
  var parents = findParents( data , key, match ),
      result = parents.shift()
  result.parents = parents;
  return result;
}


Counting intersections of wires between towers

There are two key observations to make about this problem.

The first (which you spotted), is that the exact heights of the left and right endpoints of each line segment don't matter, only their order. That is, a line \$A_i, B_i\$ intersects the line \$A_j, B_j\$ if either \$A_i < A_j\$ and \$B_i > B_j\$, or \$A_i > A_j\$ and \$B_i < B_j\$.

The second, is that each pair of intersecting lines is an "inversion". (An inversion is a pair of items that are out of order with respect to a permutation.) That is, if we start with the lines in order of their left heights \$A_i\$, and consider sorting them into the order of their right heights \$B_i\$, the number of intersections is the same as the number of inversions with respect to the sorted order.

The number of inversions in a sequence with respect to a sorted order can be counted in \$O(n \log n)\$ using an adaptation of the merge sort algorithm. This is a standard exercise in an algorithms course (for example, it's exercise 2–4d in Introduction To Algorithms by Cormen, Leiserson, Rivest, and Stein), so I won't spoil it for you here.


This is honestly pretty good. I usually use requirejs.config to set the paths and configurations on require (it's going to grow a lot as you add things like shims, urlArgs, etc). You will also probably want to reuse it in several places. See my blog article on how I recommend doing this. The general idea is that you don't use data-main to bootstrap things, you instead have a request for the configuration file and another to actually bootstrap the specific page of your application.

Next, I'll ask why bother injecting reader and env manually into application? Injecting dependencies is what RequireJs already does.

app.js

define(['reader', 'env'], function(Reader, Env) {
    return function() {
        this.reader = new Reader(),
        this.env = new Env()
    };
});

Finally, a couple notes on your specific files - you probably want to name those top-level functions even when returning immediately

env.js

define(['jquery'], function($) {
    return function Env() {
      ...
    };
});

That both makes it clear from within what module you're in, the fact that you expect it to be used with new, and will generate nicer stacktraces.

I'll also point out that - it's a matter of style but you're on CR so I consider it solicited - hardly ever is code made more bugproof or more legible by using constructor functions.  reader.js could just as easily be the following and not depend on someone remembering to use new and always bind functions.

var env = {
    components: [],
    firstPage: null,
    lastPage: null,
    maxFontSize: function() {
                   return this.env.isIOS() ? 120 : 160;
                 }
};
return env;


You are putting all in one class. That makes structuring and rereading hard. Hence your question, and maybe you felt the urge to make sections in the class by something like // ---------------------.

Then it is time to look at the Model-View-Controller paradigm. An internet search will give better material on this subject than I can.

Basically you have one instance of a Controller class, that is more or less accessible from everywhere. There are View classes (the JFrame) and the Model classes, the data model, directory lists.

The Models can be developed independently, and used in a library.

The Controller is listener of views and models, and controls views.
It holds the data model and the view (JFrame).

The Views signal events to the controller. And provide hooks for the controller. They get passed data, the model.

So you can have several classes, in several subpackages.

The approach is:

Start a new project
Use a version control system, like GIT (has the repository with the project)
An empty controller that starts the JFrame with itself
The JFrame, the original code

And then move the data to the outside, handle in the Controller.
Data changes via events over the controller.
Business logic like enabling/disabling in the controller.

Then you might be able to split up the GUI in specific JPanels or such.

Instead of doing the same actionPerformed for a menu item and button, you might use an Action extending AbstractAction, and add that to the constructors of JMenuItem and JButton. That action might then be disabled/enabled instead of doing it to the components. It also means that you need not make all components available as fields, for instance all those JMenuItems.

For the rest, production quality, for me means, using a build infrastructure like maven, that handles for you the usage of third party libraries, versioning and so on.


Sorting strings with certain restrictions

Numeric vs. lexicographic sort

Given this input: 8 4 6 1 12 55,
the output will be 1 12 4 55 6 8.

The question did not explicitly state so, but in the absence of specific instructions, I would have expected a numeric sort to be more appropriate for the numbers.

The root cause of the bug (if you do consider it to be a bug, that is) is that you detect whether each word looks like it could be a float, but you don't actually convert it to a float.  Therefore, the numbers are sorted as if they were strings.

I'm going to assume that numeric sorting is desired.

Style

Whenever you start with an empty list or dict, then populate it using a loop, consider using a list comprehension or dict comprehension instead.  Defining a variable "all at once" using a comprehension is more elegant, and possibly faster as well.

It's worth packaging the solution to the problem in a function, rather as freely floating code.  I suggest calling the function segregated_sort().

Suggested solution

Here's a much shorter way to write it.  Useful techniques include:

Use list comprehensions and dict comprehensions, as mentioned.
Use filter() to help build the equivalent of your nums and words.  (Here, I've generalized support beyond the two types int and str.  Note, however, that float and int would not intermingle with this approach.)
Use iter() to form a queue of sorted items for each type.  Each queue is drained by calling next() on it.

def segregated_sort(input_list):
    """Returns a sorted copy of the input list that maintains the same
    type of data at each index of the output as the type of data at that
    index in the input."""
    types = [type(datum) for datum in input_list]
    sorted_data_by_type = {
        t: iter(sorted(filter(lambda datum: type(datum) == t, input_list)))
        for t in set(types)
    }
    return [next(sorted_data_by_type[t]) for t in types]

def to_int_where_possible(words):
    """Returns a copy of the input list in which any word that can be
    an int is replaced with its int value."""
    def convert(word):
        try:
            return int(word)
        except ValueError:
            return word
    return [convert(word) for word in words]

if __name__ == '__main__':
    split_input = raw_input().split()
    result = segregated_sort(to_int_where_possible(split_input))
    print(' '.join(str(r) for r in result))

Addressing float/int lossiness

To address allow floats and ints to mingle, and to output the strings exactly as they were input, you can convert all numeric values into a Number class.

I've also incorporated @Veedrac's suggestion to abandon filter() in favour of a list comprehension.

class Number:
    def __init__(self, string):
        self.value = float(string)
        self.string = string

    def __str__(self):
        return self.string

    def __cmp__(self, other):
        return cmp(self.value, other.value) or cmp(self.string, other.string)

def segregated_sort(input_list):
    """Returns a sorted copy of the input list that maintains the same
    type of data at each index of the output as the type of data at that
    index in the input."""
    types = [type(datum) for datum in input_list]
    sorted_data_by_type = {
        t: iter(sorted(datum for datum in input_list if type(datum) == t))
        for t in set(types)
    }
    return [next(sorted_data_by_type[t]) for t in types]

def to_number_where_possible(words):
    """Returns a copy of the input list in which any word that looks
    numeric is converted to a Number."""
    def convert(word):
        try:
            return Number(word)
        except ValueError:
            return word
    return [convert(word) for word in words]

if __name__ == '__main__':
    split_input = raw_input().split()
    result = segregated_sort(to_number_where_possible(split_input))
    print(' '.join(str(r) for r in result))


Trello list scraper with data visualization - Monthly food expenses

Remove code from the global scope. You should try to keep global scope to just functions and classes. This is as adding data here means any function can change it, and so you can no-longer trust it's state.

The only time I use globals that contain data, is when I use a constant. Take MONTHS. Which is a good global variable.

I'd add your settings as a global constant too. You should probably use a dictionary, as then you don't have to use dodgy indexing. But, using a dictionary means that you'd have to use SETTINGS['token'], rather than SETTINGS.token. And so I'd make a new class that has this sugar:

class FrozenDict(object):
    def __init__(self, *args, **kwargs):
        # Hack to bypass `__setattr__`.
        self.__dict__['d'] = dict(*args, **kwargs)

    def __getattr__(self, key):
        return self.d[key]

    def __setattr__(self, key, val):
        raise TypeError('FrozenDict does not support setting attributes.')

    def __delattr__(self, key, val):
        raise TypeError('FrozenDict does not support deleting attributes.')

After this you may want to put getting settings into it's own function. As you wrote:

  TODO: clean up code, get feedback on reddit, maybe use args for spec params

This new function should allow you to use both a file and take arguments  from the command line. I won't go into how to do this, as Reddit probably did. But I'd use argparse. But back to your code. I'd change the construction of the list to be entirely in the with. As with statements aren't in a different scope. And I would use a list comprehension to build the list, rather than using append. This can get you:

def read_settings():
    with open('keys.txt', 'r') as keys:
        k = [line.split('=')[1].rstrip() for line in keys]
        token = k[0]
        api_key = k[1]
    return FrozenDict({
        'token': k[0],
        'api_key': k[1],
        'board': 'BE89pW61'
    })

Nice and simple. I don't know what keys.txt is structured like, but I would recommend that you instead format it so it's:

token=...
api_key=...
board=BE89pW61

Which would allow you to instead use a dictionary comprehension. And would allow you to not be so ridged on how the settings are provided. Using the second argument to str.split. And taking advantage of dict you could get:

def read_settings():
    with open('keys.txt', 'r') as keys:
        d = dict(line.split('=', 1) for line in keys)
    return FrozenDict(d)

After this I'd clean up both get_total_per_month and get_yearly_average. Instead of performing the addition yourself you can instead use sum. And to count the amount of items in an array you can use len. This allows you to change get_yearly_average to a list comprehension, and then just a sum divided by its length. And allows you to change get_total_per_month to a comprehension, passed to sum. I'd also remove the ceil in get_total_per_month as you should change the data when outputting not in it's internal state. And leads to \$\pm12\$ accuracy, as if every month is \$0.01\$ you'll say they're \$1\$, and \$12 \dot{} 0.01 = 0.12\$, but \$12 \dot{} 1 = 12\$. Which is absurdly wrong.

Finally I'd remove your prints as you're using logging. It makes no sense to use print and Pythons logging library to log the programs state. You should only use print as a means to interact with the user, such as asking if they want to use keys.txt as their settings file.

This can leave you with:

#!/usr/bin/python

# Lots of issues with Python3. Lots of unicode, string errors, Just switched to
# py2. should try to use dicts for {name: cost} and to  practice using dicts

# TODO: Data Visualization, Error/exception handling
# TODO: clean up code, get feedback on reddit, maybe use args for spec params
# TODO: set up cron job to run every month

import logging

from trollop import TrelloConnection
import seaborn as sns
import matplotlib.pyplot as plt

MONTHS = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug',
          'Sept', 'Oct', 'Nov', 'Dec']

class FrozenDict(object):
    def __init__(self, *args, **kwargs):
        self.__dict__['d'] = dict(*args, **kwargs)

    def __getattr__(self, key):
        return self.d[key]

    def __setattr__(self, key, val):
        raise TypeError('FrozenDict does not support setting attributes.')

    def __delattr__(self, key, val):
        raise TypeError('FrozenDict does not support deleting attributes.')

def read_settings():
    with open('keys.txt', 'r') as keys:
        k = [line.split('=')[1].rstrip() for line in keys]
        token = k[0]
        api_key = k[1]
    return FrozenDict({
        'token': k[0],
        'api_key': k[1],
        'board': 'BE89pW61'
    })

def get_total_per_month(month, board_list):
    month = month.lower()
    return sum(
        float(crd.name.split('-')[1])
        for lst in board_list
        if month in lst.name.lower()
        for crd in lst.cards
    )

def get_yearly_average(totals):
    totals = [t for t in totals if t != 0]
    return sum(totals) / len(totals)

def plot(totals, average):
    sns.set(style='white', font_scale=1.5)
    plt.title('Monthly Food Expenses')
    plt.xlabel('Months')
    plt.ylabel('Pesos')
    sns.barplot(x=MONTHS, y=totals)
    plt.show()

def main():
    # Establish connection
    conn = TrelloConnection(SETTINGS.api_key, SETTINGS.token)
    board = conn.get_board(SETTINGS.board)
    totals = [get_total_per_month(month, board.lists) for month in MONTHS]
    average = get_yearly_average(totals)
    logging.info(totals)
    logging.debug('Board list: {}'.format(board.lists))
    plot(totals, average)

if __name__ == '__main__':
    SETTINGS = read_settings()

    # Set up basic logging
    logging.basicConfig(format='%(levelname)s %(message)s',
                        level=logging.INFO, filename='DEBUG.log',
                        filemode='w')

    logging.info("Iterating through boards...")
    main()


Excel column string to row number and vice versa

Your code is basically fine, and your unit tests are good.  All I have is nitpicks.

"Excel" in the method names are a bit redundant.

In getExcelColumnNumber(), group - 'A' + 1 with parentheses as - ('A' - 1).  Then the compiler can generate 64 as a constant.

In getExcelColumnName(), the similarly named variables number, num, and numChar are confusing.

The complexity O(log n) is correct.  (With Big-O notation, the base of the logarithm is an unimportant detail, since the base just scales the logarithm by a constant factor, and constant factors are conventionally discarded with Big-O.  For example, O(log_26 n) = O(ln n / ln 26) = O(ln n).)

public final class ExcelColumn {

    private ExcelColumn() {}

    public static int toNumber(String name) {
        int number = 0;
        for (int i = 0; i < name.length(); i++) {
            number = number * 26 + (name.charAt(i) - ('A' - 1));
        }
        return number;
    }

    public static String toName(int number) {
        StringBuilder sb = new StringBuilder();
        while (number-- > 0) {
            sb.append((char)('A' + (number % 26)));
            number /= 26;
        }
        return sb.reverse().toString();
    }
}


First jQuery Plugin, Would like a code review

Props to you on your first plugin! Well here are a few pointers in no particular order:

- Double Wrapping: When you cache yDiv=$(this);, you're wrapping the element with the jQuery object. And then you do: $(yDiv).not(... What this does is wrap that object twice. You've already wrapped it so you don't need to do so again. Just do this yDiv.not(... after you cache.

So this is how you should do it:

//Don't
yDiv = $(this);
$(yDiv).not('.opened').addClass('closed');

//Instead do:
yDiv = $(this);
yDiv.not('.opened').addClass('closed');

- Variable Names: If you want anyone else to provide you input on your code, they have to be able to understand it. You should use variable names that will make sense to anyone reading your code. Yes, in this simple example one can deduce the what and why you named the variables the way you did and we can sort of follow along. But when you start working on large scale projects, things can get out of hand real quick. Take for example your yDiv variable. The keyword this can refer to any element that goes through the .each() which might not be a div in the first place. What if it was a ul or any other element. In that case, the name yDiv would no longer represent what is actually stored in there. Anyways, try to use meaningful and descriptive variable names and stay away from names that might not exactly represent what is stored in said variable.

- Cache your selectors: As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use $("someElem") is jQuery has to jump into the DOM and look through all elements that would match that selection. So you should really do a search only once, and save your results for future use. This way you can look and play with them whenever you want without having to try and find them again.

Ex:

var closestElem = $(this).closest(yDiv); //Cache it
if (closestElem.hasClass('closed')){ //Now use it
    //...
}

- Save a function calls: If you read the jQuery source code you'll see that shortcut methods like .click(), .scroll(), and etc. all reference the .on() method. All they do is basically call the .on() method with some parameters. Well why not just go straight to the meat and potatoes?

Check this out:

$("#foo").click(function() {
    //Do your awesomeness
});

//That does the same thing as this:
$("foo").on("click", function() {
    //Do your awesomeness even awesomener.
});

//You can also use that to set up your own custom events
$("foo").on("myEvent", function() {
    //bar
});

That just makes the syntax so easy to remember as well as provide you with enormous control over your events. If you're going to use jQuery on a regular basis, I recommend that you take some time and read through the source code of the methods you're using. To find them quickly just use CTRL+F and type methodName:. That should jump you straight to what you want to know. This way you can understand what and how they are doing things, and even find better ways to do them on your own. Also if you see something you think should be done better or differently, you understand how it works and you can contribute to jQuery.


PHP code to insert phone number and IP address into a table if not already present

Obey PSR coding standards.  As a starting point, use proper indentation and spacing.  Here's a place to begin your research: https://www.php-fig.org/psr/psr-2/
If you haven't already, narrow how your incoming submitted data is delivered to your script.  If you expect your user's data to be coming from a form with  method=POST, then use $_POST instead of $_REQUEST.  This will reduce the points of data entry and make your coding intention clearer to future human readers of your script.
Variable naming is important! If you have incoming data that holds a "phone number", use a variable name that will never lead to confusion.  phone_number, phone, or mobile_phone, etc might be better choices than $numbers which comes from $_REQUEST["number"]. Truth be told, I don't know if the incoming data is a phone numbet, a serial number, or a chemical that makes things numb. What probably concerns me more than the term is the sudden change from singular to plural.  Is this data an array of numbers? I have to assume not based on the script to follow, but then why use a plural variable name.
I wanted to recommend some investigation into the possibility of using an autoincremented primary id with two unique columns, https://stackoverflow.com/q/5416548/2943403 but there seems to be some debate about stability and suitable environments.  Furthermore, I don't want to make any incorrect assumptions about your coding logic.  Ultimately, I always encourage developers to seek solutions that execute the least number of calls to the database.  If this script can be done by sending one INSERT query and processing the response, that would get a nod from me.
Because you are hunting for a specific id value and a specific numbers value, write those conditions directly into your SELECT query's WHERE clause.  This with speed up your processing, eliminate your break requirement, and simply make your code more direct / intuitive.
Since the purpose of your SELECT query is to determine if an id or number exists, you can write your SELECT clause depending on the response quality that you intend to deliver to the end user. 1. If you don't intend to inform the user about which value already exists in the database table, use COUNT(*). 2. If you are going to explain which value already exists, SELECT id, numbers with a LIMIT of 1.
Rather than extracting the full result set then feeding it to the foreach(), I recommend fetching as you iterate.  https://stackoverflow.com/a/12970800/2943403 That said, I think your code should only be processing a single row of data at most.
You could improve your variable naming in your loop.  $k actually represents the "index" of the current row in the result set, so $i would be meaningful, $index would be more so, but best would be to omit the declaration entirely because you never use it in your script.  $v is the current row's data.  I recommend $row.
Try to avoid using boolean flags like $present.  In most cases, after a bit of careful thought, you can redesign your script to break or continue or conditionally call a custom function as a means to avoid this extra declaration.
Your INSERT query is not using the prepared statement / named placeholders / binding properly.  http://php.net/manual/en/pdo.prepare.php  First, I would the id column is to receive a static NULL value -- you don't need a variable for this, just hardcode it directly into the query.  Second, never write variable values into your prepared statement -- see my link to the pdo manual regarding the proper syntax.
Finally, never present the raw $e->getMessage() details to the public.  You may wish to offer generalized feedback but don't give the specifics as a matter of good security practices.


Switched from MySQL to MySQLi requires the connection parameter

Use object-oriented style:

$con = getCon();
$result = $con->query("SELECT * FROM sometable WHERE deleted=0");

Refer to Example #1 on the PHP documentation for mysqli_query(), as well as the Dual interface quick start page for more information.

Looking back at the functions like deprecated mysql_query() it appears that it used the "last link opened by mysql_connect()". If you really wanted to replicate that, you could define a wrapper function (potentially using call_user_func()):

function mysqli_query_con($query, $resultmode = MYSQLI_STORE_RESULT)
    $con = getCon();
    return mysqli_query($con, $query, $resultmode);
}


Fill a list of 2 lists from split string

If you're going to use map, then it's simpler to surround it in a list() call, then a list comprehension.
Rather than using list(map(list, it)), you can instead use a list comprehension.

[list(i) for i in it]

You don't need to use list(zip()), it only hinders performance and readability.
You don't have to use a list comprehension with *, instead you could use a generator comprehension.
You don't have to use f.readlines(), if you perform the comprehension in the with.

Merging this all together gets:

with open('textFile.txt') as f:
    z = [list(i) for i in zip(*(j.split() for j in f))]


For the parsing and analysis of my tests, I did something like this:

import pandas as pd
from pathlib import Path

class MyTest:

    def __init__(self, settings: dict, root_dir: Path):
        self.table_name = settings['table']
        self.file_name = settings['file']
        ...
        self.columns = settings.get('columns', None)

        filename = root_dir / self.file_name
        data = read_data(filename, columns=self.columns)
        self._data = fix_data(data)

    def summary_x(self):
        ...
        return None

    def get_data_between(self, date1, date2):
        # optionally parsing the dates
        return self._data[self._data['data'].between(date1, date2)]

    ...

def read_data(filename, **kwargs) -> pd.DataFrame:
    return pd.read_csv(
        filename,
        na_values=['00000000', ' ', ''],
        encoding="latin1",
        dtype="object",
        **kwargs,
    )

def fix_data(data: pd.DataFrame, date_cols=None) -> pd.DataFrame:
    if date_cols:
        date_cols = (date_cols,) if isinstance(date_cols, str) else date_cols
        data[date_cols] = [fix_dates(data[col]) for col in date_cols]
    ...
    return data

def fix_dates(data: pd.Series) -> pd.Series:
    #optionally a column
    pass

def remove_empty_strings(data):
    pass

Once I was at the stage where I had multiple types of tests, I made a generic type, and subclassed this. But I see little value in subclassing pandas.Dataframe, because then you also have to take care not to accidentally overwrite any of it's methods and attributes


Here's a slightly different version. It implements IDisposable so that the StreamWriter can eventually be closed and disposed properly and also uses a typed delegate for asynchronous invocation and properly calls EndInvoke upon completion.

public sealed class Logger : IDisposable
{
    private delegate void WriteMessage(string message);
    private static readonly Logger Instance = new Logger("c:\\temp\\logtester.log");
    private readonly object Locker = new object();
    private readonly StreamWriter Writer;
    private bool Disposed;

    private Logger(string logFileName)
    {
        Writer = new StreamWriter(logFileName, true);
    }

    ~Logger()
    {
        Dispose(false);
    }

    public static void Log(string message)
    {
        WriteMessage action = Instance.MessageWriter;
        action.BeginInvoke(message, MessageWriteComplete, action);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private static void MessageWriteComplete(IAsyncResult iar)
    {
        ((WriteMessage)iar.AsyncState).EndInvoke(iar);
    }

    private void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (Disposed)
            {
                return;
            }

            if (disposing)
            {
                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }

            Disposed = true;
        }
    }

    private void MessageWriter(string message)
    {
        lock (Locker)
        {
            if (!Disposed && (Writer != null))
            {
                Writer.WriteLine(message);
            }
        }
    }
}


The answer is to instead use VBA object Dictionary accessible by adding the "Microsoft Scripting Runtime" As a reference in your project. I don't know the internal mechanics but the dicitonary object has a method to see if an object .Exists within it's collection. This is much faster than my nested looping through an ordinary collection object and seeing if a specific value is contained.


Concurrency

If you want to implement it thread-safe, you have also lock the whole transaction. For instance: store != null assumes that there is no item in cache. Imagine that after that check another thread added one. That would result in a cache where the same item is cached twice.

Conside to use a thread-safe collection (e.g. ConcurrentDictionary) instead of using locking.

.Net Framework already provides a thread-safe cache: MemoryCache.

I am not very familiar with the entity framework, but as far as I know is the DbContext not thread-safe. Therefore it is not a good idea to use a single instance of it in multithreaded environments.

Code Style

_merchantStores, _db and _cacheTime should be read-only.
Methods that return a Task should be called xxxAsync
The property setter in StoreCacheInformation should be private or at least internal. Otherview external code may modify the state of the cached items.
For many cached items, it is better to use a dictionary instead of list.