regular expression for telephone/mobile per country and variable naming

For CTRY_BELGIUM_TELEPHONE:

First, to understand what the regex is doing, I'll add the railroad diagram

Demo on RegEx101

What it matches:

Zero followed by

Eight Digits
Digit-Space-Three_Digits-Space-Two_Digits-Space-Two_Digits
Digit-Hyphen-Three_Digits-Hyphen-Two_Digits-Hyphen-Two_Digits
Two_Digits-Space-Two_Digits-Space-Two_Digits-Space-Two_Digits
Two_Digits-Hyphen-Two_Digits-Hyphen-Two_Digits-Hyphen-Two_Digits

Now, looking at above, we can easily spot that many of the things are use multiple times in the same sub-pattern.

Can we combine/reuse them?

For simplicity, I'll use single backslash from here onward. You need to escape it by prepending another backslash to escape it in string.

When I say nth road, it'll refer to the nth path in the above diagram.

Review:

The first road is straight forward. Match eight digits. Simple!

The second road, \d\s\d{3}\s\d\d\s\d\d. As you've used \d{3}, similarly we can write \d\d as \d{2}. Cool!

It'll now become \d\s\d{3}\s\d{2}\s\d{2}.

The third road similarly can be written as \d-\d{3}-\d{2}-\d{2}.

For fourth and fifth road, same can be used.

Second and Third roads are similar except the separator used between digits. Is there any way to combine them?

Back-reference.

How can back-reference be used here?

I'll show you: The character should be captured in capturing group and refer it with back-reference whenever needed.

\d([\s-])\d{3}\1\d{2}\1\d{2}

The regex here can be used to match both second and third road.

\d: Match a digit
([\s-]): Match either a space character or hyphen and add it into first capturing group
\d{n}: Match digits n times.
\1: Match whatever is in first captured group(see #2 above)

There still is repetition in \1\d{2}\1\d{2}. This can be added in group and repeated twice (?:\1\d{2}). Since, back-reference is used, it's not better to use non-capturing group.(You'll know why in the 4th and 5th road).

Similarly, for fourth and fifth road, the regex will be

\d{2}([\s-])\d{2}(?:\1\d{2}){2}

At this stage, the regex will become

^0(?:\d{8}|\d([\s-]?)\d{3}(?:\1\d{2}){2}|\d{2}([\s-])\d{2}(?:\2\d{2}){2})$

The first part \d{8} can also be removed by using ? quantifier on the first captured group. By doing this, we're making the [\s-] optional and thus \1 will be empty and will match eight digits with no spaces between them.

So, Final RegEx is

/^0(?:\d([\s-]?)\d{3}(?:\1\d{2}){2}|\d{2}([\s-])\d{2}(?:\2\d{2}){2})$/

Here's railroad diagram for this

Note that 1 and 2 in the diagram refer to respective capturing group.

Demo on RegEx101

Although, this answer only explains about one RegEx, other RegExes can be modified in the similar way.


Well, it's not a huge performance improvement, but at least it's a lot cleaner:

def to_chars2(number, length):
    bin_num = bin(number)[2:].zfill(length)
    return ''.join([chr(int(bin_num[s:s+8], 2)) for s in range(0, len(bin_num), 8)])

Benchmarks:

>>> timeit(lambda: to_chars2(4820, 16))
1.590714931488037
>>> timeit(lambda: to_chars(4820, 16))
1.6366891860961914


If you don't know the size of your array, don't estimate it

Your graph is an array of 1000 std::list<int>. Why ? If you don't know the size, just don't use a const expr to set it. Just use any dynamic table object available (vector, hashmap, etc...).
If you have only 3 edges, 997 cells of your graph will be wasted memory space, and if you have more than 1000 edges, errors will occur.

Avoid non-const global variables

n, res and cnt are declared as global. Avoid using non-const globals. Among many problems (like name conflicts or multi-threading), it greatly reduce the readability of your program, and thus it's more easy for you to make errors.

Try declaring variables in the most restrained scope as possible. In a struct for example, which is passed down to checkPlayers. Global variable are almost never required to do what you want, you can always use local variables.
Plus, you should prefix your globals' name with g_ so it is clear that they are globals.

On top of that, you only use these variables into checkPlayers() ! These really should be local variable to this function.

Don't call list.end() in the `for` loop head

In your for loop, each time list.end() is called and re-evaluated. Just declare a const iterator with this value  like that :

std::list<int>::const_iterator iterator;
std::list<int>::const_iterator iteratorEnd = list.end();
for(iterator = list.begin(); iterator != iteratorEnd ; ++iterator){
...
}

You also should consider using std::for_each or BOOST_FOREACH (I have a preference for the latest, as it is shorter than the former to implement).

use const reference to pass non-basic types

Passing objects by copy may be long (your graph contains a 1000 cells array !), so passing it by reference is way quicker. To ensure that the reference isn't modified though, make the reference const (const Graph & graph instead of Graph graph). The same goes for the std::string.

Create variables only where you need it

Besides the fact that the two arrays of bool could be move into a single array of struct containing the bools, four of the five arguments of checkPlayers are useless. Don't create them above is you don't need to, there's no use for that.

If you're doing this just in case you may need it later, well I think this is the wrong way to do it, because you may end up with tons of useless code difficult to maintain. Declare variables only when you need it, and if yo ulater may need to generalize, you'll do it then, not before.

main returns an int

Don't forget the return 0; at the end of your program. Error codes are important.


You shouldn't need to create a HeadNode, just use one of the ones given to you. Right now you relink every single item. But if one list has many sequential values, you could save time by just advancing to the tail.  Also, right now you are checking 2 conditions in every loop even though only 1 changes.

You could try something like this: (after setting cur to the minimum node):

while True:
   while cur.next and cur.next.val <= l2.val:
       cur = cur.next
   cur.next = l2
   if not cur.next:  break

   while cur.next and l2.val <= l1.val:
       cur = cur.next
   cur.next = l1
   if not cur.next:  break


Powershell Interaction with Excel (Highlighting Cells)

While this isn't a direct way to speed up PowerShell interaction with Excel, I suspect most people having this problem will find this helpful.  I ended up writing a VBA macro ("Sides") that opens in a third workbook, along with the two of interest.  I then call it from Powershell.  All together, I came up with:

$excel= New-Object -ComObject "excel.application"
$excel.Visible=$true
$ocomp1=$excel.Workbooks.Open($WorkingDirectory+"Discrepancies1.csv")
$ocomp2=$excel.Workbooks.Open($WorkingDirectory+"Discrepancies2.csv")
$macro=$excel.Workbooks.open("\\dshfs03.dgoz.dccz.ccnz\psst\Aram\Highlighter.xlsm")
$excel.run("Sides")

This runs really smoothly and does exactly what I want.  Granted, you have to know a little VBA, but that wasn't a problem for me.


Looking for performance improvement of my custom dataframe aggregation function (Python/Pandas)

Normally, I really despise the fact that itertools.groupby only groups adjacent elements with the same key... in your case, though, this seems ideal. Forgive me for just rewriting the code rather than critique'ing what you have, but using this grouping function completely changes how the overall task is best approached.

Let's use itertools.groupby to perform the grouping rather than pandas.groupby specifically because of this adjacency behavior:

In [1]: grouped = itertools.groupby(df.itertuples(False), key=lambda x: x.Id)

In [2]: {k: list(v) for k, v in grouped}
Out[2]:
{'foo': [Pandas(Anticipation=10, Id='foo', Size=10),
  Pandas(Anticipation=9, Id='foo', Size=11),
  Pandas(Anticipation=8, Id='foo', Size=30)],
 'bar': [Pandas(Anticipation=10, Id='bar', Size=10),
  Pandas(Anticipation=9, Id='bar', Size=9),
  Pandas(Anticipation=8, Id='bar', Size=10)],
 'baz': [Pandas(Anticipation=10, Id='baz', Size=7)]}

Note that non-adjacent rows won't be aggregated together:

In [3]: [list(v) for _, v in itertools.groupby([1, 1, 2, 1], key=lambda x: x)]
Out[3]: [[1, 1], [2], [1]]

So then we just need a custom aggregation function. Let's use a generator function that can produce multiple outputs per input, so that we can aggregate each group and output one or more rows as appropriate. It'll operate on a single adjacent group of rows and handle the funkiness of your grouping logic:

def funky_aggregate(k, vs, max_size=10):
    cur_size = 0
    cur_ant = 0
    for v in vs:
        cur_size += v.Size
        cur_ant += v.Anticipation * v.Size
        if cur_size > max_size:
            yield {'Id': k, 'Size': cur_size, 'Anticipation': cur_ant / cur_size}
            cur_size = cur_ant = 0
    if cur_size != 0:
        yield {'Id': k, 'Size': cur_size, 'Anticipation': cur_ant / cur_size}

This can then be easily joined back together into a dataframe:

In [4]: pd.DataFrame([row
            for key, group in itertools.groupby(df.itertuples(False), key=lambda x: x.Id)
            for row in funky_aggregate(key, group)
        ])
Out[4]:
   Anticipation   Id  Size
0      9.476190  foo    21
1      8.000000  foo    30
2      9.526316  bar    19
3      8.000000  bar    10
4     10.000000  baz     7


Check if a binary tree is a binary search tree

I think one of reasons that this question is on the verge of getting closed, is that the code presented doesn't make much sense combined with a question of iterative version. But let us come to back that.

Code and style review

Good naming of methods and variables – You are trying to follow the PEP8 and that is good
Combine similar if statements – When you have similar if condition, and they do the same, then combine them using the or operator
Use \ (line continuation) or parenthesis to break long if conditions – This is a matter of personal preferences, and one area where I'm not sure what I prefer to do in all cases. But if you have a long if condition, you can either break it using a single \ at the end of the line, or add the otherwise unneccessary parenthesis around the entire condition.
Add vertical space between non-similar if statements – In some places it can be good to introduce a little vertical space. This is especially true with following if/elif/else blocks. If not vertically spaced, one might wonder if they should have been using elif or else instead. And if they really are meant to be separate if statements, then separate them using extra newlines. This enhance readability, and code understanding
(optional) Shorten None conditions – Consider whether you want to test directly on not node or if you want to use the more verbose node is None. In most cases they are identical, but I tend to prefer the not node version my self.
Bug: Not keeping the key_min and key_max whilst traversing tree – Your code sets these to None, which would introduce errors if you have a tree with a little more levels then your test case, and you first traverse a left tree, and then go down the right tree. That value could now be higher than the root value, and you'll be happy with that. So extend test cases, and then afterwards correct the bug.

With these options implemented you'll get the following (untested) code:

def is_bst(node, key_min=None, key_max=None):
    """Checks is the subtree rooted at this node is a BST."""
    if node is None:
        return True

    if (not key_max and node.key >= key_max) \
        or (not key_min and node.key <= key_min):

        return False

    return is_bst(node.left, key_min, node.key) \
           and is_bst(node.right, node.key, key_max)

Algorithmic comments

Your implementation is good, and should do what it is supposed, with correction of bug, and does so in a recursive manner. You can't do it entirely iterative as retrieving the values of a tree is not an iterative procedure.

However, you do have the option of creating/returning/yielding something which you can use in an iterative manner. Either iterating over your returned list from inorder(), or by implementing an iterative version of the traversal, as I've done in my answer for values_in_order().

If having some you can iterate over you could do either of the following variants:

# First variant: Manually keeping the previous_node
previous_node = None
for node in inorder(root):
    if previous_node and previous_node.key > node.key:
        return False
    previous_node = node

# Second variant: Using the itertools.pairwise iterator
return any(prev.key > node.key for prev, node in pairwise(inorder(root)))

The last one depending on the itertools.pairwise recipe, which returns all pairs of nodes from the start through end.

Do however note, that neither of these methods are tested for efficiency or speed, but are mostly presented as alternate methods on how to do the check whether all the values are in sorted order which seems to the criteria for a binary search tree.


Meta-programming template for collection statistics

Use of T for accumulator and result

I question the decision to use a template parameter T as the result and accumulator type. Especially in the calculation of the variance, using T as accumulator and mean value will cause significant errors in the calculated standard deviation and variance. The mean value may be off by at most \$\lim_{x\rightarrow 1}x\$. I cannot think of any situation where if you are interested in statistics, you would want to use anything else than double.

Clever lambda

While the lambda trick is easy to understand, I question the necessity of it when the same code could have been implemented in the constructor body and with less typing. This would also allow to use double for the mean internally and only truncate to T after assigning, this would bound the error on the variance and standard deviation. Edit: at least if the result is within the domain of T.

Use of std::accumulate

For small types, say short the risk of overflow is large. For double you run the risk of truncation errors when there are many samples. For accuracy see my answer here: Function that normalizes a vector of double. The same applies here and depends on the level of accuracy that you require, seeing as it is statistics, I wouldn't be too worried.

What about min/max value?

One stat that I'm missing is the maximum and minimum value.

Performance

What if I don't need the standard deviation but only the mean? You might want to implement the sum, mean and stdev as separate classes so the user can choose if she only needs the mean for example.

Naming

I find the name Statistics a bit too generic. The name may suggest statistics about anything (like for example memory usage for the day) but here it means the sample count, sum, mean, variance and standard deviation.

Documentation

The variable sample wasn't immediately obvious that it was used to distinguish between sample and population statistics. A comment for the constructor explaining the arguments might be in order.

Checking for iterator type

The compiler will emit an error if the type used for iterator isn't suitable, so strictly speaking this isn't really necessary if it complicates the code. Also I'm not completely sure how you would test that a fulfills the iterator concept in a useful way. I mean you can test for the existence of std::iterator_trait<Iter>::iterator_category but that can have false negatives.

But I never turn down a nice error message telling me what I'm doing wrong instead of a horrendous template substitution failure wall of text that MSVC emits... :)


Reorder list such that each element is followed by the value closest to it

while len(fcfs_working) > 0:

is the same as

while fcfs_working:


You probably do want std::forward here. You're using forwarding references with your templated && types, which means that they might actually be lvalues which the rest of the program expects to remain valid. std::move is basicall a promise that says "The owner is done with this object; feel free to plunder it". Obviously that's dangerous if it's false! std::forward, by contrast, will intelligently say whether something is free to plunder, based on whether it was free for plundering when passed as a parameter in the first place.

One other thing that I would suggest might be helpful is adding some sort of error detection. It would take a bit of work, but stuffing compose with a few well placed static_assert lines or similar would make a world of difference when trying to get something to build which has a few layers of composition. I'm thinking you could construct something helpful with is_invocable although that would require c++17.


Calling a function every 40 second inside a while loop

This seems like a fairly straightforward implementation with reasonable naming. It seems very maintainable, so good work there. Here are a few suggestions:

Useless variables

The time_now variable doesn't seem to serve much of a purpose. You calculate it, then immediately use it. However, you could just call time(0) directly like this:

time_left = time_next_interval - time(0);

It's fewer characters, and since you're calling time(0) directly in several other places, any reader of the code will already have to know what it means.

Don't Repeat Yourself

Usually the "Don't Repeat Yourself" suggestion has to do with code being copied several times. You haven't done that, but you are running your loop far more frequently than you have to. Instead of sleeping for 1 second and then checking if you've reached your desired time, why not sleep for the desired amount of time? Something like this:

time_t remainder = interval;
while(1)
{
    sleep(remainder);
    start_time = time(0);
    call_my_func();
    hit_count--;

    if(hit_count< 0)
        break;
    remainder = (start_time + interval) - time(0);
}

Use Your Loop Counter as a Loop Counter

You have a loop control variable, but you aren't directly using it as such. Instead you've written an infinite loop and then a conditional which checks the loop counter and breaks out of the infinite loop. This isn't the 1970s! We have proper control flow structures now. Just do:

while (hit_count >= 0)
{
    //... etc.
    hit_count--;
}


There's no need to use a list and convert it to a set, you can use a set from the start.

Also, you're checking for every entry if it's in the list as an anagram and adding it to the answer, which is inefficient. You can do this in a faster way by using a dictionary that has the sorted substr as key and pushing the values in there.

from collections import defaultdict
import itertools

def anagram_substring(str):
    substr_list = set([])
    anagrams = defaultdict(list)

    for i in xrange(len(str)):
        for j in xrange(i + 2, len(str) + 1):
            substr_list.add(str[i:j])

    for substr in substr_list:
        anagrams[''.join(sorted(substr))].append(substr)

    return [values for key, values in anagrams.iteritems() if len(values) > 1]

str = raw_input().strip()
print anagram_substring(str)


A* in Clojure - trickier than I expected

I'm not going to be able to do a very thorough review. The code doesn't have anything outright wrong with it, and I'll admit, I've never been able to implement a decent A* implementation. It's just not something that's ever clicked for me very well (cue a new project to fix that).

That said, there's a few minor things that can be pointed out:

(fn [_] node) can be written as (constantly node). Your use of complement suggests you like to avoid explicit functions.

You can also replace:

(map (juxt identity (fn [_] node)) cheaper)

with:

(map vector cheaper (repeat node))

I personally find the latter to be much cleaner. (map vector xs ys) zips xs and ys together into pairs. Here, I'm just zipping cheaper with an infinite list of nodes.

#(-> % graph keys)

can be replaced with:

(comp keys graph)

If, again, you want to avoid explicit functions (although that's not necessarily better).

I don't think returning "no more neighbors" is a great idea. If you need an indicator value for something like this, I'd probably define at the top something like:

(def no-neighbors ::no-neighbors)

Then return no-neighbors. You could also just use ::no-neighbors inline wherever you need it, but then you need to change it multiple places if you ever decide to change the keyword used. IDE's can help with that, but I like to just avoid the problem.

You could avoid the efficiency problem regarding neighbors if you had neighbor-f return a lazy sequence of keys. I can't off hand think of a good way to do that though.

You never use prev-node. It's good to remove dead code like that to remove bulk.

I think that's all I can really comment on. Hopefully someone else can give you a better review regarding the algorithm itself.

Good luck!


Simplify this function which finds the coordinates of the neighbors of an isometric cell

First off, I'm not a game developer, and this is a fundamental point, but wouldn't it be easier to use "regular" coordinates (for example: https://i.stack.imgur.com/XpFSQ.png) instead of "staggered" ones (https://i.stack.imgur.com/Mt5Mw.png)?

Anyway, aside from that, in my opinion there are two major problems about your your function: A) Is doing too much and B) repeating itself.

The main function of calculating the neighbor coordinates should be separate and take an coords object and return an array of coordinates objects. It should use a list of (either pre-calculated or hardcoded) relative coordinates of the neighbors. If you have, for example, functions to calculete the explicit north, north-east, east, etc. neighbors, then they should be sharing this data.

const CELL_NEIGHBORS = [
   // Even:
   [{dx: 0, dy: -1}, {dx: 0, dy: -2}, {dx: +1, dy: -1} /* etc. */ ],
   // Odd:
   [ /* TODO */ ]
];

function getAllNeighborCoordinates({x, y}) {
   const evenOdd = y % 2;

   return CELL_NEIGHBORS[evenOdd].map({dx, dy} => {x: x + dx, y: y + dy});
}

Now if you change getCellIdFromCoordinates to also take an coordinates object, the final function would be:

 function getNeighborsCellId(cellId) {
   return getAllNeighborCoordinates(getCoordinatesFromCellId(cellId))
     .map(getCellIdFromCoordinates);
 }

(DISCLAMER: I'm not that into ES2015 yet, so there may be errors in my code.)


"magic" method

If you're  learning the data structures in Python, I would read about the python data model and Collections abstract base classes to see what magic methods you can/should implement. A Hashmap is a mapping, so it should implement __getitem__, __iter__, __len__, __contains__, keys, items, values, get, __eq__, and __ne__

return vs exception

In case your mapping does not find a key, it returns "This key cannot be found.". This means users of your code should check against this sentinel value when retrieving something. What if that is the value they want to store in this mapping? The correct way to handle a missing key, is to raise an Exception. More specifically a KeyError

range

for i in range(0,1) is equivalent to range(1), so it only yields 0, which means that in this list comprehension it does nothing.

[[] for j in range(self.size)]

Would hav achieved the same. [[]] * self.size would not have worked, since the reference to the same inner list would have been copied.

variable names

size is not the size of the mapping, but the size of the hash table, so this name might be confusing. Moreover, this should not be a public variable of the, so _hashtable_size would be more appropriate.

According to PEP-8, variable names should be snake_case, so mainList would be _main_list

get

For a dict and a mapping, get has another argument default, which gets returned if the key is missing

iteration

In python, it is seldomly necessary to iterate over the index , like you do in for i in range(0,len(self.mainList[index])):

for dict_key, value in self.mainList[index]:
    if dict_key == key:
        return value

achieves the same, but is a lot more clearer and concise

docstrings

Python has a convention on how to document a method. It's called docstrings. Instead of a #, you use a """

def put(self, key, value):
    """To add value to the list."""

class Hashtable:
    def __init__(self, size):
        """explanation what this class does, and what the argument means"""
        self._hastable_size = size
        self._main_list = [[] for j in range(size)]

    def _index(self, key):
        # To get the index number.
        return sum(ord(i) for i in key) % self._hastable_size

    def __contains__(self, key):
        index = self._index(key)
        return any(dict_key == key for dict_key in self._main_list[index])

    def put(self, key, value):
        """To add value to the list."""
        if key in self:  # calls self.__contains__(key)
            raise ValueError(f"<{key}> already present")
            # you can also choose to overwrite the already present value
        index = self._index(key)
        self._main_list[index].append((key, value))

    __setitem__ = put

    def __getitem__(self, key):
        if key not in self:
            raise KeyError(f"<{key}> not present")
        index = self._index
        for dict_key, value in self._main_list[index]:
            if dict_key == key:
                return value

    def get(self, key, default=None):
        # To get value from the list
        try:
            return self[key]
        except KeyError:
            return default

    def __len__(self):
        return sum(len(sublist) for sublist in self._main_list)

    ...


Using a single for loop to load multiple images in a canvas

Sprite!

I suggest you place the images in a single image, like a "sprite sheet". This means that you need to pre-assemble the images into one image, load that single image and draw it on the canvas.

That way:

You only load one image, thus reducing your http requests to the server to one only.
You draw to the canvas only once. No more loops, no more multiple drawImage.

Order in the court!

Loading images are async, thus the need for the event handler. This also means that the images will arrive in any order, and not necessarily in the order you called them down. In your case, the image at index 21 might come earlier than you'd expect, even before all others have loaded.

I suggest you add an onload to each image and have it check if all images have been loaded before doing anything with them. A simple way to do this is to increment a counter and check if the counter value matches the expected number.

When the count is equal to the expected length, run the code you want to run.

No aftershocks?

If the entire operation was just to load into the canvas the images, it's fine.

However, you aren't loading them for no reason now are you? You are loading them for something. I suggest you wrap this operation in a function, have it accept your url array, and a callback that runs when it finishes loading and rendering all your images on the canvas.

Something like:

loadImagesToCanvas([
  //urls
],function(renderedCanvas){
  //run when done
});

Math.floor() is slow and long

In some browsers, Math.floor() is a slow way to trim off the decimal places of a number. Try bitwise OR (|) instead:

var wholeNumber = decimalNumber | 0;

Unnecessary math

If some consecutive operations use some value resulting from some math operation, cache that value in a variable rather than doing the math again.


Exception handling should be added
to the constructor, handling a negative
quesize. Or take a look at Code
Contracts.
Instead of initializing head and
tail to -1, you could use
nullable ints, and adjust your
logic so it doesn't rely on the
magic number -1.
Implement some missing features.
(might have been left out
intentionally): implement ICollection and IEnumerable, isFull().
A minor point would be naming conventions. In C# method names normally start with a capital letter.
Be aware that this is not a thread safe class.
Add some comments, this code isn't that self-documenting. Or, where possible, make it self-documenting, e.g. if ( head == tail ) could be if ( Count == 0 ).


FizzBuzz Solution Rags to Different Rags

Taking your question at face value:

  I removed braces because these are all essentially one-line statements and don't need them, so what does this say about my Java coding style?

They are not essentially 1-line statements. Your assumptions are incorrect.

An if is a statement, and a System.out.println is another statement. Thus, you have two statements there... now, the code segment:

        if(i % (5*3) == 0)
            System.out.println("FizzBuzz");

represents two statements on two lines... but, the statement:

       else if(i % 3 == 0)

technically merges one if statement (with an else clause) in to a second if statement. You thus have two statements on one line.

What conclusion can you draw from there? That code style does not depend on the number of statements on one line, because it is normal, and acceptable to have an else and a new if on a single line.

Thus, the fact that it is a 1-liner or not is not the issue. The issue relates to readability, and maintainability.

Your code is readable, sure, but is it maintainable? No.

Maintenance requires making changes. Now, the base reason I have against the un-braced 1-liners, is that maintenance often requires breaking a single statement in to multiple.

Thus, a line like:

        if(i % (5*3) == 0)
            System.out.println("FizzBuzz");
        else if (....)

may need to become:

        if(i % (5*3) == 0) {
            System.out.println("FizzBuzz");
            dualmatch++;
        } else if (....)

Note, now, that to make a single change to count the number of times that the double-modulo has happened (FizzBuzz), we have added a single line of code, but also modified 2 other lines.

Thus, we have had to modify two lines, and add a third, just to add one line.

Now, what does this mean?

It means someone looking through a 'diff' to see what changed, sees a diff on the line:

        if(i % (5*3) == 0) {

and also on the line:

        } else if (....)

when, in fact, nothing in those lines of any consequence changed.....

By not adding the braces when you created the code, you have made the maintainability of the code much more difficult, because each maintenance requires a lot more effort, and a lot more confusion when trying to identify code progression.

What saved you 2 seconds when you wrote the code, is going to create 5 minutes of effort later for every single person who investigates why you changed lines of code, that you did not actually change.... and those 'unchanged' but different lines are the most complicated parts of the code...

By not adding the braces, you are essentially saying, "My 2-seconds saved is worth more than the hours? of time that someone else has to consume understanding revisions of my code).

Now, if that is not enough, whenever work is done, bugs can be introduced, and the amount of bugs is typically proportional to the complication and effort required to implement a change....

By making changes to your code more difficult, you are increasing the amount of bugs that result from your laziness, because other people need to correct both the code, and your laziness in the future.

Note here is the diff for adding in a count of the number of FizzBuzz's using your code:

Now compare that diff with what it looks like if the bracing is right to start with:


Checking that data has been created in multiple tables

As I mention in this other SQL answer:

  Any SQL query has up to eight primary clauses.  WITH, SELECT, INTO, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. Everything else is a part of one of these clauses. These 8 clauses should have zero indentation relative to the query as a whole, and everything else should be indented by at least one level.

A little indentation can go a very long way to making your query far more readable.

So, just using your first SELECT as an example, proper indentation would look something like this:

SELECT @rowCntAttCode = SUM(PART.rows)
FROM sys.tables TBL
    INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
    INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblAttCode AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

If you insist on turning any of these single lines into multiple lines to reduce the width, then the extra lines should get an extra level of indentation.  For example

SELECT @rowCntAttCode = SUM(PART.rows)
FROM sys.tables TBL
    INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
    INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
        AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblAttCode
    AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

And some people like breaking the ON part of a join onto its own line, which should look like this:

SELECT @rowCntAttCode = SUM(PART.rows)
FROM sys.tables TBL
    INNER JOIN sys.partitions PART
        ON TBL.object_id = PART.object_id
    INNER JOIN sys.indexes IDX
        ON PART.object_id = IDX.object_id
            AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblAttCode
    AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

Any of these three indention styles are fine, but be consistent, no matter what you pick.  Hopefully, you can see how this sort of indention style helps guide the reader's eye to the important parts of the query.

Now, with the indentation out of the way... I'm a little concerned about how exactly your query is even working.

Normally, when we're doing a variable assignment in a select, we want to use TOP 1 just to be certain we're only getting one row back.  Given that you're using an aggregation query, you don't necessarily need to do this... but why are you using a GROUP BY?  What sort of results do you expect?  The TBL.name is redundant in the GROUP BY since you already have a WHERE TBL.name = @tblAttCode, so there can only be one value in that column anyway.  What are you hoping to accomplish with the GROUP BY TBL.object_id?


jQuery .validate() plugin, additional method to validate numbers

jQuery.validator.format()
jQuery.validator has a format method
This allows you to replace the String  you created entirely.
However, this would require you to replace your 'o' parameter object with an array ( [min,max] ).
$.validator.addMethod('c_number_between',
    function(d,i,o){
        var num=d.replace(/\./g,'').replace(',','.')/1,
            // min/max assigns for context readability (optional)
            min = o[0],
            max = o[1];
        return max>=num&&num>=min;
    },$.validator.format('The value must be between {0} and {1}'));

Update:
While the docs say:

The default message to display for this method. Can be a function created by ''jQuery.validator.format(value)''. When undefined, an existing message is used (handy for localization), otherwise the field-specific messages have to be defined.

Any function that returns a string can be used so boom:
$.validator.addMethod('c_number_between',
    function(d,i,o){
        var num=d.replace(/\./g,'').replace(',','.')/1,
        return 0.max>=num&&num>=0.min;
    },function(params){return 'The value must be between {0} and {1}'.replace('{0}',params.min).replace('{1}',params.max);});


Asynchronous connect() with one function call, using C++11 lambdas and Boost.Asio

Looks good to me.
Given what is posted there is not much else to comment about.

Object life-span: Looks good. (Though I recommend some unit-tests).
Naming: Looks good.
Style: Looks good. (Though personally I don't yet like '{' on the same line as other stuff).

The only thing I may have done differently (but this is very subjective and I would not expect you to change if you prefer your technique).

using namespace boost::asio::ip;

// I may have used
namespace BIP = boost::asio::ip;

Then prefixed all the boost stuff with BIP::. Just so I don't pollute the namespace.

But as I say your technique is totally valid since you have bound the scope of the using declaration to the function. If I was code reviewing within your company I may have commented but I would not block your merge to mainline over it.


Sonar: Move constants to a class or enum

Personally, I do not see the reason why this needs to be a variable in the first place. If I were you I would either move this into the @Query annotation or better yet I would create a @NamedQuery under your Task entity class.
Also on a side note, I would avoid naming the repository method deleteTaskById as this name implies that a matching object will be deleted from the database. Since this is not the case here, I would rename the method to markTaskAsDeleted to avoid ambiguity.


How can I make this StringToCollections method more generic?

Consistency:

Don't mixup using var and declaring your variables explicitly. Choose one of the two, preferably var.

Combining methods:

Use method chaining to shorten your code. There's no need to create a variable for every step your code does. This:

var materialStringArray = materialIDs.Split(',');
var materialIdsArray = materialStringArray.Where(x => x != "").Select(int.Parse);

can be changed to:

var materialIdsArray = materialIDs.Split(',').Where(x => x != "").Select(int.Parse);

Generics:

You cannot make one magic generic method to do this. Why? Simply because you do not know the type ahead of time. What you can do however is to create separate method for getting the valid ids from the string:

public IEnumerable<int> GetValidIDs(string ids)
{
    foreach (var id in ids.Split(','))
    {
        int x;
        if (Int32.TryParse(id, out x))
        {
            yield return x;
        }
    }
}

private Package StringToCollections(Package inPackage, string materialIDs, string functionIDs, string companyIDs)
{
    var validMaterialIDs = GetValidIDs(materialIDs);
    var materials = DB.Materials.Where(x => validMaterialIDs.Contains(x.MaterialId));

    var validFunctionIDs = GetValidIDs(functionIDs);
    var functions = DB.Function.Where(x => validFunctionIDs.Contains(x.FunctionId)));

    var validCompanyIDs = GetValidIDs(functionIDs);
    var companies = DB.Companies.Where(x => validCompanyIDs.Contains(x.FunctionId)));

    inPackage.GATE_material = materials;
    inPackage.Function = functions;
    inPackage.Companies = companies;

    return inPackage;
}

Now your code looks much cleaner and is easier to read and maintain, not only by you but also other people.

You can also assign the database call directly to the according property of inPackage, for example:

var validMaterialIDs = GetValidIDs(materialIDs);
inPackage.GATE_material = DB.Materials.Where(x => validMaterialIDs.Contains(x.MaterialId));


Find the smallest element in a sorted and rotated array

The input, 1) which doesn't contain duplicates, has been 2) sorted, 3) rotated:

int a[] = {5,3,2,5,6,7};
// removing duplicates gives
int a[] = {5,3,2,6,7};
// sorting gives
int a[] = {2,3,5,6,7};
// rotating gives (for instance):
int a[] = {5,6,7,2,3};

log(n) suggests a divide-and-conquer strategy like binary-search, as you found out by yourself. But what are you looking for in this case? Not a value, but the position where a[n] > a[n+1]. Notice that if a[n] > a[n+1], then also a[0] > a[n+1]: the "direction change" occurred in that range. If not, it occurred in the range [a[n+1], a[len(a)]).

Divide-and-conquer is trickier than it may seem because it's really easy to access the array out-of-bounds. Iterator interfaces likes those of the C++ standard library make it easier and clearer:

template <typename Iterator>
Iterator find_partition_point(Iterator first, Iterator last) {
    if (first == last) return last; // empty array
    if (std::next(first) == last) return first; // one-value array
    if (*first < *std::prev(last)) return first; // null/full rotation
    // so we have at least two elements and a change of direction
    auto pivot = first + std::distance(first, last) / 2;
    if (*pivot < *first) { // direction change in [first, pivot]
        if (*std::prev(pivot) > *pivot) return pivot;
        return find_partition_point(first, pivot);
    }
    return find_partition_point(std::next(pivot), last); // direction change in (pivot, last)
}


Parse weak ciphers out of an nmap.xml report

I don't believe that this does what you want, for a few reasons.

First, I'm not 100% on interleaving ElementTree iterators, but this may pick up more elements than you want; for example, what happens when the document is something like

<host>
<address addr="1.1.1.1"/>
</host>
<host>
<address addr="2.2.2.2"/>
<elem key="md5"/>
</host>

It's at least plausible to me that both IP addresses would show up in the md5 list. Even if it doesn't, you should strive to use code that has clear semantics.

Second, your filters check that ip not in md5Stack but what you add to md5Stack is ip.split(',').

Let's try this:

from xml.etree import ElementTree

def extract_weak_ips(nmap_root):
    md5_ips = set()
    sha1_ips = set()
    hosts = list(nmap_root.iter('host'))
    for host in hosts:
        addresses = [address.get('addr').split(',')
                     for address in host.findall(".//address[@addr]")]
        if host.find(".//elem[@key='md5']") is not None:
            md5_ips.update(addresses)
        if host.find(".//elem[@key='sha1']") is not None:
            sha1_ips.update(addresses)

def print_ip_set(s, key):
    for ip in s:
        print ' %s :: %s' % (ip, key)

if __name__ == '__main__':
    parser = ElementTree.XMLParser()
    parser.parser.UseForeignDTD(True)
    md5_ips, sha1_ips = extract_weak_ips(ElementTree.parse('nmap.xml', parser).getroot())
    print_ip_set(md5_ips, 'md5')
    print_ip_set(sha1_ips, 'sha1')

I've extracted code into clear functions, and I'm using XPath queries so that the XML engine is doing the work of querying XML, not your application-specific code.

I think that in this case the list-comprehension approach is less readable than the code with for-loops, but if you really want list comprehensions, try this:

def extract_ips_with_key_type(nmap_root, key_type):
    query = ".//elem[@key='%s']" % key_type
    return set(apply(
        itertools.chain,
        (address.get('addr').split(',')
         for host in nmap_root.iter('host')
         if host.find(query) is not None
         for address in host.findall('.//address[@addr]')))


It does the job, so that's good. It's quite clear and I don't see fundamental flaws in it. There are a few minor things I'd recommend to change:

The most important expression in the middle is a bit hard to read.
I find it much easier this way: num += m * ((unsigned char*) source)[i];
(Redundant parens removed, multiplication operands switched, minor spacing adjustments)
Instead of m<<=0x8; I would write m <<= 8; with more spacing and 0x8 is the same as simply 8
The name byte_extract doesn't convey well what you described: "You give this function a pointer and how many bytes you want to extract as a decimal and it returns it." extract_num or extract_bytes_as_num would be better
Renaming m to multiplier could be a good idea too


I wold separate the concerns somewhat and put them into functions.

One major concern is actually solving the quadratic equation. Another is the fancy input/output around it (if you want to be pedantic, that is actually two concerns).

The solving function, which I would call solve_quadratic returns a list of the solutions. This list can be empty (if there are no resolutions) or have multiple entries. We can use this fact to just append a solution if there are multiple.

I inlined some of the computations, if they were only used once.

import math

def solve_quadratic(a, b, c):
    """
    Given three real coefficients,
    returns the (real) roots of the second degree polynomial
    """
    negative_b = -b
    determinant = b**2 - 4*a*c

    if determinant < 0:
        return []
    elif a == 0:
        return [float(-c)/b]
    else:
        root_determinant = math.sqrt(determinant)
        two_a = 2*a
        answers = [(negative_b - root_determinant)/two_a]
        if determinant:
            answers.append((negative_b + root_determinant)/two_a)
        return answers

Now, the input part and the printing which serves as interpretation. For the initial printing I would use str.format, instead of first building a list and then joining it. It is slightly more readable IMO.

Finally, I would use if __name__ == "__main__": to be able to import these functions in another script without calling the input function.

def fancy_quadratic_solver():
    a = int(raw_input("Enter a:"))
    b = int(raw_input("Enter b:"))
    c = int(raw_input("Enter c:"))
    print "Solve: {}x^2 + {}x + {}".format(a, b, c)

    x = solve_quadratic(a, b, c)
    if not x:
        print "No real solutions."
    else:
        print "x =", " or ".join(map(str, x))
        if a == 0:
            print "But this is a straight line."

if __name__ == "__main__":
    fancy_quadratic_solver()


Welcome to CodeReview!

Whitespace

The PEP8 standard, and consequently most Python linting tools, will recommend that you add another linebreak before your function definitions, plus some whitespace around your operators, etc. I won't detail this exhaustively; you're best to use the IDE of your choice - PyCharm is a reasonable one that is helpful for this.

Type hinting

bound is probably an integer, so add : int after it. It probably returns an int as well.

Subroutines

Put your global-scoped code into subroutines for ease of maintenance, legibility and testing.

Redundant pass

That pass isn't needed.

Use format strings

This:

str(i[0])+' '+str(i[1])+'\n'

can be

f'{i[0]} {i[1]}\n'

Simplify some math

This:

((bound**2)*2)+1

can be

2 * bound**2 + 1

due to operator precedence.

Truthiness

This:

if parity[a+n*d] != 1:

can be

if not parity[a + n*d]:

because 0 is falsey.

camel_case

ariLen is more commonly written ari_len in Python.


Return whether a string is a palindrome if you can delete at most k elements

You have a question embedded in the code:

void(set.delete(char) || set.add(char)); // <--is this good code?

The void operator "evaluates the given expression and then returns undefined"1. It doesn't appear that there is a need to have undefined be the final value of that expression because that expression doesn't get assigned or returned. The void() can be removed without changing the functionality of the code. I wouldn't say it is bad code, but unnecessary.

That for loop could be simplified:

for (let i = 0, len = str.length; i < len; i++) {
  const char = str[i];
  void(set.delete(char) || set.add(char)); // <--is this good code?
}

using a for...of loop:

for (const char of str) {
  set.delete(char) || set.add(char);
}

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void


You can take advantage of async to do parallel IO which Async.Parallel makes very easy. Also, when you don't need the return value of an async call you can use Async.ignore in combination with do!: do! fs.AsyncRead(data, 0, data.Length) |> Async.ignore

However this specific snipper can be made much simpler since there is no reason to await the result of the computations when using Async.Parallel:

open System.IO

let fileContents =
    [ "filename1"; "filename2"; "etc" ]
    |> List.map(fun file -> async { use fs = File.OpenRead(file) in return! fs.AsyncRead(fs.Length |> int)})
    |> Async.Parallel
    |> Async.RunSynchronously
    |> Seq.map System.Text.Encoding.ASCII.GetString

One caveat - if the size of your file is more than 2GB it won't work due to long->int conversion - but that would be a crazy big file to just read the content of like that :-D


Proper way of a testable method with multiple return points

You've got a Policy abstraction that is asking to be teased out.  The Policy provides a method that tests "is it valid to do this operation now".  In production, the Policy instance checks the time difference to see if it is valid.  In test, however, you specify an instance of the policy object that always says no when you want to test that code path.

You've a bit of refactoring to do to make that possible.  To make testing easier, you want to inject an instance of policy into the object, so that your test can control which implementation is being used.

@Override
public void applyStates(int timestamp, State[] states) {
    if (! this.policy.isValid(timestamp)) {
        return;
    }

    // ....

So for testing purposes, you might inject a "policy.isValid always returns false" object, and then run your tests and verify that none of the states have been applied (whatever that means).


Improvements for a C getline implementation

Overall, it's a lot of effort (perhaps not in the right place) for one line. Textual data typically has lines that are very short, on the order of 80 bytes. If you're so deeply concerned about performance, you need to back out of this function and look at the I/O pattern of the calling program for more context. You'll very likely find that it's more efficient to have a buffer much larger than your current PACK_SIZE, perhaps 4MB. Read the file into it one such chunk at a time with fread, not fgets; then iterate through to find and split on newlines. Roughly,

Allocate a large buffer
fread as much as possible
memchr your way to a newline
Set that newline to '\0'
Consume the line
Repeat 3-5 until you're at the end of the buffer
If there is a partial line segment at the end, then memcpy the segment to the beginning of the buffer and plan for the next fread to use a buffer write position that starts after the end of the segment
Repeat until end of file

The principle to heed here is that I/O (particularly disk I/O) is expensive, and frequent calls to the I/O layer are expensive even when cached at the operating system level. Doing as much in RAM as possible is strongly preferred.
If you want a convenience interface, then consider accepting a FILE* and a callback function, making the buffer locally rather than accepting it, and invoking the callback for each line when found.


Firstly, your case 1 case is identical to your case 0,default case (order by street). Is that intentional? It looks like a mistake to me because you've cascaded 0 and default but not 1. If it isn't a mistake, and they do all have the same behaviour you should cascade them all or let them all be picked up by the default case.

I normally see default as the last option in a switch statement, I feel like that might be a convention but don't have anything to back it up.

You're repeating this code a lot: _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase) put it in a variable (which will make the code more readable.

So far:

private void OrderResults()
{
    var isDescending = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase);
    switch (_orderColumn)
    {
        case 2:
            _fitleredResults = isDescending ? _fitleredResults.OrderByDescending(x => x.City) : _fitleredResults.OrderBy(x => x.City);
            break;
        case 3:
            _fitleredResults = isDescending ? _fitleredResults.OrderByDescending(x => x.Country) : _fitleredResults.OrderBy(x => x.Country);
            break;
        case 4:
            _fitleredResults = isDescending ? _fitleredResults.OrderByDescending(x => x.RecID) : _fitleredResults.OrderBy(x => x.RecID);
            break;
        default:
            _fitleredResults = isDescending ? _fitleredResults.OrderByDescending(x => x.Street) : _fitleredResults.OrderBy(x => x.Street);
            break;
    }
}

As Heslsacher says, you could further improve by using named constants for the indexes.

I did write some additional stuff about using a method to get a Func but then I realised that RectId is a long so it all went out the window.

Edit

For posterity, I'll add in what I had written:

private void OrderResults()
{
    var isDescending = _orderDirection.Equals("desc", StringComparison.InvariantCultureIgnoreCase);
    var sortProperty = GetSortProperty();
    if (isDescending)
    {
        _filteredResults = _filteredResults.OrderByDescending(sortProperty);
    }
    else
    {
        _filteredResults = _filteredResults.OrderBy(sortProperty);
    }
}

private Func<AddressObject, object> GetSortProperty()
{
    switch(_orderColumn)
    {
        case 2:
            return x => x.City;
        case 3:
            return x => x.Country;
        case 4:
            return x => x.RectId;
        default:
            return x => x.Street;
    }
}


Streaming modified lines of a file from a Controller

A small improvement you can do to avoid the pretty deep nesting is, stacking all usings without extra brackets.

public static AsyncEnumerable<string> ReadLinesAsyncViaHttpClient(this string uri)
{
    return new AsyncEnumerable<string>(async yield =>
    {
        using (var httpClient = new HttpClient())
        using (var responseStream = await httpClient.GetStreamAsync(uri))
        using (var streamReader = new StreamReader(responseStream))
        {
            while(true)
            {
                 var line = await streamReader.ReadLineAsync();
                 if (line != null)
                 {
                     await yield.ReturnAsync(line);
                 }
                 else
                 {
                     return;
                 }
             }
        }
    });
}

Apart from that I don't know if this the kind of thing that should be a extension method. This should rather be a class.

(I'm currently do not have my hands on a pc, so I cannot comment on the technical side of things >:( )


Simplify : find if element is in tuples stored in list

I don't think there is, except maybe unpacking the pairs:
test = None
for k, v in data:
    if v == searched_value:
        test = k
        break

You could use next, but I wouldn't call it simpler:
test = next((k for k, v in data if v == searched_value), None)


Fetching data through HTTP and caching JSON result in a file

If your logger object is derived from the logging module, use the logger.exception which'll log the traceback information as well. The docs (linked above) also specify this behaviour:

  Exception info is added to the logging message. This function should
  only be called from an exception handler.

You can avoid nesting try-except block by just passing in first exception and place the write to cache inside the first try block itself:

def fetch_list(location=MY_LOCATION, cache_file=CACHE_FILE):
    """Goes to the default location and returns a python list.
    """
    try:
        http = urllib3.PoolManager()
        request = http.request("GET", location)
        raw_data = request.data.decode("utf-8")
        data = json.loads(raw_data)
        with open(cache_file, "w") as cache:
            cache.write(raw_data)
        return data
    except (urllib3.exceptions.HTTPError, JSONDecodeError) as exc:
        logger.exception("Cannot access Intranet List Location - fetching cache")
    try:
        data = json.loads(open(cache_file).readlines())
        return data
    except (IOError, JSONDecodeError):
        logger.exception("Cache File not found or broken")
        raise


Truncate String to target length using only whole words

Style

if (s.length() > TARGET_LENGTH) {
    if (s.contains(SEPARATOR)) {
        if (s.substring(0, TARGET_LENGTH + 1).contains(SEPARATOR)) {
            return s.substring(0, s.substring(0, TARGET_LENGTH + 1).lastIndexOf(SEPARATOR));
        } else {
            return s.substring(0, s.indexOf(SEPARATOR));
        }
    }
}

The above code is cumbersome. When you have a return statement inside an if-condition, there is no reason to have an 'else' condition.

Additionally, when you are using early-returns anyway, there's no reason to have such nested code blocks....

Alternatives

I can see multiple options to this problem. I would recommend testing them to see which performs better for you. The Regex option may in fact be faster if the pattern is reused often.

On the fly

In your own answer, you suggest on-the-fly building of the string, and ending early. This is a good option, but I would do it differently:

public static String portion(final int length, final String separator, String...words) {
    if (words.length == 0) {
        return "";
    }

    StringBuilder sb = new StringBuilder(length);
    sb.append(words[0]);
    for (int i = 1; i < words.length; i++) {
        if (sb.length() + separator.length() + words[i].length() > length) {
            return sb.toString();
        }
        sb.append(separator).append(words[i]);
    }
    return sb.toString();
}

Regex

Yeah, yeah, the whole "use a regular expression, now you have two problems...." but, this concept is:

If the String is < 20 chars, or has a separator within the 20 chars, take the longest string.
If the string is >= 20 or there are no separators within 20, then take until the end of string, or the first separator, whichever is shorter.

If you have the separator - and the length 20, then this can be expressed in the regex:

^(.{0,20}(?=$|-)|.*?(?=$|-))

where:

.{0,20}(?=$|-)

is: find up to 20 chars followed either by the end-of-line, or a separator.

and:

.*?(?=$|-)

is: otherwise, if the previous test fails, take until the end-of-line, or the next separator, whichever happens first.

You can build this in to a reusable pattern (and being defensive about separators that may have special regex meaning....):

private static final Pattern buildPattern(int length, String separator) {
    String qpat = Pattern.quote(separator);
    return Pattern.compile(String.format("^(.{0,%d}(?=$|%s)|.*?(?=$|%s))", length, qpat, qpat));
}

Then, you can use this as follows:

public static String portion(Pattern pat, String s) {
    Matcher mat = pat.matcher(s);
    mat.find(); // patterns will always match, will never fail...
    return mat.group();
}

I imagine this can be used, in your code, like:

private static final Pattern TWENTY_DASH = buildPattern(TARGET_LENGTH, SEPARATOR);

and then in your remaining code:

String s = Arrays.asList("this", "is", "a", "sample", "string")
            .stream()
            .collect(Collectors.joining(SEPARATOR));

return portion(TWENTY_DASH, s);

Return-Early

Having suggested the RegEx option, I would also suggest a simplified lastIndexOf/indexOf using early-returns, instead of nested if-blocks:

public static String portion(final int length, final String separator, String text) {

    if (text.length() <= length) {
        return text;
    }

    int pos = text.lastIndexOf(separator, length);
    if (pos >= 0) {
        return text.substring(0, pos);
    }

    pos = text.indexOf(separator, length);
    if (pos >= 0) {
        return text.substring(0, pos);
    }

    return text;

}


Using freebsd strlcat as a guide.

"length" with C strings typical does not include the null character.  "size" usually does include the null character.  Suggest name change

// dsize = strlen(dst);
dlen = strlen(dst);

Code walks the array and repeatedly adjust 3 variables.  Could be done adjusting only 2.

while (*dst && size > 0 && size--) {
    dst++;
    lsize++;
}
// vs.
size_t remaining_size = size;
while (*dst && remaining_size > 0) {
  dst++;
  remaining_size--;
}
size_t lsize = size - remaining_size;

The below could use memcpy() or strcpy().  These functions are typically optimized for speedy execution, especially long strings.  The key performance assessment should be based on long strings and with sufficient space.  Little need to optimize for undersized values of size.

while (*src && size > 1 && size--)
  *dst++ = *src++;
// vs.
memcpy(dst, src, ...);

Code does not handle overlapping strings.  Should use restrict to indicate that.

size_t ft_strlcat(char * restrict dst, const char * restrict src, size_t size);

Pedantic code would test for overflow in dsize + lsize, but let us skip that corner case for now.
Initialize when declaring, if possible.

// size_t  lsize;
// lsize = 0;
size_t  lsize = 0;

Some lightly tested code follows.

size_t ft2_strlcat(char *restrict dst, const char *restrict src, size_t size) {
  size_t s_length = strlen(src);
  size_t remaining_size = size;

  while (*dst && remaining_size > 0) {
    dst++;
    remaining_size--;
  }
  // Length of destination is the lesser of `size` and
  // offset of the null character, if any.
  size_t d_length = size - remaining_size;

  if (d_length < remaining_size) {
    // We know there is at least room to write the \0

    size_t copy_length = remaining_size - 1;
    if (s_length < copy_length) {
      copy_length = s_length;
    }
    memcpy(dst, src, copy_length);
    dst[copy_length] = '\0';
  }
  return d_length + s_length;
}


Great choice, Allan and good effort! React is awesome and fun. You can improve a few things if you are interested:

Separate Presentational and Container Components. This way your app will be easier to scale, read and maintain
You can try to have your state in one parent component and pass it as props to its children
Extract all components in different files
Navigation can be done with React Router. It is very simple to set up and easy to work with
Consider learning and using Redux for your React App state when you are comfortable with the basics or React
Enjoy learning :)


Outputting prime numbers in given ranges

Before addressing the performance problem I would like to make some
general remarks:

You validate the input values (t, m, n), but invalid numbers are
simply ignored. For a programming challenge I would assume that the
input values are in the specific ranges. However, if you decide to
check the validity then an invalid input should produce an error message
or program exception.

Also the check is unnecessary complicated: m and n are passed to
functions checkM and checkN, but those functions also refer to
the class variables m and n directly. This could be simplified to

if (1 <= m && m <= n && n <= 1000000000 && n - m <= 100000) { ... }

Even better, define and use constants for those limits.
The recursive function repeatReader is used to handle all test
cases (but only if there is more than one test case). This seems
unnecessary complicated to me, a simple loop would suffice.
The logic to get two integers from the input line is duplicated
in main and repeatReader.
Several variables are declared as static class variables, but
needed only locally in a function (such as m, n, beforeSeparate).
There is no need to store all ranges in an array first, you can
read each range and then produce the corresponding output.
Scanner.nextInt() can be used to read the input into integers
directly.
In addPrimeNumbers you can print all found prime numbers directly,
without concatenating them to a string first.

So the overall structure could be simplified to

import java.util.Scanner;

class PrimeNumbers {

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int numTests = sc.nextInt();
        for (int test = 1; test <= numTests; test++) {
            int m = sc.nextInt();
            int n = sc.nextInt();
            printPrimesInRange(m, n);
            System.out.println();
        }
    }

    private static void printPrimesInRange(int low, int hi) {
        // Print prime numbers in the range low...hi
    }
}

Note that

       for (int num = j; num >= i ; num--) {

in addPrimeNumbers should be

       for (int num = j; num >= 1 ; num--) {

otherwise the result is not correct for ranges not starting at 1.

With respect to performance: Your function counts all divisors
of a number, but

one can stop the test if any non-trivial divisor has been found,
any non-prime number \$ n \$ has a divisor which is \$ \le \sqrt n \$

Therefore this

    private static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        int limit = (int) Math.sqrt(n);
        for (int j = 2; j <= limit; j++) {
            if (n % j == 0) {
                return false;
            }
        }
        return true;
    }

    private static void printPrimesInRange(int low, int hi) {
        for (int n = low; n <= hi; ++n) {
            if (isPrime(n)) {
                System.out.println(n);
            }
        }
    }

would already improve the performance because the primality check
for each number \$ n \$ is reduced from \$ O(n) \$ to \$ O(\sqrt n) \$.

For the range 100000 200000 this reduced the time from 43 seconds
to approx 0.3 seconds on my 3.5 GHz Intel Core i5 iMac, measured with

$ time java PrimeNumbers < input > output

and for the range 999900000 1000000000 I measured 0.7 seconds.

So this might be sufficiently fast to pass the challenge.
For even better performance, use sieving methods like the
(segmented) sieve of Eratosthenes (see for example https://www.geeksforgeeks.org/segmented-sieve/).


How can I optimize this Monte Carlo simulation running at 10,000,000 iterations?

import random as rnd

I dislike abbreviation like this, they make the code harder to read

from time import time

#get user input on number of iterations
numOfIterations = raw_input('Enter the number of iterations: ')
numOfIterations = int(numOfIterations)

Any reason you didn't combine these two lines?

start = time()

#initialize bag (44 green, 20 blue, 15 yellow,  11 red, 2 white, 1 black
#a counter
#and question counter
bag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k'
counter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0}
question = {'one':0,'two':0,'three':0,'four':0,'five':0}

Looking up your data by strings all the time is going to be somewhat slower. Instead, I'd suggest you keep lists and store the data that way.

for i in range(0,numOfIterations):

Given that numOfIterations will be very large, its probably a good idea to use xrange here.

  for j in xrange(0,5):

You should generally put logic inside a function. That is especially true for any sort of loop as it will run faster in a function.

    draw = rnd.sample(bag,5)
    for x in draw: counter[x]+=1

I dislike putting the contents of the loop on the same line. I think it makes it harder to read.

  if counter['w'] >0 and counter['k'] >0: question['one']+=1
  if counter['b'] > counter['r']: question['two']+=1
  if counter['b'] > counter['y']: question['three']+=1
  if counter['y'] > counter['r']: question['four']+=1
  if counter['g'] < (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1
  for k in counter: counter[k] = 0

p1 = float(question['one'])/float(numOfIterations)
p2 = float(question['two'])/float(numOfIterations)
p3 = float(question['three'])/float(numOfIterations)
p4 = float(question['four'])/float(numOfIterations)
p5 = float(question['five'])/float(numOfIterations)

Don't create five separate variables, create a list. Also, if you add the line from __future__ import division at the beginning of the file then dividing two ints will produce a float. Then you don't need to convert them to floats here.

print 'Q1 \t Q2 \t Q3 \t Q4 \t Q5'
print str(p1)+'\t'+str(p2)+'\t'+str(p3)+'\t'+str(p4)+'\t'+str(p5)

See if you had p1 a list, this would be much easier

end = time()

print 'it took ' +str(end-start)+ ' seconds'

For speed improvements you want to look at using numpy. It allows implementing efficient operations over arrays.

In this precise case I'd use a multinomial distribution and solve the problem analytically rather then using monte carlo.


I've noticed you have a common bug that often occurs in Javascript code called a race condition.

If uniqueIdCreatorHandler is called again before a previous call finishes there is a race condition created because state.ids is replaced at the end of the call.

If both calls happen at the same time they each generate a unique copy of the original state.ids then overwrite state this.setState({ ids: ids });. This causes the first change to state.ids to be forgotten.

This is a direct result caused by replacing state. this.setState({ ids: ids });

As others have recommend I would simply keep a increment in state for new ids.

Note: you can easily demonstrate this in your code by adding and calling this method

double = () => {
  this.uniqueIdCreatorHandler()
  this.uniqueIdCreatorHandler()
}

Other comments
There are small improvements you could make to your code like spreading the mapped ids into Math.max.

I wouldn't worry too much about Javascript performance, focus on readability. Make variable names more verbose and add doc blocks to methods.

One thing I like to see (which you have done) is the embrace of array methods. Although they may not be necessary here they are a strong indicator of comprehension.

Keep it up!


Wait for a "3rd party" element to be appended to the DOM

That's a perfect job for MutationObserver.

new MutationObserver(function(mutations) {
    this.disconnect();
    // access the menu
    ........
}).observe($('.immediate-parent-of-the-menu')[0], {childList: true});

$button = $('#button');
$button.trigger('click');

The simplest case above works as-is if the menu is added in one mutation, otherwise you'd have to check each of the mutations array elements for addedNodes.


Guessing game where the first player inputs a word and a hint and the second player tries to guess it

You have a bit of code duplication that could be extracted and consolidated. But first with some error fixes (at least the code did not compile on my TASM).

Compilation issues

right:
    lea dx [win] ; <-- missing comma between dx and [win]

fail is defined twice. First as a string (fail db ' Enter guess again($') and the second time as a label. I would rename the first one to failmsg and use it in

lea dx, [failmsg] ; <-- instead of fail before

With those fixes the code compiles now. As for the code review I would start with

DOS functions

mov ah,09
int 21h

which is just Display string. So let's call it like that and make sure a requirement that when calling it we have dx

PROC display_string
   mov ah,09
   int 21h
   ret
ENDP

and instead of

lea dx, [a3msg]
mov ah, 9
int 21h

just do

lea dx, [a3msg]
call display_string

The same goes for other DOS functions

PROC get_char
   mov ah,01
   int 21h
   ret
ENDP

PROC put_char
   mov ah,02
   int 21h
   ret
ENDP

Using those instead of bare int-ing will make your code more readable. Having those it's clear what you try to do with this code

High-level functions

mov dx, 10
call put_char

but in DOS it should be 2 characters: 13,10 so it's better to do like this:

PROC new_line
  mov dx,13
  call put_char
  mov dx,10
  call put_char
  ret
ENDP

Buffered input

I don't know why you chose buffered input as your method of entering the hint, but in case of this command the data has a specific format.

hint db 100,?,101 dup(0)

The actual string starts on index 2 and before that you have max string length, and bytes read. Also there's no $ at the end. You have to put it there.

xor bx,bx
mov bl, [hint+1]
mov [hint+bx+2], '$'

So printing the hint should look like this:

lea dx, [hint+2]
call display_string

Printing the count

This is obviously wrong

lea dx, [cnt]
call put_char

as in the cnt will be the number of characters not the ascii representation of that number. If we could restrict ourselves to maximum 9 characters that would be easy. Just add 48(dec) to the cnt and you get the value. Since your secret is limited to 21 characters we could go with a simple method for printing.

PROC print_number
    push bx
    push dx
    mov bx,10
    xor dx,dx
    div bx
    mov bx,dx
    cmp ax,0
    je second
    mov dx,ax
    add dx,48
    call put_char
second:
    mov dx,bx
    add dx,48
    call put_char
    pop dx
    pop bx
    ret
ENDP

What we do here is just divide the number in ax by 10 and print the values stored in ax (result - only if >0) and the dx - reminder.

Printing the hints

On fourth attempt you are putting the character to be printed in dh. It should be in dl. You don't also have to use different registers so just:

mov dl, [secret]
call put_char
mov dl, [secret+1]
call put_char

To print the last char you need to keep in might that the last is '$' so just one before the last

mov di, [cnt]
mov dl, [secret+di-1]
call put_char

The same issue when you try to print the 6th hint. Also that you did not retrieve the char at all.

mov di, [cnt]
sub di,2
mov dl, [secret+di-1]
call put_char

Compare

Your compare method is kinda strange. You do not iterate at all and you don't use any opcodes that would do that for you. It works only when you have one-char secret. Not so cool :)

I would write it like this

PROC compare
  push cx
  lea si, [secret]
  lea di, [guess]
  rep cmpsb
  pop cx
  ret
ENDP

and change how to check for equality

call compare
je right

Other things that might be good to fix

You have the same loop for scanning the characters. Why not enclose it as another proc and just use in those two places? You can make assumption that for example di will point to the buffer that has to be filled. Also in this scanning you could handle for example backspace character and delete the characters.

PROC read_input
  push cx
  mov bx, 0
  mov cx, 0
scan:
  call get_char
  cmp al, '.'
  je com
  inc cx
  mov [di+bx], al
  inc bx
  jmp scan
com:
  mov [di+bx], '$'
  mov ax,cx
  pop cx
  ret
ENDP

And use it

lea di,[secret]
call read_input
mov [cnt],ax

and similarly in the second place.

Also some checks for input length might be good to do.

You should also comment more your code. I strongly believe the code should be self documented but not on such low level as asm :) So comment more.

GIST


What you really want is a robust argument parsing. This calls for argparse:

import argparse
import os.path

def is_file(f):
    if os.path.isfile(f):
        return f
    raise OSError("{} does not exist".format(f))

parser = argparse.ArgumentParser(description="SMTP user checker")
parser.add_argument('server', help="IP address of server")
parser.add_argument('usernames', type=is_file, help="Path to list of user names")
parser.add_argument('--port', '-p', type=int, default=25, help="SMTP port of server")
args = parser.parse_args()

smtp_conn = create_connection(args.server, args.port)
print smtp_conn.recv(1024)

Note that it is already standard practice of Python to print any error and exit afterwards.

Additionally, you probably want to close your SMTP connection even in the case of an exception. For this, you could use a contextmanager:

from contextlib import contextmanager

@contextmanager
def create_connection(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        yield sock
    except socket.error:
        # Handle specific exception here, or not and re-raise
        raise
    finally:
        # Ensure sock is closed under all circumstances
        try:
            sock.close()
        except UnboundLocalError:
            # Did not even succeed in creating the variable, nothing left to do
            pass

And then use it like this:

with create_connection(args.server, args.port) as smtp_conn:
    print smtp_conn.recv(1024)
    with open(args.usernames) as users:
        for user in users:
            print smtp_verify(user.strip(), smtp_conn)

Note that Python uses read mode by default when opening a file, so there is no need to use 'r'.

Final code:

import argparse
import socket
import os.path
from contextlib import contextmanager

@contextmanager
def create_connection(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        yield sock
    except socket.error:
        # Handle specific exception here, or not and re-raise
        raise
    finally:
        # Ensure sock is closed under all circumstances
        try:
            sock.close()
        except UnboundLocalError:
            # Did not even succeed in creating the variable, nothing left to do
            pass

def smtp_verify(username, smtp_conn):
    smtp_conn.send('VRFY {}\r\n'.format(username))
    return smtp_conn.recv(1024)

def is_file(f):
    if os.path.isfile(f):
        return f
    raise OSError("{} does not exist".format(f))

def parse_args():
    parser = argparse.ArgumentParser(description="SMTP user checker")
    parser.add_argument('server', help="IP address of server")
    parser.add_argument('usernames', type=is_file, help="Path to list of user names")
    parser.add_argument('--port', '-p', type=int, default=25, help="SMTP port of server")
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    with create_connection(args.server, args.port) as smtp_conn:
        print smtp_conn.recv(1024)
        with open(args.usernames) as users:
            for user in users:
                print smtp_verify(user.strip(), smtp_conn)

Alternatively, you could use the docopt module for this:

"""SMTP user checker.
Usage:
  argparser_comp.py SERVER USERNAMES [(-p <p>| --port=<p>)]
  argparser_comp.py (-h | --help)
Options:
  -h --help          Show this screen.
  -p <p> --port=<p>  SMTP port of server [default: 25].
"""

import socket
import os.path
from contextlib import contextmanager
from docopt import docopt

def is_file(f):
    if os.path.isfile(f):
        return f
    raise OSError("{} does not exist".format(f))

def parse_args():
    args = docopt(__doc__)
    return args["SERVER"], is_file(args["USERNAMES"]), int(args["--port"])

@contextmanager
def create_connection(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        yield sock
    except socket.error:
        # Handle specific exception here, or not and re-raise
        raise
    finally:
        # Ensure sock is closed under all circumstances
        try:
            sock.close()
        except UnboundLocalError:
            # Did not even succeed in creating the variable, nothing left to do
            pass

def smtp_verify(username, smtp_conn):
    smtp_conn.send('VRFY {}\r\n'.format(username))
    return smtp_conn.recv(1024)

if __name__ == "__main__":
    server, usernames, port = parse_args()
    with create_connection(server, port) as smtp_conn:
        print smtp_conn.recv(1024)
        with open(usernames) as users:
            for user in users:
                print smtp_verify(user.strip(), smtp_conn)


Multithreaded Python implementation of a Sudoku validator

The way you're starting the block threads looks wrong to me.  You're starting each thread with the same parameters (the grid and a queue):

t = Thread(target=check_3x3_grid, args=(grid, q))

I can't see anywhere that the thread is told which block it is supposed to check.  So, instead of starting 9 threads, one to check each block, it looks like you're starting 9 threads and having each of them check all nine of the blocks.

You could partition the blocks and then start a thread to validate each block, but this seems like overkill.  Simply starting a single thread to check the nine blocks is the smallest change and probably the right one to make, since checking nine blocks is almost the same amount of work as checking the nine horizontals/verticals.  With that in mind, you can simply change the code to the following (an achieve the same result with 8 less threads):

#...

grid_thread = Thread(target=check_3x3_grid, args=(grid, q))
grid_thread.start()

#...

grid_thread.join()

Or a slightly more concise:

validation_threads = [Thread(target=check_rows, args=(grid, q))
                     ,Thread(target=check_columns, args=(grid, q))
                     ,Thread(target=check_3x3_grid, args=(grid, q))]

[t.start() for t in validation_threads]
[t.join() for t in validation_threads]


Improving multiple assignment using an iterator function

I'll look at each of your three examples individually.

Ignoring remaining values

In Python 2:

>>> a, b = 'foo bar is here'.split()[:2]
>>> a, b
('foo', 'bar')

In Python 3 (_ used by convention, double underscore, __, is
also appropriate):

>>> a, b, *_ = 'foo bar is here'.split()
>>> a, b
('foo', 'bar')

When ignoring remaining values, using the built-in language features would be the most Pythonic approach.  I think they're clear enough that they do not need to be re-invented.
Capture remaining values

In Python 2:

>>> split_string = 'foo bar is here'.split()
>>> a, b, c = split_string[2:] + [split_string[2:]]
>>> a, b, c
('is', 'here', ['is', 'here'])

In Python 3:

>>> a, b, *c = 'foo bar is here'.split()
>>> a, b, c
('is', 'here', ['is', 'here'])

In Python 3, the * feature is again more Pythonic than your approach.  In Python 2, that approach won't work if you're dealing with a non-indexable type.
Fill remaining values with None.  Here is a somewhat similar question.  That question and the Python 2 solution only work for lists.

Python 2:

>>> split_string = 'foo bar is here'.split()
>>> a, b, c, d, e = split_string + [None] * (5-len(split_string))
>>> a, b, c, d, e
('foo', 'bar', 'is', 'here', None)

Python 3.5 (this is not very clear in my opinion):

>>> a, b, c, d, e, *_ = *'foo bar is here'.split(), *[None]*5
>>> a, b, c, d, e
('foo', 'bar', 'is', 'here', None)

There isn't really a built-in language construct for this so this case might warrant re-inventing.  However, this kind of None-filling seems rare and may not necessarily be clear to other Python programmers.

A review of your actual implementation

Don't use import * in Python.  In Python we value our namespaces highly because namespaces allow us to see what variables came from what modules.

from itertools import *

Do this instead:

from itertools import chain, islice, repeat

You didn't use use_default in your code at all.  It seems like you could use another islice instead of an enumerate to restructure your code like this:

def iterassign(iterable, *, count, default=None, tail=False):
    it = iter(iterable)
    for x in islice(chain(islice(it, 0, count), repeat(default)), 0, count):
        yield x
    if tail:
        yield list(it)

Iterators are the right solution to this problem (assuming we've decided it's one that needs solving).

If we want to rewrite this to only handle case 3 (because we've already decided we can just use Python's built-in language features for case 1 and 2, we could rewrite like this:

def fill_remaining(iterable, *, length, default=None):
    """Return iterable padded to at least ``length`` long."""
    return islice(chain(iterable, repeat(default)), 0, length)

Which would work like this:

>>> a, b, c, d, e = fill_remaining(ret, length=5)
>>> a, b, c, d, e
('foo', 'bar', 'is', 'here', None)


Let's break down your algorithm for a moment:

get a String to analyze ("bananas").
do a 'nested' loop (i,j) to find every possible sub-word in it
for each sub-word, inject it in to the possible node tree 1 character at a time.

With that tree, you can then compare matching values to see if they exist in the tree. To see if they exist, you:

loop over each character in the search word
for each character, you check whether a Node exists matching the respective character a the respective level.
if any character is impossible, you return false. If all characters are possible, you return true.

Problems

the name - it is not a "Suffix" Tree, it is an "Infix" tree. It does not  match only suffixes.
the overhead - The HashMap instances and the Character and Node classes, are a problem from a memory perspective. Sure, the count of these instances will be relatively small, but, for "bananas", you are creating about.... 28 HashMaps? Each HashMap has a significant memory footprint. It is expensive.

Advantages

the perceived advantage here is that you have discrete places where the data exists in a tree. You can check for infixes starting from any character in the base word, at the same time.

Alternatives

There are two alternatives I recommend, the differences between them will depend on the number of letters in the input word. The one solution has a runtime performance of \$O(1)\$, but a memory consumption of \$O(n^2)\$. The other has a runtime performance of \$O(n \log n)\$ and a memory consumption of \$O(n)\$. Note that your solution has a runtime performance of \$O(n)\$ and a memory size of \$O(n^2)\$.

What does that mean? It means the one alternative will have slitgtly worse performance than yours for larger inputs, but will take much less space. The other alternative will be much faster than yours for larger inputs, and will take about the same proportion of space. Each alternative has merits over yours.

In your solution, with \$n\$ being the number of letters in the input word ("bananas"), your runtime performance requires you scanning the Node tree for as many as n nodes (one for each letter), which makes your check performance proportional to the number of characters in the input word. The number of nodes you have is proportional to the square of the number of input letters, so if you double the number of letters, you quadruple the number of nodes.

The two alternatives I suggest are different, in that the one alternative will have an \$O(n \log n)\$ search performance but an \$O(n)\$ memory performance. Because of the way the data is stored, though, for smaller input strings ("bananas" is small), it will likely be much faster though, than yours.

The other solution is much faster (essentially constant time - \$O(1)\$ ), but has a higher memory cost - about the same as your code.

Fastest - and Largest

The fastest solution is to take all possible substrings from the input and put them in a HashSet. The input processing is simple:

Set<String> infixes = new HashSet<>();
for (int i = 0; i < input.length; i++) {
    for (j = i + 1; j < input.length; j++) {
        infixes.add(input.substring(i,j));
    }
}

Now, there's a single HashSet (which under the covers is a HashMap), and it contains all substrings. Searching for those substrings is a case of computing the hashCode of the search value, and it will find the value "fast"...

return infixes.contains(search);

That algorithm stores potentially a lot of strings, but the search is lightning fast.

The way this code works, is by taking the input string, and splitting it in all possible ways. For example, from "fubar" you will get:

f fu fub fuba fubar u ub uba ubar b ba bar a ar r

Put those all in the set, and every possible infix "search" word is recorded. The HashSet makes the search effectively an O(1) operation.

Fastish - and Smallish

The second alternative will slow down (very slightly) as the input words get larger, but the memory footprint will be relatively small.

First, create an Array of words.... each word being a suffix:

String[] suffixes = new String[input.length];
for (int i = 0; i < input.length; i++) {
    suffixes[i] = input.substring(i);
}

Then, sort it....

Arrays.sort(suffixes);

That array is pretty small in comparison to your alternatives....

Now, using that, you can quickly find (in \$O(n \log n)\$ time) whether a search string is a suffix:

int ip = Arrays.binarySearch(suffixes, search);
if (ip >= 0) {
    // exact match to a suffix
    return true;
}
// no exact match, but, maybe the place the value would
// belong is a longer version of our search term....
ip = -ip - 1;

return ip < suffixes.length && suffixes[ip].startsWith(search);

This algorithm works in part by relying on the lexical (alphabetical) sorting of any suffix of the input word. Again, using "fubar", the code creates all 5 suffixes:

fubar ubar bar ar r

It then sorts them alphabetically:

ar
bar
fubar
r
ubar

Now, if you want to find a search string that is a complete suffix (like "bar"), then the binary search will find it no problem, and return true. But, what if you want tos earch for an "infix", or a not-complete suffix, for example, "ba"? Well, "ba" would normally fit alphabetically between "ar" and "bar". The Arrays.binarySearch will return the 'insertion point' of -2. The -2 indicates that there was not an exact match, but if we want to insert the value in the array, we would insert it before the element at - ip - 1, or, since the ip is -2, at - (-2) - 1, or before position 1.

Note though, that because of the alphabetic order, if the search term is an infix, it is by definition, a prefix of a suffix ;-), and if it is a prefix of a suffix, the suffix it is a prefix of is alphabetically immediately after it. So, if the search term matches the start of the insertion-point value, then the search term is an infix of the original word.

That's all just a complicated way of saying: if the search term is an exact match of a suffix, it is a match, or, if it matches the beginning of the suffix alphabetically after it, it is a match.

Either way, you can locate that match with the binary search, and test the insertion point.

Code

public class SearchNLogN {

    private final String[] suffixes;

    public SearchNLogN(String input) {
        suffixes = new String[input.length()];
        for (int i = 0; i < suffixes.length; i++) {
            suffixes[i] = input.substring(i);
        }
        Arrays.sort(suffixes);
    }

    public boolean search(final String search) {
        int ip = Arrays.binarySearch(suffixes, search);
        if (ip >= 0) {
            return true;
        }
        ip = -ip - 1;
        return ip < suffixes.length && suffixes[ip].startsWith(search);
    }

}

and

import java.util.HashSet;
import java.util.Set;

public class SearchO1 {

    private final Set<String> infixes = new HashSet<>();

    public SearchO1(String input) {
        for (int i = 0; i < input.length(); i++) {
            for (int j = i + 1; j <= input.length(); j++) {
                infixes.add(input.substring(i, j));
            }
        }
    }

    public boolean search(String search) {
        return infixes.contains(search);
    }

}

Results

Running the two code chunks above, as well as your code chunk, for a number of iunput values ("foo", "bananas", and "supercali......"), with a number of test values (including the input value itself), and then benchmarking the results (using Microbench ), I get:

Your code: small, medium, large (microseconds) - 0.24, 0.5, 1.2

Task SuffixTree -> foo: (Unit: MICROSECONDS)
  Count    :     10000      Average  :    0.5620
  Fastest  :    0.2390      Slowest  : 1044.6770
  95Pctile :    0.7730      99Pctile :    1.2420
  TimeBlock : 1.480 0.471 0.326 0.271 0.257 0.254 0.263 0.249 0.252 1.804
  Histogram :  8781   855   302    11     1    44     2     1     1     0     0     1     1

Task SuffixTree -> bananas: (Unit: MICROSECONDS)
  Count    :     10000      Average  :    0.9490
  Fastest  :    0.5020      Slowest  : 1107.9860
  95Pctile :    1.7720      99Pctile :    2.7260
  TimeBlock : 2.734 0.848 0.670 0.635 0.532 0.635 0.635 0.612 1.638 0.561
  Histogram :  8790   870   268    13    12    41     0     5     0     0     0     1

Task SuffixTree -> supercalifragilisticexpialidocious if you like the sounds of that it must be quite atrocious.: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   1.8380
  Fastest  :   1.2400      Slowest  :  96.8740
  95Pctile :   3.8860      99Pctile :   5.9270
  TimeBlock : 5.778 1.999 1.392 1.321 1.300 1.337 1.315 1.276 1.301 1.371
  Histogram :  8782  1082    51    44    24    16     1

Search O1: small, medium, large (microseconds) - 0.18, 0.25, 0.21

Task SearchO1 -> foo: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   0.7840
  Fastest  :   0.1810      Slowest  :  75.3810
  95Pctile :   1.9970      99Pctile :   2.5670
  TimeBlock : 2.212 2.002 1.980 0.255 0.236 0.250 0.236 0.228 0.225 0.226
  Histogram :  6978     3     3  2944    46    12    13     0     1

Task SearchO1 -> bananas: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   0.9330
  Fastest  :   0.2510      Slowest  :  36.0610
  95Pctile :   2.2400      99Pctile :   3.1790
  TimeBlock : 2.429 2.231 2.284 0.367 0.343 0.356 0.346 0.340 0.318 0.316
  Histogram :  6969     3   243  2735    19    28     1     2

Task SearchO1 -> supercalifragilisticexpialidocious if you like the sounds of that it must be quite atrocious.: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   0.8450
  Fastest  :   0.2190      Slowest  :  21.3880
  95Pctile :   2.1300      99Pctile :   2.6750
  TimeBlock : 2.208 2.120 2.104 0.309 0.290 0.297 0.291 0.279 0.279 0.276
  Histogram :  6966    13    29  2955    23    13     1

Search NlogN: small, medium, large (microseconds) - 0.24, 0.33, 0.60

Task SearchNLogN -> foo: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   0.5180
  Fastest  :   0.2430      Slowest  :  66.9210
  95Pctile :   1.0680      99Pctile :   2.2020
  TimeBlock : 1.430 0.350 0.252 0.357 0.504 0.504 0.550 0.531 0.392 0.312
  Histogram :  5928  3500   389   128    20    29     4     1     1

Task SearchNLogN -> bananas: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   0.6610
  Fastest  :   0.3340      Slowest  :  44.2550
  95Pctile :   1.2930      99Pctile :   2.5630
  TimeBlock : 1.671 0.429 0.350 0.497 0.678 0.675 0.705 0.688 0.542 0.384
  Histogram :  6812  2758   342    48    25     9     5     1

Task SearchNLogN -> supercalifragilisticexpialidocious if you like the sounds of that it must be quite atrocious.: (Unit: MICROSECONDS)
  Count    :    10000      Average  :   1.1370
  Fastest  :   0.6030      Slowest  :  46.9750
  95Pctile :   1.9280      99Pctile :   4.7460
  TimeBlock : 2.719 0.737 0.628 0.887 1.187 1.194 1.204 1.216 0.924 0.679
  Histogram :  8380  1266   256    57    34     6     1


Wrapping a CSV file for access and testing

Just passing by. There are few comments I want to make here.

ReadCountData() is definitely out of place because the first method just exposes you to a StreamReader object reference. This method can not be unit-tested. I created an interface called IFile that wraps the static OpenText() method

public  interface IFile
{
    StreamReader OpenText(string path);
}

  I created a FileClass that uses this interface

public  class FileClass
{
    private readonly IFile file;

    public FileClass(IFile file)
    {
        this.file = file;
    }

    // I renamed your ReadCountData as OpenFile
    public void OpenFile(string path)
    {
        try
        {
            var fileReader = file.OpenText(path);
        }
        catch (Exception e) {
            // do whatever;
        }
    }
}

Using this approach, you can unit-test the OpenText() using the below code

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void OpenFile_PathAsAParameter_CSVFileOpened()
    {

        //Arrange
        string path = @"C:\myfilerocks.txt";
        var fileMock = new Moq.Mock<IFile>();
        var fileClass = new FileClass(fileMock.Object);

        //Act
        fileClass.OpenFile(path);

        //Assert
        fileMock.Verify(x=> x.OpenText(path));
    }
}

Notice there is still a dependency on StreamReader and TextReader, it's best to create a wrapper for those classes. When you have some many static class in a testable method I see it more as a smell . When a wrapper can't be created for them keep them as dependency e.g  public void ReadCountData(TextReader fileReader) seems alright to me. If you are looking for wrappers for the file system, visit System.IO.Abstractions by Jonathan Channon. His blog also explains a great deal Abstracting the File System

So the above test that the OpenText() was called.
Rather than using csvReader, I will use TextFieldParser from Microsoft.VisualBasic.FileIO.TextFieldParser . It works for both C# and VB. Note this example was extracted from Reading CSV Files using C#

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData)
    {
        //Processing row
        string[] fields = parser.ReadFields();
        foreach (string field in fields)
        {
           //TODO: Process field
        }
    }
}

Note: AbsolutePath, Delimiter is redundant here.
Refrain from names like ReadCountData, they don't provide information about their functionality. I would've thought ReadDataCount sounds better.


Add effective error handling to Python Notebook in Azure Synapse Analytics

Ignoring your closed-connection and managed-identity questions, since (a) I don't know how to answer them and (b) on their own they're off topic, there is still review to be done:

A Pythonic way to tell the standard library to format your URI instead of you doing it yourself is to call into urlunparse
Consider using pathlib
connect accepts kwargs as an alternative to the conn string, and the former will lay out your connection parameters more nicely
except / raise is redundant and should be deleted
Your try starts too early and should only start after the connection has been established
You're not reading a lines list; you're reading content, which would be a better variable name

Suggested
from pathlib import Path
from urllib.parse import urlunparse, ParseResult
import pyodbc
from pyspark import SparkFiles

pAccountName = 'someStorageAccount'
pContainerName = 'someContainer'
pRelativePath = '/raw/sql/some_sql_files/'
pFileName = 'someSQLscript.sql'

# Add the file to the cluster so we can view it
sql_filename = urlunparse(
    ParseResult(
        scheme='abfss',
        netloc=f'{pContainerName}@{pAccountName}.dfs.core.windows.net',
        path=f'{pRelativePath}{pFileName}',
        params=None, query=None, fragment=None,
    )
)

sc.addFile(sql_filename, False)

# Open the file for reading
sql_file_path = Path(SparkFiles.getRootDirectory()) / pFileName
with sql_file_path.open() as f:
    content = f.read()

# Open the database connection
conn = pyodbc.connect(
    DRIVER='{ODBC Driver 17 for SQL Server}',
    SERVER='someServer.sql.azuresynapse.net',
    DATABASE='someDatabase',
    UID='batchOnlyUser',
    PWD='youWish',
    autocommit=True,
)

try:
    # Split the script into batches separated by "GO"
    for batch in content.split("GO"):
        conn.execute(batch)  # execute the SQL statement
finally:
    conn.close()


Checking if there are no numbers from cellular services

Have a look whether you can extract the code into a function. It then may look like this.

def has_no_numbers():
  if use_verizon_sms:
    return Api.check_avalible_credits()

  if use_verizon:
    return buy_verizon_number()

  if check_count_numbers()
    return True

  raise Exception("THERE IS NO AVAILABLE NUMBERS")