Algorithm to transform one word to another through valid words

There are four other answers here, and they all have very sensible advice. But none of them, as far as I can see, points out the terrible runtime complexity of the chosen algorithm, so I think an additional answer is necessary.

1. Bug

>>> english_words = set('bar bat cat war'.split())
>>> transform(english_words, 'bar', 'war', 0)
['bar', 'bat', 'cat', 'war']

As pointed out by Barry, ths is because the line

potential_ans[:-1]

is a mistake for:

potential_ans.pop()

In what follows, I'm going to assume that the bug is fixed.

2. Abstracting the problem

The problem being solved here can be thought of as a problem on a graph, in which each word is a node of the graph, and two words are connected if they differ by one letter. Supposing that the words are cake, came, camp, dame, damp, dike, dime, lake, lame, lamp, like, lime, and limp, then the graph looks like this:

A transformation of one word to another corresponds to a path in this graph. For example one possible transformation of cake to limp corresponds to the highlighted path here:

Finding the shortest transformation between two words corresponds to finding the shortest path between the two nodes in the graph.

There are several benefits of thinking about a problem in terms of abstract data structures like graphs, including:

There are standard terms for describing the problem: here nodes, edges, paths.
There are concrete representations of the data structure that support efficient operations.
You can look up the best known algorithms for solving the problem, instead of having to invent your own.

3. Description and complexity of algorithm

With the bug noted in §1 fixed, what your program does is to generate all the simple paths (paths with no repeated nodes) in the graph of words beginning at start, until it finds a path that leads to end.

But this can take a very very long time:

>>> from timeit import timeit
>>> english_words = set('bar bat cat eat fat hat mat oat pat rat sat tat vat war'.split())
>>> timeit(lambda:transform(english_words, 'bar', 'war', 0), number=1)
['bar', 'war']
2732.44891167

Why does the algorithm take three-quarters of an hour to find this result? Well, the graph being searched looks like this:

The algorithm starts at bar and keeps adding nodes to its path until it can't go any further without repeating a node. For example (depending on the order in which the words are retrieved from the set), it might end up with this path:

After backtracking a couple of steps, it will find this path:

and so on. You'll see that it will explore every path that starts bar—bat and then visits all the —at words. There are \$ 11! = 39,916,800 \$ such paths, and only when it has explored them all will it consider the path bar—war.

Checking to see if two words with \$ m \$ letters differ by one letter takes time \$ O(m) \$, so if there are \$ n \$ words of \$ m \$ letters each, the total runtime is \$ O(n!m) \$.

4. Better algorithm

It is possible to do much better than this if you use one of the standard graph search algorithms such as Dijkstra's or A*. Here's an implementation using the latter.

from collections import defaultdict, namedtuple
from heapq import heappush, heappop

class NotFound(Exception):
    pass

def word_ladder(words, start, end):
    """Return a word ladder (a list of words each of which differs from
    the last by one letter) linking start and end, using the given
    collection of words. Raise NotFound if there is no ladder.

    >>> words = 'card care cold cord core ward warm'.split()
    >>> ' '.join(word_ladder(words, 'cold', 'warm'))
    'cold cord card ward warm'

    """
    # Find the neighbourhood of each word.
    placeholder = object()
    matches = defaultdict(list)
    neighbours = defaultdict(list)
    for word in words:
        for i in range(len(word)):
            pattern = tuple(placeholder if i == j else c
                            for j, c in enumerate(word))
            m = matches[pattern]
            m.append(word)
            neighbours[word].append(m)

    # A* algorithm: see https://en.wikipedia.org/wiki/A*_search_algorithm

    # Admissible estimate of the steps to get from word to end.
    def h_score(word):
        return sum(a != b for a, b in zip(word, end))

    # Closed set: of words visited in the search.
    closed_set = set()

    # Open set: search nodes that have been found but not yet
    # processed. Accompanied by a min-heap of 4-tuples (f-score,
    # g-score, word, previous-node) so that we can efficiently find
    # the node with the smallest f-score.
    Node = namedtuple('Node', 'f g word previous')
    open_set = set([start])
    open_heap = [Node(h_score(start), 0, start, None)]
    while open_heap:
        node = heappop(open_heap)
        if node.word == end:
            result = []
            while node:
                result.append(node.word)
                node = node.previous
            return result[::-1]
        open_set.remove(node.word)
        closed_set.add(node.word)
        g = node.g + 1
        for neighbourhood in neighbours[node.word]:
            for w in neighbourhood:
                if w not in closed_set and w not in open_set:
                    next_node = Node(h_score(w) + g, g, w, node)
                    heappush(open_heap, next_node)
                    open_set.add(w)

    raise NotFound("No ladder from {} to {}".format(start, end))

Suppose that there are \$ n \$ words of \$ m \$ letters, and \$ e \$ edges in the graph of words. Then this algorithm takes \$ O(m^2n) \$ to find the edges and then \$ O(e + mn + n \log n) \$ to find the shortest path.

So this finds shortest ladders on large sets of words in a reasonable amount of time:

>>> dictionary = [w.strip() for w in open('/usr/share/dict/words') if w == w.lower()]
>>> five_letter_words = [w for w in dictionary if len(w) == 5]
>>> len(five_letter_words)
8497
>>> from timeit import timeit
>>> timeit(lambda:print(' '.join(word_ladder(five_letter_words, 'above', 'below'))), number=1)
above amove amoke smoke smoky sooky booky booly bolly bally balli balai balao baloo balow below
0.3188382713124156


Procedural generation of an infinite map made up of 1's and 0's

I know that this is minor, but you should not stuff all your code together without spaces like:

for (int y=0;y<complexity;y++){
    level[complexity-1,y]=RandomReturn(complexity-1+offsetx,y+offsety);

Because spaces help differentiate tokens at a first glance, I suggest one space on each side of each operator.


The XY class looks like it would be better as a plain struct:
struct XY
{
    short x;
    short y;
};

Then we don't need to declare a constructor, because it can be aggregate-initialised.
I'll assume that your vector is an alias for std::vector here, since there's no definition visible.
Eight of the statements to populate the vector look reasonable.  The duplicate of x+1, y-1 is probably unintended, though.
You might profitably use emplace_back rather than writing those constructors.  We could create the vector directly, with all the element values as its initializer-list:
std::vector<XY> neighboursOf(XY coord)
{
    auto const x = coord.x;
    auto const y = coord.y;

    return { {x-1, y-1}, {x, y-1}, {x+1, y-1},
             {x-1, y  },           {x+1, y  },
             {x-1, y+1}, {x, y+1}, {x+1, y+1} };
}

See how the formatting here helps us see that each neighbour is included exactly once?
It is possible to write a clever loop, but that's going to be harder to read and no more efficient than the straightforward code.
Note that if we have a finite grid, then we might want special behaviour at the edges.  And if we have an infinite grid, we'll suffer arithmetic overflow (Undefined Behaviour) when we reach the limits of short.


Get the first item in a sequence that matches a condition

This is a use case for the walrus operator :=, which was introduced in Python 3.8. It allows you to write 1) without repeating yourself:
runner = next(
    r
    for caller in inspect.stack()
    if isinstance(r := caller[0].f_locals.get("runner"), AbstractRunner)
)

Whether or not you find this more readable or if this is too much nestedness in the if part is up to personal taste.


Short script to hash files in a directory

First of all, I'd make a variable which will keep the current path. For that, I'd use os.getcwd(...):

current_path = getcwd()

From the docs:

  Return a string representing the current working directory.

After this, I'd normalize the path, so that your script will be able to run on multiple OSs:

current_path = normpath(getcwd())

From the docs:

  Normalize a pathname by collapsing redundant separators and up-level
  references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
  This string manipulation may change the meaning of a path that
  contains symbolic links. On Windows, it converts forward slashes to
  backward slashes.

Then, I'd get a list of all the files in the directory using listdir(...):

only_files = [join(current_path, f) for f in listdir(current_path) if isfile(join(current_path, f))]

After getting the files, I'd wrap everything within a function:

def get_files():
    current_path = normpath(getcwd())
    return [join(current_path, f) for f in listdir(current_path) if isfile(join(current_path, f))]

Then, I'd make another function which will return a list of hashes for all the files in the list:

def get_hashes():
    files = get_files()
    list_of_hashes = []
    for each_file in files:
        hash_md5 = hashlib.md5()
        with open(each_file, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        list_of_hashes.append('Filename: {}\tHash: {}\n'.format(basename(each_file), hash_md5.hexdigest()))
    return list_of_hashes

After this, I'd just write this list of hashes in the desired file:

def write_hashes():
    hashes = get_hashes()
    with open('list_of_hashes.txt', 'w') as f:
        for md5_hash in hashes:
            f.write(md5_hash)

Finally, the code would look like this:

from os import listdir, getcwd
from os.path import isfile, join, normpath, basename
import hashlib

def get_files():
    current_path = normpath(getcwd())
    return [join(current_path, f) for f in listdir(current_path) if isfile(join(current_path, f))]

def get_hashes():
    files = get_files()
    list_of_hashes = []
    for each_file in files:
        hash_md5 = hashlib.md5()
        with open(each_file, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        list_of_hashes.append('Filename: {}\tHash: {}\n'.format(basename(each_file), hash_md5.hexdigest()))
    return list_of_hashes

def write_hashes():
    hashes = get_hashes()
    with open('list_of_hashes.txt', 'w') as f:
        for md5_hash in hashes:
            f.write(md5_hash)

if __name__ == '__main__':
    write_hashes()

Now, why I'd do it this way:

Compare your code with this new one, and tell me which one is more readable.
You should read PEP8, which is the standard style guide for python.
You should use with() when opening a file as this will make sure the file will be closed when needed.
I've used for chunk in iter(lambda: f.read(4096), b"") which is a better approach for hashing large files (sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially).
I've split the logic of your main program into multiple functions which I'll let you document using docstrings:

E.g:

def get_files():
    """Returns a list of all files in the current directory"""
    # ...

You can see that I also added if __name__ == '__main__'. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

To be considered:

MD5 is known broken and (IMHO) should come with scary deprecation warnings and removed from the library, so you should actually do the hashing thing using sha256 from the the same module:

Remember:

Each statement that you write is important, and if changing the name of a local variable / method / anything with a descriptive name makes your code a lot clearer and more readable then do it!


My one improvement would be this line of code

if self.death is None:
    family_tree.deaths.append('N/A')
else:
    family_tree.deaths.append(self.death)

can be reduced to one line:

family_tree.deaths.append('N/A' if self.death is None else self.death)

Also, I would recommend keeping all code not in these classes in a main guard, so you can import these classes without also running the code in the module.


SQLite and Python: commit once every 10 seconds maximum, and not after every client request

What do you think of the following code? Is it safe to do like this?

In my opinion, it is not. So many things could go wrong.

One example: in this code there is no exception handling. If your program crashes for any reason, your routine may not be triggered. Fix: add an exception handler that does some cleanup, commits and closes the DB. Or better yet, just do that commit in the finally block.

By the way the doc says this about the close function:

  This closes the database connection. Note that this does not
  automatically call commit(). If you just close your database
  connection without calling commit() first, your changes will be lost!

So it is a good idea to commit systematically.

  time.sleep(10)  # I hope this doesn't block/waste CPU here?

time.sleep blocks the calling thread. It is useless anyway because what you want here is a timer, not a thread. You can have a timer routine that runs every n seconds to perform a  given task. But you should still have a commit in the finally block, so that all pending changes are written to the DB when the program ends, even after an exception.

Now to discuss the functionality more in depth:
You say:

  In a Python Bottle server using SQLite, I noticed that doing a DB
  commit after each INSERT is not efficient: it can use 100ms after each
  client request.

That may not be 'efficient' but if I have to choose between slow and safe there is no hesitation. Have you actually measured how long it takes on your own environment ?

On Stack Overflow you wrote:

  I optimized my server to serve pages very fast (10ms), and it would be
  a shame to lose 100ms because of DB commit.

While I applaud your obsession with performance, does 100 ms really make a difference to your users ? It normally takes more than 100 ms to load a page or even refresh a portion of it using Ajax or a websocket. The latency resides in the network transport. I don't know how your application is structured but my priority would be to deliver as little traffic as possible to the users. Websocket + client-side JS should do.

Perhaps using a different storage medium could improve IO performance. If you are not using a SSD drive, maybe you could consider it or at least test it.

Before writing code like this I would really try to exhaust all possibilities, but it is better (more reliable) to let SQLite handle things using the options that already exist. What have you tried so far ?

Would this be acceptable to you ?

PRAGMA schema.synchronous = OFF

  With synchronous OFF (0), SQLite continues without syncing as soon as
  it has handed data off to the operating system. If the application
  running SQLite crashes, the data will be safe, but the database might
  become corrupted if the operating system crashes or the computer loses
  power before that data has been written to the disk surface. On the
  other hand, commits can be orders of magnitude faster with synchronous
  OFF.

Source: PRAGMA Statements

There is a risk of corruption in case of power loss but this is no worse than what you are doing. If on the other hand data integrity is more important you should stick to a full commit after every operation.

You should also have a look at Write-Ahead Logging. This may interest you if there are concurrent writes to your database. Otherwise opening the DB in EXCLUSIVE mode may bring some benefits (see the PRAGMA page for details).

More detailed discussions:

Atomic Commit In SQLite
35% Faster Than The Filesystem

Last but not least: transactions. SQLite starts an implicit transaction automatically every time you run a SQL statement and commits it after execution. You could initiate the BEGIN & COMMIT TRANSACTION statements yourself. So if you have a number or related writes, regroup them under one single transaction. Thus you do one commit for the whole transaction instead of one transaction per statement (there is more consistency too: in case an error occurs in the middle of the process you won't be left with orphaned records).

There are quite many things you can try until you find the mix that is right for you.


Vectorized numpy version of arange with multiple start stop

This code looks good to me: the docstring is clear and the implementation is simple and efficient. So I have only a few minor points.

The code doesn't fit in 80 columns, meaning that we have to scroll it horizontally to read it here on Code Review.
The docstring contains an example. If it were formatted like this:

>>> starts = np.array([1, 3, 4, 6])
>>> lengths = np.array([0, 2, 3, 0])
>>> vrange(starts, lengths)
array([3, 4, 4, 5, 6])

then it could be run using the doctest module, allowing you to automatically check that it is correct.
The example in the docstring uses the print statement and so is not compatible with Python 3.
I think it would be clearer to take a stops array instead of a lengths array. It would then have an interface that corresponds closely to range and numpy.arange. Possibly lengths is more convenient for your application, but you can easily calculate stops = starts + lengths.
The docstring says that starts and lengths must be "numpy.array", by which I think you mean numpy.ndarray, but in fact it's OK for starts to be an array_like because the code doesn't call any methods on it.
It would be possible to allow lengths to be array_like too, by calling numpy.asarray.
The implementation requires starts and lengths to be 1-dimensional, so the docstring should mention this.
The implementation carries out a sum that includes (among other terms):

np.repeat(starts, lengths) - np.repeat(lengths.cumsum() - lengths, lengths)

this is the same as:

np.repeat(starts - lengths.cumsum() + lengths, lengths)

which saves a call to numpy.repeat, and this is the same as:

np.repeat(stops - lengths.cumsum(), lengths)

Putting all that together, I get:

def vrange(starts, stops):
    """Create concatenated ranges of integers for multiple start/stop

    Parameters:
        starts (1-D array_like): starts for each range
        stops (1-D array_like): stops for each range (same shape as starts)

    Returns:
        numpy.ndarray: concatenated ranges

    For example:

        >>> starts = [1, 3, 4, 6]
        >>> stops  = [1, 5, 7, 6]
        >>> vrange(starts, stops)
        array([3, 4, 4, 5, 6])

    """
    stops = np.asarray(stops)
    l = stops - starts # Lengths of each range.
    return np.repeat(stops - l.cumsum(), l) + np.arange(l.sum())

This is not quite as clear as your implementation: it's hard to give a concise explanation of what stops - l.cumsum() means. So I can see an argument for preferring the more explanatory version even if it does have an extra call to numpy.repeat.


Building equal number of records list object

Try following some simple rules: Avoid setting flags in loops. Try calculating the data you need before taking action. Only increment counters inside loop declaration. This way even if something gets broken - you will not have to wonder "how did we end up here?". Instead you will be able to tell "this index / limit is not calculated correctly".

Also when saying

  even if that means that first column doesn't fill page to bottom on the second page

Did you mean:

  even if that means both columns don't fill the last page to the bottom

This is how I understood it.

int ROWS_PER_PAGE = 41;
int totalDataCount = dataTable.Rows.Count;
int pagesToProcess = (int)Math.Ceiling(totalDataCount / 2.0 / ROWS_PER_PAGE);
int itemsPerPage = ROWS_PER_PAGE * 2;

for(int pageIdx = 0; pageIdx < pagesToProcess; pageIdx++)
{
    int itemsOnThisPage = (pageIdx + 1) * itemsPerPage >= totalDataCount ? totalDataCount - pageIdx * itemsPerPage : itemsPerPage;
    int rowsOnThisPage = (int)Math.Ceiling( itemsOnThisPage / 2.0 );
    for( int rowIdx = 0; rowIdx < rowsOnThisPage; rowIdx++)
    {
        var item = new DataForExcelExport();
        int itemIdx1 = pageIdx * itemsPerPage + rowIdx;
        int itemIdx2 = itemIdx1 + rowsOnThisPage;
        SetItemData(dataTable.Rows[itemIdx1], item, true);
        if(totalDataCount > itemIdx2)
            SetItemData(dataTable.Rows[itemIdx2], item, false);
    }
}

Ah yes, and try to name variables in a meaningful way. Names like i or maxrow do not tell what the variable is really used for.


Non-sequential template class container C++

Thanks for a well-presented question!  I'll dive straight in:

Your exceptions are a bit weird.  Leaving aside the impenetrable (to me) naming, I think that adding your own exception types derived directly from std::exception just to add your own what() is probably a poor investment of time.  If you go this way, I certainly recommend that you subclass the provided std::bad_alloc and std::out_of_range, so that existing code that catches those also catches your equivalents.

Having member variables of exception type in your container instances is decidedly unconventional.  We generally create exceptions at the point where they are thrown.  This may be important in a debugging environment, if exceptions there are able to carry context information (as happens in Python and Java, for example).  In production code, the exception construction will be very low overhead compared with actually raising and catching the exception, so there's little to be gained in speed, and something to be lost by adding unnecessary members to every instance.

A quick skim through the rest of the code draws me to this line:

        std::shared_ptr<A_Type> ptr(new A_Type(std::forward<Args>(args)...));

Bare new in modern C++ always triggers my interest - here, it is better to use std::make_shared().  This will give improved memory locality to the object and its smart-pointer control block.

This gives my version of your code as follows:

#include <memory>
#include <vector>

template<typename A_Type>
class CNSContainer
{
    std::vector<std::shared_ptr<A_Type>> pointers_m;
public:
    size_t size()
    {
        return pointers_m.size();
    }

    template <class... Args>
    std::weak_ptr<A_Type> push(Args&&... args)
    {
        // may throw std::bad_alloc - if so, pointers_m is unchanged
        auto ptr = std::make_shared<A_Type>(std::forward<Args>(args)...);
        pointers_m.emplace_back(ptr);
        return ptr;
    }

    void remove(const size_t& key)
    {
        pointers_m.erase(pointers_m.begin() + key);
    }

    // Will throw std::out_of_range if key is invalid
    std::weak_ptr<A_Type> operator[](const size_t& key)
    {
        return pointers_m[key];
    }
};

At this point, there's almost nothing here that's not in the underlying container, and much that's missing (reserve(), iterators, member types, and more).  What you end up with is a convenience function for creating a smart-pointer member in a collection:

#include <memory>

template<typename Container, class... Args>
std::weak_ptr<typename Container::value_type> push(Container& c, Args&&... args)
{
    // may throw std::bad_alloc - if so, c is unchanged
    auto p = std::make_shared<typename Container::value_type>(std::forward<Args>(args)...);
    c.emplace_back(p);
    return p;
}

You might be able to further generalize that to not depend on emplace_back as the insertion method and/or use Concepts to constrain the function and give more informative errors if it's misused.

I'm sorry if the above reduces what you've written to something near-trivial, but I hope you've learnt a lot whilst you were doing it (and that you can apply that to your future projects).  Certainly, you seem to have your head around forwarding references, which is more than many can say!


Find the closest number to each given number

First point: every time anybody writes code with using namespace std; at global scope, a cute, furry little animal dies a horrible death. You don't want that on your conscience, so you need to stop doing it1.

Right now, you seem to be doing a linear search. Since you've sorted the numbers, you could do a binary search instead. This could use either std::lower_bound or std::upper_bound. If the target number might be duplicated in the collection, lower_bound gives the location of the first, and upper_bound gives the location of the last of those duplicates. Since it doesn't appear that duplicates would change the results you're producing, you might prefer to just remove the duplicates with std::unique immediately after sorting (but unless you really expect duplicates in the inputs, this may waste more time than it saves).

If you also sort the nbQ numbers before searching for them, you can optimize a little more by reducing the bounds within which you do successive binary searches. Given the relatively small amount of data (20000 numbers, 20000 queries) this probably won't make a huge difference, but still might be fairly noticeable.

Other than that, you could make considerably better use of the standard algorithms and containers than you do right now. For example:

int dens;
std::vector<int> tab(nbBlocs);
for(int i=0; i<nbBlocs; i++){
    cin >> dens;
    tab[i]=dens;
}

Could be turned into:

std::vector<int> tab;
tab.reserve(nbBlocs);
std::copy_n(std::istream_iterator<int>(std::cin), nbBlocs, std::back_inserter(tab));

Looking at:

for(int j = 0; j<nbQ; j++){
    cin >> quest;
int valSup=-1;
int valInf=-1;
int reponse=-1;

[... much more]

The indentation is misleading--based on the indentation, it's not immediately apparent that all the succeeding code is executed inside that loop. This doesn't affect speed in itself, but better formatting could give a better grasp of the importance of speed of the inner loop.

Although it's also unrelated to speed, my final thought would be that your variable names seem open to considerable improvement. A few (e.g., response) aren't too bad, but quite a few (e.g., nbBlocs, nbQ, quest) seem fairly meaningless.

1. Okay, seriously, it brings a large (and unknown) number of symbols into scope. We know some of those names, but the standards reserve a fair number of other classes of names (e.g., anything starting with str) so the number of other possibilities is infinite. Bottom line: it's unnecessary and dangerous.


Control the input of the user according to a sample string and get some info from it

Bug

The regex is flawed, consider this:

>>> print(re.match(pat, 'show me the multiplication table of  from  to '))
>>> <re.Match object; span=(0, 46), match='show me the multiplication table of  from  to '>

That is because [0-9]* matches the digit zero, or more times

I suggest to change them with + which will match the digit 1, or more times

pattern = re.compile('(?i)^show me the multiplication table of \d+ from \d+ to \d+$')

Codestyle

StringController() seems overly complex

Basically the same can be achieved with re.match(pattern, input_string)

It adds a layer of complexity what is not needed, I would just remove the entire class
The extraction of numbers can be greatly simplified

You could use re.findall(r'(\d+)', input) to find the digits in a neater way

And you could map(int, iterable) to convert them to integers

Alternative

INPUT_REGEX = re.compile('(?i)^show me the multiplication table of \d+ from \d+ to \d+$')

def make_table(user_input):
    step, min_range, max_range = map(int, re.findall('(\d+)', user_input))
    return "\n".join(str(step * t) for t in range(min_range, max_range))

def main():
    while True:
        user_input = input('Example string: show me the multiplication table of 8 from 3 to 8\nInput: ')
        print('-'*50)
        if user_input.lower() in ('q', 'quit', 'exit'):
            exit()
        elif re.match(INPUT_REGEX, user_input):
            print(make_table(user_input))
        else:
            print('Use the provided string')

if __name__ == '__main__':
    main()

Note I added a quit, might be nice for your user to let them exit in a clean way ;)


Directory watcher and notifier for files added or removed

This code compares the size of the lists twice:

x = lst2 if len(lst2) > len(lst1) else lst1
y = lst1 if len(lst1) < len(lst2) else lst2

It would be better to do that only once:

longer, shorter = (lst2, lst1) if len(lst2) > len(lst1) else (lst1, lst2)

Notice that I also used better names instead of the meaningless x, y.

With this change the function becomes:

def xor(lst1, lst2):
    """ returns a tuple of items of item not in either of lists
    """
    longer, shorter = (lst2, lst1) if len(lst2) > len(lst1) else (lst1, lst2)
    return tuple(item for item in longer if item not in shorter)

It might also help to turn the shorter list into a set for faster lookups:

    longer, shorter = (lst2, set(lst1)) if len(lst2) > len(lst1) else (lst1, set(lst2))

However, at this point, I realize the method doesn't do what the comment says it does:
it returns the items of the longer list that are not in the shorter list,
which is not the same as items in neither lists (can be fewer than that).

It would be better to move "/Users/ppl/Desktop/testFolder" into a constant at the top of the file, rather than buried inside a class constructor.

It's recommended to follow PEP8, the Python coding style guide.

For example there are several coding style violations here:

def main():
    app         = QtGui.QApplication(sys.argv)
    window      = MyMainWindow()
    window.show()
    window.raise_()

    return sys.exit(app.exec_())
if __name__ == '__main__':
  main()

The recommended writing style would be:

def main():
    app = QtGui.QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    window.raise_()

    return sys.exit(app.exec_())

if __name__ == '__main__':
    main()


Disclaimer: I'm a C# developer and I haven't written Java in ages.

First of all I'd move this to a separate method, with (String selection, String[] selectionArgs) as parameters:

cursor = cupboard().withDatabase(sqLiteDatabase).query(Cattle.class)
        .withSelection(selection, selectionArgs)
        .getCursor();

if(cursor.getCount() < 1){
    Toast.makeText(getContext(), "Sorry, No Cattle with those details!", Toast.LENGTH_LONG).show();

You can now call that method in each if instead of copy-pasting the same code over and over again and only changing a small part.

But I'm mostly baffled by the convoluted logic WRT those ifs and the resulting selection and selectionArgs. Are you sure you didn't mean to construct something like this (pseudo-code):

var selectionOptions = new Dictionary<String, String>();

if(breed != "" && breed != "Breed")
{
   selectionOptions.Add("breed LIKE ?", breed);
}

if(sex != "" && sex != "Sex")
{
   selectionOptions.Add("sex LIKE ?", sex);
}

// same for tag and name

// now construct the selection
var selection = string.Join(" AND ", selectionOptions.Keys);

// pass the selection and its arguments to the method I mentioned above
ThatMethodMentionedAbove(selection, selectionOptions.Values);

The logic being:

Look at each of the four possible parameters
Only add a parameter to the query if it has a value and its value is not its own name

That would make sense to me, whereas this kind of logic:

if (tag == "" && name == "" && breed == "Breed"){
    // snip
    .withSelection("sex LIKE ?", sex)

... just looks... odd. And indeed, very un-maintainable.


Formatting uptime as a human-friendly time interval

Bearing in mind that a linter can only look at how the code is written and not at what it's actually doing, switch statements (or the equivalent case as with Ruby) that don't do much are completely fine.

A switch that tests many conditions is bound to be long-ish, there's not much you can do there. Every one of the warnings you get is a direct consequence of the fact that you're testing 8 values.

I would say this is one prime example of a situation in which you just don't waste your time in an attempt to make the linter happy. Extracting methods is going to clutter things up and look dumb.

The only viable option that I can think of right now is sticking those ranges along with their readable description in some kind of hash, and retrieving the value from there. But it's a compromise, really: if this method gets called often, you could be instantiating yet another object at each call.

I say you just ignore what the linter says in situations like this, or adjust its default settings to make it less bitchy.

Your method is fine, the intent is very clear to me, and it's not doing anything complicated. Don't get all caught up in an attempt to please a tool that doesn't understand your code to begin with.


All in all, a basic review of your question shows that you are creating objects numerous times, when they do not need to be. Other things are pointed out in comments.

const choices = ['rock', 'paper', 'scissors'],
      capitalize = word => word.charAt(0).toUpperCase() + word.slice(1),
      // Should these be made into 1 function, that takes another argument, 'condition', which is 'Win' or 'Lose'?
      winStatement = (winner, loser) => `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`,
      loseStatement = (winner, loser) => `You Lose! ${capitalize(winner)} beats ${capitalize(loser)},
      winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};

function computerPlay() {
    return choices[Math.floor(Math.random() * choices.length)];
}

function playRound(playerSelection, computerSelection) {
    playerSelection = playerSelection.toLowerCase();

    // Also, Consecutive if statements that all return need not be else-if.
    if(playerSelection === computerSelection) {
        return "Oh! It's a tie";
    }
    if(playerSelection === winningChoice[computerSelection]) {
        return winStatement(playerSelection, computerSelection);
    }
    return loseStatement(computerSelection, playerSelection);
}

// Should be improved upon? Actually take input?
const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));


Actually I'm surprised there isn't a $q.some or so to do exactly that.

I think this is a good solution for the problem, though putting it in a separate function would be nice.  (Can't think of any reasons to not do it like this either.)


A basic pure Python hash map using a tree

I wanted to know how your program worked and so I removed all the module level checking code and used the following:

table = []
def check(key, value):
    global table
    table = insert(key, value, table)
    print table
    print get(key, table)

check(5, 'value')
check('key', 'value2')
check('key', 'value3')
check('key2', 'value4')

This gave me a somewhat strange output.

[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [5, ['value']], [], [], [], [], []]
['value']
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [[], [], [], [], [], [], ['key', ['value2']], [], [], [], [], [], [], [], [], [], [], [], [], [5, ['value']], [], [], []], [], [], [], [], []]
['value2']
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [[], [], [], [], [], [], ['key', ['value2', 'value3']], [], [], [], [], [], [], [], [], [], [], [], [], [5, ['value']], [], [], []], [], [], [], [], []]
['value2', 'value3']
[[], [], [], [], [], [], [], [], ['key2', ['value4']], [], [], [], [], [], [], [], [], [[], [], [], [], [], [], ['key', ['value2', 'value3']], [], [], [], [], [], [], [], [], [], [], [], [], [5, ['value']], [], [], []], [], [], [], [], []]
['value4']

The keys 5 and key collide and so the results should be a list of two items, but you spam it with lots of items.
This can be due to two things:

A bad algorithm that spams list.append
Your algorithm being a 'hash-tree' not hash-table.

From the looks of your algorithm it's probably the latter.
This is as you do:

entry = table
for i, char in enumerate(key_hash):
    ordinal = ord(char) - 48
    entry = entry[ordinal]

This is fine and all, but then it's not a hash-table.

A hash-table should be a 2D-table of items. Where items here is just a [key, value] pair.

If you change your code to a hash-table then it'd be so much more simpler.
The algorithm is hash key, modulo it, append to table:

def add(key, value, table):
    hashed_key = hash(key) % len(table)
    table[hased_key].append([key, value])

This should bring up some concerns:

What if the size of the table changes?
What if the key is already in the table?
What if the key is already in the table and the size of the table changes?

These can be resolved, (1) by using a class, (2) by checking the list.

class Dict(object):
    def __init__(self, size=8192):
        self._table = [[] for _ in xrange(size)]
        self._mod = size

    def _get_item_index(self, key):
        hashed_key = hash(key) % self._mod
        list_ = self._table[hashed_key]
        return list_, next((i for i in xrange(len(list_)) if list_[i][0] == key), None)

This then makes insert and get easy to make.

def insert(self, key, value):
    list_, index = self._get_item_index(key)
    if index is None:
        list_.append([key, [value]])
    else:
        list_[index][1].append(value)

def get(self, key):
    list_, index = self._get_item_index(key)
    if index is None:
        raise KeyError(key)
    return list_[index][1]

Your method seems alright, it's hard to read, and is way more complex then it needs to be, so I'd recommend at least making a _get_item_index if you do carry on with your hash tree.
But it seems faster than my one.

For in-depth review of the code:

If I were to make _get_item then I'd look at the get function first.
I don't think that you should have pop in that function, and so I'll remove it.
This leaves you with:

def get(key, table):
    key_hash = hashlib.sha1(str(key)).hexdigest().upper()
    entry = table
    for i, char in enumerate(key_hash):
        ordinal = ord(char) - 48
        entry = entry[ordinal]
        entry_len = len(entry)
        if entry_len is 0:
            raise KeyError(key)
        elif entry_len is 2:
            return entry[1]
    raise KeyError(key)

From this we can see the basic looping structure. I'd first merge ordinal with entry, to get entry = entry[ord(char) - 48].
You shouldn't use 1 is 1 instead use 1 == 1, it makes more sense as 1 == 1.0 is true where 1 is 1.0 is not.
As we need to get the item, entry, even if it's not there (we'll be using this for update too), we should change the ifs to just return the entry.
Finally you should notice that entry_len == 0 is the same as not entry.
Merging these all together gets us:

def _get_item(key, table):
    key_hash = hashlib.sha1(str(key)).hexdigest().upper()
    entry = table
    for i, char in enumerate(key_hash):
        entry = entry[ord(char) - 48]
        if not entry:
            return entry
        elif len(entry) == 2:
            return entry
    else:
        raise KeyError(key)

To use it is simple:

def get(key, table):
    item = _get_item(key)
    if item and item[0] == key:
        return item[1]
    raise KeyError(key)

We still need to get _get_item working for update however.

You should be able to see that the code is roughly the same for all except elif entry_len is 2:.
To help with this we should break out of the loop so that we're in a 'separate environment'.
To make things simpler I'd also return if key == entry[0].
And so:

elif len(entry) == 2:
    if key == entry[0]:
        return entry
    break

You should notice that we don't want the new code to run if we are using the other version of this function.
To do this we can pass a flag that returns the entry after exiting the for.

if extend:
    return entry

Finally we're left with:

extant_key, extant_values = entry[0], entry[1]
del entry[:]
#entry = []
extant_hash = get_hash(extant_key)
for i in xrange(i + 1, len(key_hash)):
    char, extant_char = key_hash[i], extant_hash[i]
    if char == extant_char:
        entry.extend(alphabet())
        ordinal = ord(char) - 48
        entry = entry[ordinal]
        #entry = []
    else: break
if char != extant_char:
    entry.extend(alphabet())
    char_ord = ord(char) - 48
    entry[char_ord].extend((key, [value]))
    extant_ord = ord(extant_char) - 48
    entry[extant_ord].extend((extant_key, extant_values))
    #entry has empty lists except 2
    break
else: pass
    #hash collision, to be continued

This leads to the following changes:

Using both extant_key and extant_value is more verbose than I like, and would just use extant with the slice item[0:2].
Use izip rather than xrange(i + 1, len(key_hash)).
This is quite simple add from itertools import izip at the top, and then use:

for char, extant_char in izip(key_hash[i + 1:], extant_hash[i + 1:]):

Use item[ord(...) - 48] rather than setting intermarry variables.
Raise an error if you don't break out the for loop.
Change the if to char != extant_char and then break.
This adds a little bit of readability, and prevents large amounts of indents.
Finally return entry[ord(char) - 48].

This should lead to something like:

extant = entry[0:2]
del entry[:]
extant_hash = get_hash(extant[0])
for char, extant_char in izip(key_hash[i + 1:], extant_hash[i + 1:]):
    if char != extant_char:
        break
    entry.extend(alphabet())
    entry = entry[ord(char) - 48]
else:
    raise KeyError(key)
entry.extend(alphabet())
entry[ord(extant_char) - 48].extend(extant)
return entry[ord(char) - 48]

Finally I should note that the two KeyErrors raised in this function, aren't really errors with the key, it's actually that there is actually a sha1 collision.
And so I'd change the errors to custom errors.

What is the likelihood of these? Not very likely but my favorite programmers.SE answer makes me think that ruling this out is not a good idea.


Build a MySQL upsert query to insert/update multiple records in Python

Should I be quoting or escaping some strings/fields?

Yes, you should definitely escape table and field names. Currently this is trivial to exploit. It should not be possible to produce invalid SQL with any input parameters. If you get to that point there might not be any exploits left.

  The existing solutions for upsert and batch-insert seem more generalized, and therefore slower, than implementing a MySQL-specific solution.

Which options are these? And have you tested them? I would be very surprised if there are no options available which would save you much more time overall than rolling your own.

  Also, I'm clearly in love with str.format()—is this the best way of handling string composition?

str.format() is very nice for relatively simple format strings, but in this code it's hard to see what the actual result will be for some given input. I would pull out variables for the various .join()ed strings, but even then it's a big string to compose.

Some general things:

Use more descriptive variable names. database = MySQLdb.connect(… and cursor = database.cursor() are much more descriptive.
Use transactions by initialising your cursors using with database.cursor() as cursor:
You'll want to run your code through pep8 to improve readability.


Instead of trying to create your own versions, you could try doing it without.

Not wanting to use ASCII conversions makes sense since that would be inefficient.  using a string to get the char value from a specific integer value, works well.  However, to go the other way a map would work better, and ignores how the native mapping works.

map<char,int> values =
{
    {'0',0},
    {'1',1},
    {'2',2},
    {'3',3},
    {'4',4},
    {'5',5},
    {'6',6},
    {'7',7},
    {'8',8},
    {'9',9},
    {'A',10},
    {'B',11},
    {'C',12},
    {'D',13},
    {'E',14},
    {'F',15},
    {'G',16},
    {'H',17},
    {'I',18},
    {'J',19},
    {'K',20},
    {'L',21},
    {'M',22},
    {'N',23},
    {'O',24},
    {'P',25},
    {'Q',26},
    {'R',27},
    {'S',28},
    {'T',29},
    {'U',30},
    {'V',31},
    {'W',32},
    {'X',33},
    {'Y',34},
    {'Z',35}
};

Using a power function  reiterates over the same loop over and over again each time you call it.  It would make more sense to start at the end of the string and increase a multiplier in each iteration of the existing loop.  Also when working with base 10 it is alot simpler to keep the values as integers:

int ToBase10(string value, int base)
{
    int decValue = 0;
    int baseMult = 1;
    for (int i = value.size()-1; i > -1; i--)
    {
        decValue += values[value[i]] * baseMult;
        baseMult *= base;
    }
    return decValue;
}

Since decimal has other meanings, it would be clearer to say base10 instead.

Lastly wrapping your functions up in a static class allows you to expose only what needs to exposed.  Also this keeps the validation in only one place:

#include <map>
using std::map;
using std::string;
class BaseConverter
{
    static map<char, int> values;
    static bool GoodValue(string& value, int base);
    static string FromBase10(int value, int base);
    static int ToBase10(string value, int base);
public:
    static string Converter(string value, int fromBase, int toBase);
    static string Converter(int decValue, int base);
};

map<char,int> BaseConverter::values =
{
    {'0',0},
    {'1',1},
    {'2',2},
    {'3',3},
    {'4',4},
    {'5',5},
    {'6',6},
    {'7',7},
    {'8',8},
    {'9',9},
    {'A',10},
    {'B',11},
    {'C',12},
    {'D',13},
    {'E',14},
    {'F',15},
    {'G',16},
    {'H',17},
    {'I',18},
    {'J',19},
    {'K',20},
    {'L',21},
    {'M',22},
    {'N',23},
    {'O',24},
    {'P',25},
    {'Q',26},
    {'R',27},
    {'S',28},
    {'T',29},
    {'U',30},
    {'V',31},
    {'W',32},
    {'X',33},
    {'Y',34},
    {'Z',35}
};

string BaseConverter::Converter(string value, int fromBase, int toBase)
{
    if(!GoodValue(value,fromBase))
    {
        return "Improper Value";
    }
    if (fromBase == toBase)
    {
        return value;
    }
    return FromBase10(ToBase10(value,fromBase),toBase);
}
string BaseConverter::Converter(int decValue, int base)
{
    return FromBase10(decValue,base);
}

bool BaseConverter::GoodValue(string& value, int base)
{
    for(int i = 0; i < value.length();i++)
    {
        value[i] = toupper(value[i]);
        if (values[value[i]]>= base)
        {
            return false;
        }
    }
    return true;
}

string BaseConverter::FromBase10(int value, int base)
{
    const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string baseValue = "";
    while (value > 0)
    {
        baseValue.insert(baseValue.begin(), chars[value % base]);
        value /= base;
    }
    return baseValue;
}

int BaseConverter::ToBase10(string value, int base)
{
    int decValue = 0;
    int baseMult = 1;
    for (int i = value.size()-1; i > -1; i--)
    {
        decValue += values[value[i]] * baseMult;
        baseMult *= base;
    }
    return decValue;
}

Notice the simplicity of only having to call one wrapper function(string test = BaseConverter::Converter("291", 10, 16);)


JavaScript function for the get the formatted date of tomorrow

With Intl.DateTimeFormat you can also format the date elements to 2 and 4 digits. You code would then look something like this:
const getDateStringForTomorrow = () => {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  const day   = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(tomorrow);
  const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(tomorrow);
  const year  = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(tomorrow);
  return day + '.' + month + '.' + year;

};

console.log(getDateStringForTomorrow());

Another variant uses the European date format to get the order of the elements correctly and then only replaces dashes by dots:
const getDateStringForTomorrow = () => {
  const tomorrowDate = new Date();
  tomorrowDate.setDate(tomorrowDate.getDate() + 1);
  const tomorrowStr = new Intl.DateTimeFormat('uk', { day: '2-digit',  month: '2-digit', year: 'numeric' }).format(tomorrow);
  return tomorrowStr.replaceAll('-','.');

};

console.log(getDateStringForTomorrow());

The advantage of using Intl.DateTimeFormat() is that it writes out very clearly what you want.


Building a summary string from a flags enum

Am I going about this in the most efficient way?

If you're worried about efficiency, then Enum.HasFlag is known to be fairly slow.

Instead, I would use a very simple helper method:

private static bool HasFlag(FileAttributes value, FileAttributes flag)
    => value & flag != 0;

Though if you're doing that, you might as well expand the helper function to give you the flag character:

private static string GetAttributeCharacter(
    FileAttributes value, FileAttributes flag, string character)
    => (value & flag != 0) ? character : string.Empty;

I'm on the fence whether the helper method should access _attribs directly or whether it should get its value in a parameter. On one hand, reading the field over and over is likely going to be slower. On the other hand, that's the kind of microoptimization that does not matter in the vast majority of cases and accessing it directly would remove quite a lot of duplicated code.

Using string.Concat(…) instead of string.Join(string.Empty, …) is simpler and should be faster.

If you're on C# 6.0, you can avoid some code repetition by using using static System.IO.FileAttributes;.

If it's clear what type a variable is, like your fatt, most code styles accept using var for its type. Also, I think that abbreviations like fatt are generally not worth it: they save you some type, but make understanding the code later harder.

Also, I don't understand why is the cast to FileAttributes necessary, but I'm going to assume there is a good reason for it.

Put together:

private string GetAttributeCharacter(FileAttributes flag, string character)
    => ((FileAttributes)_attribs & flag != 0) ? character : string.Empty;

public string AttributeSummary
{
    get
    {
        return string.Concat(
            GetAttributeCharacter(ReadOnly,          "R"),
            GetAttributeCharacter(Hidden,            "H"),
            GetAttributeCharacter(System,            "S"),
            GetAttributeCharacter(Directory,         "D"),
            GetAttributeCharacter(Archive,           "A"),
            GetAttributeCharacter(Normal,            "N"),
            GetAttributeCharacter(Temporary,         "T"),
            GetAttributeCharacter(SparseFile,        "P"),
            GetAttributeCharacter(ReparsePoint,      "L"),
            GetAttributeCharacter(Compressed,        "C"),
            GetAttributeCharacter(Offline,           "O"),
            GetAttributeCharacter(NotContentIndexed, "I"),
            GetAttributeCharacter(Encrypted,         "E"),
            GetAttributeCharacter(IntegrityStream,   "V"),
            GetAttributeCharacter(NoScrubData,       "X"));
    }
}


Fastest way to get a value from csv file using java 7

Spaces

Your use of spaces could stand improvement.  You should have one space after every comma in argument list, and around binary operators.  It is also customary to have a space between a closing parenthesis and an opening brace.

Names

Use descriptive names!

Is r1 a method name, or a BufferedReader?  Why are these named the same, anyway?

What is input?  It is a String, that much is clear, but what is it used for?  filename would be so much more descriptive than input.

Try-with-resources

If an IOException happens, is FileInputStream closed, or does it bypass the r1.close() statement?

Java 7 introduced the "try-with-resources" construct, which ensures resources are properly closed, even in the event of exceptions, and even if exceptions happen during the exception handling.

try (FileInputStream fis = new FileInputStream(new File(input)),
         InputStreamReader isr = new InputStreamReader(fir, "UTF-8"),
         BufferedReader br = new BufferedReader(isr)) {

    // use br here - see below

    // br, isr, and fis are automatically closed here, at the end of the try block.
} catch (IOException e) {
    e.printStackTrace();
}

Efficiency

You are doing a lot of unnecessary work, wasting time, to extract a single value from the file.

If you want the value from the first line, you still read in all of the lines
You split every line into columns, even when you don't need a value from that line.
You store all of the lines of data, split into columns, as an ArrayList
You store a second copy of of all of the lines of data, as a String[][]

In place of the // use br here - see below line, you could do the following:

Read in lines without storing them, until you reach the i-th row.
Split the i-th row into columns
Return the j-th value

Ie)

for(int row = 0;  row < i;  row++) {
    br.readLine();                    // Note: value is not saved
}

String line = br.readLine();
String[] columns = line.split(",");
return columns[j];                    // Resources are automatically closed!

Remove the original declaration of result, row, and lines.

  What about bufferSize, should I never use it?

It was an oversight on my part when writing the try-with-resources replacement, but in general, no.  The JVM will pick a buffer size that is optimal for the OS.

If you did want to specify a buffer size, 10KiB seems too arbitrary.  It should be related to (a multiple of) the size of the data being read, in this case, the length of the lines in the csv file.  The larger the value, the lower the odds that readline() will have to do string concatenation because the part of the line is in one buffer & part of the line is in another.  However, the larger the value, the higher the odds that too much data will be read (you want to stop at exactly the right line, remember?), memory pressure will increase causing other inefficiencies.  If you do try tweaking the value, profile, profile, profile (... and then go back to the default).


Return true if a portion of one string can be rearranged to create the other string

12 seconds
is forever for a CPU. However your solutions is so complex, 12 seconds is likely it timing out on a string that is only a few K long.
These code sites also like to throw curve balls, passing arguments that have very quick solutions if you check for them, but if you don't will take so long it will time you out.
Also know that these sites run distributed virtual machines on which they test code, some (all that I tested) time how long it takes to get a result not how long your code takes to run. If its busy that time will include how long it takes to locate CPU/Memory resource (VM), setup context (Javascript runtime), and then execute your code. So times vary and should never be used as an indication of performance.
Performant and Complexity
The first step to fast solutions is always write performant code,
Basic performant optimisations

Locate opportunities to exit early. In this case, is the first string is shorter than the second then you know the result must be false.

Locate lines of code that are repeated in iteration that can be done once. In this case you set result to true each time you find a match. You need only do it once by assigning true to result when you declare it.

Avoid redundancy. Redundant lines of code take time to execute. In this case result is not needed as you can return the result directly from within the statement found===null, removing the need for break, and defining result.

Develop a good Understanding of available language features and stay up to date. MDN has a good Javascript reference. Knowing this reference in your head will makes your code faster, to know it in your head means you must continuously be studying the reference as JavaScript is always changing.
String.match is not the only way to test for a character. Also it can return an array which is less performant than a bool such as RegExp.test, and String.includes or a Number such as String.indexOf.
Once a year read the Javascript Spec (current ECMAScript2019) Its long and dry, not an easy read for beginners (or 40+ year vets) , so read it again, and again. This will not only reenforce your internal mind javascript reference but give you an understanding of how javascript does what it does. (Help you understand JS complexity. See below)
Test your understanding. Is str1 === str2 faster than str1.length === str2.length ? If you dont know write some code to find out.

A more performant solution
From that you can get a good improvement in overall performance. An example follows
function scramble(str1,str2) {
    var i;
    if (str1.length >= str2.length) {
        if (str1 === str2) { return true }
        for (i = 0; i < str2.length; i++) {
            const str = str1.replace(str2[i]);
            if (str.length === str1.length) { return false }
            str1 = str;
        }
        return true;
    }
    return false;
}

That may pass the time limit but as the size of the strings grows the improvement in performance reduces.
For 2 char strings this a twice as fast. When str1 is shorter than str2 this is a above umteenQuadBillion times faster. If str1 is longer or equal len to str2 then for a 4K string it will likely timeout, taking only a few ms shorter to solve.

Complexity
In computer science there is a difference between performance and complexity. The above code has better performance and hence will always be a little quicker, however it has the same complexity and thus not going to help you.
The metric n
We measure an algorithm's complexity in terms of some metric. In this case the metric can be the mean size of both strings. We call it n and use that to create a formula that counts the number operations per n needed to complete the task.
For example count A's in a string
// Note len is string len
count = 0
for(i = 0; i < len; i++){
    if(str[i] === "A") {
        count ++
    }

}

2 operations to set count and start the loop.

1 op for the loop.

1 op for the test.

if there is an "A" 1 op to count.
We can say that the complexity has a worst (all A's) case of 2 + 3 * n complexity and a best case (No A's) of 2 + 2 * n

The difference between best a worst case can be huge, generally we define what the complexity is for (worst, mean, or best case). Without that we assume the complexity is the worst case
Big O notation.
Formalized we call the expression of complexity big O notation and you will see it as a math function, sometimes O(2 + 3 * n) but most often just the n or a number O(n), O(n2) or O(1).
Complexity grows quickly
Lets up the complexity and count the number of chars in str1 that exist in str2
count = 0
for(i = 0; i < len1; i++){
    for(j = 0; j < len2; j++){
        if(str1[i] === str2[j]) {
            count ++
        }
    }
}

Now n is the mean string len and there are

2 ops to get into the first loop,
for each n there is

1 op to loop and another to enter the inner loop. thus 2 * n.
then for each inner loop

1 to loop, and 2 to count.

The complexity is O(2 + 2 * n + 3 * n * n)
Note that the  there is a n * n or we can express it as n^2 or n2 thus O(2 + 2n + 3n2)
The highest power
The function inside the () is called a polynomial.
There is a property of polynomials that allow for simplification.
As the value of n grows the size of the term that has the highest power n2 gets so large that the other terms (2 + 2n + 3 * ) become insignificant.
With this in mind Big O ignore all but the highest power. So for the above the complexity is not O(2 + 2n + 3n2) but  O(n2)
Javascript complexity.
As part of understanding javascript you need to know the complexity of the many javascript functions and operators.
Some examples
if(a === b)  // if numbers O(1)
if(a === b)  // if strings O(n) where n is string len (it may be a little lower (O(nlogn)
if(a.includes(b)) // if a is array of numbers b is a number O(n) n is size of array
if(a.includes(b)) // if a is array of string b is a string the worst case O(n**2)

So a single JS line can not just be counted as a single operations, each line can have vastly different complexity
So looking at your code the outer loop is O(n) but inside we have str1.match and str1.replace both of which are O(n). So overall its O(n2). The same for the more performant version I wrote. The str1.replace is O(n) thus the solution is O(n2)
Optimise complexity target the highest big O power
So if we can reduce the size of the highest power in a solution, even if that means more code we can get huge improvements in complexity.
One solution is to go over the first string and count the number of times each letter occurs, storing the count in an array, one item for each possible character. Then go over the second array and for each subtract 1 from the counts. If any of the counts are negative we know that the first string is missing a value that is in the second.
function scramble(str1,str2) {
    const buf = new Uint8Array(256);
    var i = 0;
    if (str1.length >= str2.length) {
        if (str1 === str2) { return true }
        while(i < str1.length) {
            buf[str1.charCodeAt(i++)] ++;
        }
        i = 0;
        while(i < str2.length) {
            const idx = str2.charCodeAt(i++);
            if(buf[idx] === 0) { return false }
            buf[idx] --;
        }
        return true;
    }
    return false;
}

If we write out the full complexity its 256 + 3 + 2n + 1 + 4n + 1 or 261 + 6n the 256 is to create and fill the array with zeros. If the strings are unicode it would be 65536 + 5 + 5n
But only the highest power matters so the above function is O(n)
Now if the strings are the same size and the mean length is 4000 this solution should be around 4000 times faster.
Caveats
There are however some caveats for the above solution
The array holding the counts must be able to count all the characters.
To ensure the function will work use an array of 32bit unsigned ints which will handle strings upto 4Gb is size. If the function errors the strings may be unicode and thus you will need to use a larger array 65536 items long.
The O(n) solution.
function scramble(str1, str2) {
    const buf = new Uint32Array(256);  // For unicode array size is 65536
    var i = 0;
    if (str1.length >= str2.length) {
        if (str1 === str2) { return true }
        while (i < str1.length) {
            buf[str1.charCodeAt(i++)] ++;
        }
        i = 0;
        while (i < str2.length) {
            const idx = str2.charCodeAt(i++);
            if (buf[idx] === 0) { return false }
            buf[idx] --;
        }
        return true;
    }
    return false;
}


I think your approach is reasonable if you don't want (or can't) have the whole collection in memory. One minor change: if you don't need the count, just whether the collection was empty or not, use a simple bool:

bool any = false;

foreach(var e in expensiveObjects)
{
    any = true;

    //other processing
}

if (any)
{
    //do something
}


There seem to be some inconsistencies here. What is s? I guess this is the stack? Also declaring a class Main is a little strange. You certainly want to have a main method, but a Main class?

Also I'd suggest you not use raw collections e.g. replace

Queue queue = new LinkedList();

with

Queue<Node> queue = new LinkedList<Node>();

You may like to consider implementing DFS recursively so that you don't have to explicitly use a stack, although that's a matter of taste. Also, where is getUnvisitedChildNode() defined?  Where are the edges of the graph actually stored? This could be e.g. an adjacency list carried around by each node, or perhaps in another object, but it should be somewhere.


Finding palindromic numbers most efficiently

Here, you first check if $x is palindrome, but then you will only print it if $x > $lm:

if ($x eq reverse $x) {
    print "$x is $a * $b" if ($x > $lm);
    last if ($n > 3); # show them all for small numbers
}

It would be more efficient to do the other way around, checking $x > $lm first:

if ($x > $lm) {
    if ($x eq reverse $x) {
        print "$x is $a * $b";
        last if ($n > 3); # show them all for small numbers
    }
}

With \$n = 3\$, this makes a big difference: it saves reversing $x 23602 times.

I also tried rewriting the reverse operation,
somewhat inspired by the the duck's comment:
instead of comparing an entire string with its reverse,
it should be more efficient to compare its first half with the reverse of its second half:

sub is_palindrome {
    my ($word) = (@_);
    my $l = length($word);
    foreach my $i (0 .. $l / 2) {
        if (substr($word, $i, 1) ne substr($word, $l - $i - 1, 1)) {
            return;
        }
    }
    return 1;
}

Although this function does only half of the comparisons as in $x eq reverse $x,
at least as interpreted code, this cannot compete with the speed of the compiled reverse function. Using this function the script runs much slower, unfortunately.


Updating one model field based on the associated model's field

A couple of things:

I wouldn't do this in the after_commit handler. If you do it before the commit then an error here would cause the whole transaction to fail whereas doing it after committing could potentially result in an inconsistent database.
You also want to update the library when a destroy happens which you currently doing. Even though it looks like you are using soft deletion I would consider it a good idea to cover all your bases.
books.available.exists? usually performs a little better than books.available.present? in this situation. (Because I can almost guarantee from experience that you are going to completely destroy bad data manually for some reason)
If you are need to optimize for performance you might want to check if destroyed? || deleted_changed? before running the query.
Additionally you could be more intelligent and factor in the value of the deleted flag on the current record. i.e. if it is false then you can make the library active without running a second query.


So the idea in this new approach is to write two expressions:

one that extracts the next expresstion:
(take-while #(not= "#ENTRY_END" %)
                            (rest (drop-while #(not= "#ENTRY_START" %) data)))
one that extracts everything after the next expression
(rest (drop-while #(not= "#ENTRY_END" %)
                        (rest (drop-while #(not= "#ENTRY_START" %) data))))

and then wrap them up into a lazy sequence:

first lets expand the test data to include some additional edge cases:

user> (def test-data [
       "Header line"
       "#ENTRY_START"
       "entry line 1 "
       "entry line 2"
       "#ENTRY_END"
       "not part of an entry"
       "also not part of an entry"
       "#ENTRY_START"
       "entry line 1 "
       "entry line 2"
       "#ENTRY_END"
       "footer1"
       "footer2"])

then wrap our two expressions into a function:

user> (defn entry-seq [data]
        (let [f (take-while #(not= "#ENTRY_END" %)
                            (rest (drop-while #(not= "#ENTRY_START" %) data)))
              r (rest (drop-while #(not= "#ENTRY_END" %)
                            (rest (drop-while #(not= "#ENTRY_START" %) data))))]
      (when (not-empty f) (lazy-seq (cons f (entry-seq r))))))
#'user/entry-seq

and we test it:

user> (take 4  (entry-seq test-data))
(("entry line 1 " "entry line 2") ("entry line 1 " "entry line 2"))


I think if you created a projection and pass that in the class would be easier to use and more readable for anyone coming after you.

Instead of the IEnumerable<Func<T, object>> I would change it to be Func<T, K> projection and lose the IEnumerable.  Which would need to make the class now take two generics

public class AutoEqualityComparer<T, K> : IEqualityComparer<T>
{
    private readonly Func<T, K> _projection;

    public AutoEqualityComparer(Func<T, K> projection)
    {
        _projection = projection;
    }

Since we now have the strong type of class in equals we can use the EqualityComparer class for both the Equals and GetHashCode methods.

    public virtual bool Equals(T x, T y)
    {
        if (x == null && y == null)
        {
            return true;
        }
        if (x == null)
        {
            return false;
        }
        if (y == null)
        {
            return false;
        }

        var xData = _projection(x);
        var yData = _projection(y);

        return EqualityComparer<K>.Default.Equals(xData, yData);
    }

    public virtual int GetHashCode(T obj)
    {
        if (obj == null)
        {
            return 0;
        }

        var objData = _projection(obj);

        return EqualityComparer<K>.Default.GetHashCode(objData);
    }

I would create a class to create the AutoEqualityComparer to make it easier to use

public class EqualityProjectionComparer<T>
{
    public static AutoEqualityComparer<T, K> Create<K>(Func<T, K> projection)
    {
        return new AutoEqualityComparer<T, K>(projection);
    }
}

Now with the extension method you can create Tuples or anonymous classes for the IEqualityComparer

Example could be

var comparer = EqualityProjectionComparer<ArgumentException>.Create(arg => new
{
    arg.ParamName,
    arg.Message
});

Now to me this is more clear on what we are comparing and anonymous type compare the properties to see if they are equal and not reference.


Some things I would look for on an interview question such as this:

Is the coder handling bad input cases?  This is something you are not really doing now. What if non-integer values are passed for parameters?  What if values are not > 0?  Oftentimes in interview scenarios like this, I at least want to see the coder acknowledge (even if with a "todo" kind of comment) that validations need to take place.  If I was the one writing this code in the interview, I would probably ask the interviewer if they want you to write the validation code or just get to the heart of the algorithm.  Regardless of their answer, at least they understand that you acknowledge these edge cases.  If you are doing this as an off-line coding test for an interview than I would for sure add in the validation so they don't think you missed this.
I would personally like to see more exact and meaningful comparisons rather than just vaguely truthy/falsey comparison.

Example:

// instead of
if(!($i % $fizz)){
// something like this
if($i % $fizz === 0){

// instead of
if(!$output[$i]){
// do this
if(empty($output[$i])) {

To me, the suggested replacement examples are more clear in intent.  Also, I would be worried about developers that make a habit of loose or unclear comparisons as this could be indicative of someone who is writing error-prone code.

The comment //If I ignore warnings, this isn't needed. is really bothersome.  Why would you ignore warnings?  I think your initialization of this array key to an empty string makes sense, specifically in light of you wanting to check it after the moduli checks to see if it is still an empty string.  Don't apologize for writing code that behaves properly.


Your code does represent the tree that you drew.  However, the code doesn't implement the logic for determining where to place nodes within a binary search tree; instead, you hard-coded that logic in your main() function.  A useful implementation of Binarytreenode would let you write something like

BinaryTree t = new BinaryTree();
t.add(3);
t.add(1);
t.add(4);
t.add(2);
t.add(5);

… to produce the same tree structure.

You want to design the code as a class that maintains the tree in a self-consistent state, supporting operations such as .add(int value) and .find(int value).  The member fields left, right, and data should generally not be have public access, which would let other code modify the tree in an invalid way.  It could be acceptable, however, to let data remain public if you also mark it as final.


Provided I understand the intent of this code, I think the following may be cleaner:

public static class DownloadUtilities
{
    private const int RETRY_COUNT = 4;

    public static void DownloadLinks(Dictionary<string, string> files)
    {
        Parallel.ForEach(
            files,
            new ParallelOptions { MaxDegreeOfParallelism = 20 },
            DownloadLink);
    }

    private static void DownloadLink(KeyValuePair<string, string> link, bool retrying = false)
    {
        int retriesRemaining = retrying ? RETRY_COUNT : 1;

        while (retriesRemaining > 0 && !File.Exists(link.Value))
        {
            retriesRemaining -= 1;
            try
            {
                using (var webClient = new WebClient())
                {
                    webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
                    webClient.DownloadFile(new Uri(link.Key), link.Value);
                }
            }
            catch (WebException e)
            {

                if (e.Status != WebExceptionStatus.ProtocolError)
                {
                    throw;
                }

                var response = ex.Response as HttpWebResponse;

                if (response.StatusCode != HttpStatusCode.GatewayTimeout ||
                    response.StatusCode != HttpStatusCode.Forbidden)
                {

                    Program.FailedDownloads.Add(link.Key);
                    Logger.Error($"Failed to download {link.Key}, unhandled response code.");
                    return;
                }

                Logger.Error($"Failed to download {link.Key}, {retriesRemaining} attempts remaining");
                Logger.Error(e.Message);
            }
        }

        if (!File.Exists(link.Value))
        {
            // Lets settle for the fact it can't download, and add it to the failed list.
            Program.FailedDownloads.Add(link.Key);
            Logger.Error($"Failed to download {link.Key}, retries expired.");
        }
    }
}

Here is a summary of the changes and their reasoning:

Replaced addition of string literals and variables with string interpolation, which is generally regarded as better practice.
Making use of the HttpStatusCode enum instead of matching on the response message. This shortens the code and does not require string matching.
Moving the retry logic into the DownloadLink method, rather than extracting into an auxiliary method, since this does not add to the code and complicates behaviour.


You can use the ? operator :

const string TOTAL_COUNT_KEY = "totalCount";
private int TotalCount
{
    get
    {
        return ViewState[TOTAL_COUNT_KEY] != null ? (int)ViewState[TOTAL_COUNT_KEY] : 0;
    }
    set { ViewState[TOTAL_COUNT_KEY] = value; }
}

You can use the null propagation operator ?.

const string TOTAL_COUNT_KEY = "totalCount";
private int TotalCount
{
    get
    {
        return ((int?)ViewState[TOTAL_COUNT_KEY])?.Value ?? 0;
    }
    set { ViewState[TOTAL_COUNT_KEY] = value; }
}

It works this way:

We cast the ViewState[TOTAL_COUNT_KEY] to int?,
This way, it is either null or the value (let's say 42).
Then, the ?. operator will return null if the viewstate property is null, otherwise it'll return the value, 42.
If it is null, the ?? operator will return 0.

I think the ? operator is the clearest, the second one is a little more ninja and might not be appropriate if some member of your team (if you have one) don't fully understand the operators.


When you encounter an ImportError it does not really help you debug the problem if you ignore it, just print the string "Import Error" and then fail at some random later point where that module is actually needed. This will generate a lot more error messages which are less clear than the normal ImportError!

Think about using argparse for your command line arguments. This will not allow you the shenanigans of asking three times for an existing directory name before offering to create it, but you can just add a flag for this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("url", help="The base page where to search for PDF files.")
parser.add_argument("path", help="Where to save the files")
parser.add_argument("--create-directory", "-p", action="store_true", help="Create the directory if it does not exist")
locals().update(vars(parser.parse_args()))
if not os.path.isdir(path):
    if create_directory:
        os.makedirs(path)
    else:
        raise OSError("Directory {} does not exist. Use the '-p' flag to create it".format(path))

I used a trick here to update the locals dictionary, which is just the variables in the local scope. This way the variable url and path exist and have the right value. This magic works only outside of a function, inside you can use:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("url", help="The base page where to search for PDF files.")
parser.add_argument("path", help="Where to save the files")
parser.add_argument("--create-directory", "-p", action="store_true", help="Create the directory if it does not exist")
args = parser.parse_args()
if not os.path.isdir(args.path):
    if create_directory:
        os.makedirs(args.path)
    else:
        raise OSError("Directory {} does not exist. Use the '-p' flag to create it".format(args.path))

Use this argument parser by calling your script like:

$ python pdf_downloader.py http://url.to/pdfs.html path/to/save/files/to/

If you don't enter the two required arguments, an automatically generated usage message will be displayed:

$ python pdf_download.py
usage: pdf_download.py [-h] [-p] url path
pdf_download.py: error: too few arguments

$ python pdf_download.py --help
usage: pdf_download.py [-h] [-p] url path

positional arguments:
  url         The base page where to search for PDF files.
  path        Where to save the files

optional arguments:
  -h, --help              show this help message and exit
  -p, --create-directory  Create the directory if it does not exist

Interlude: Python has an official style guide, PEP8. One of the things it recommends is using a blank after a comma in a(n) (argument-)list, like (1, 2, 3). Another thing is to use lower_case for variable and function names. In all of the below code I fixed this.

Your url manipulation is probably better written as

base_url = '/'.join(url.split('/')[:-1])

And the separating trailing '/' can be added when actually building the full url. I would also put it into a new variable, just to make it clearer what this is.

Even better would be to just use the built-in os.path.dirname, since you already imported os:

base_url = os.path.dirname(url)

For the full url I would use str.format, which makes it a bit easier to read and which is also faster than multiple string additions (even though for one addition it does not matter).

full_url = "{}/{}".format(base_url, link.get('href'))

Instead of separately saving the urls to download and their names, only to zip it first and then iterate over the zipped container, just save the two together right away:

    if full_url.endswith('.pdf'):
        # print fullurl
        name = soup1.select('a')[i].attrs['href']
        urls.append((name, full_url))

pass is not what you think it is. It is a no-op that does nothing (you can use it as placeholder when you need some code block there because of indentation but don't have the code yet). What you mean is continue which directly goes to the next iteration of the loop.

You should never have a bare except clause. This will also catch e.g. CTRL-C if you run into an infinite loop and want to abort it! Use at least except Exception or better, figure out the actual exceptions you code would raise.

Also try to limit the scope of the except to the one call that might fail, if possible. At leas use except Exception as e and print the exception afterwards. Otherwise this information is lost.

Figuring out which urls to download and actually downloading them are two distinct tasks, which are ideal for functions. In addition I would add a main function for the rest and guard it with a if __name__ == "__main__": clause. The latter allows you to do in another script to just do from pdf_download import get_urls and reuse that function.

This results in the final code:

import urllib2
from bs4 import BeautifulSoup
from time import sleep
import os
import sys
import argparse

HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'}

def get_urls(url):
    request = urllib2.Request(url, None, HEADERS)
    soup = BeautifulSoup(urllib2.urlopen(request).read(), "html.parser")
    soup.prettify()

    urls = []
    base_url = os.path.dirname(url)
    for anchor in soup.findAll('a', href=True): #Going inside links
        req = urllib2.Request(anchor['href'], None, HEADERS)
        soup1 = BeautifulSoup(urllib2.urlopen(req).read(), "html.parser")

        for i, link in enumerate(soup1.findAll('a')): # Download all pdf inside each link
            full_url = "{}/{}".format(base_url, link.get('href'))
            if full_url.endswith('.pdf'):
                name = soup1.select('a')[i].attrs['href']
                urls.append((name, full_url))
    return urls

def download(urls, path):
    old_dir = os.getcwd()
    os.chdir(path)
    for name, url in urls:
        if os.path.isfile(name):
            print name, "already exists, skipping..."
            continue
        try:
            request = urllib2.Request(url)
            res = urllib2.urlopen(request).read()
            with open(name, 'wb') as pdf:
                pdf.write(res)
            print "Downloaded", name
        except Exception as e:
            print "Failed to download", name, ", because of", e
    os.chdir(old_dir)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="The base page where to search for PDF files.")
    parser.add_argument("path", help="Where to save the files")
    parser.add_argument("--create-directory", "-p", action="store_true", help="Create the directory if it does not exist")
    args = parser.parse_args()

    if not os.path.isdir(args.path):
        if args.create_directory:
            os.makedirs(args.path)
        else:
            raise OSError("Directory {} does not exist. Use the '-p' flag to create it".format(args.path))

    download(get_urls(args.url), args.path)

if __name__ == "__main__":
    main()

Here I made some more cosmetic changes, like using proper grammar in the notifications ("Downloaded file_name" instead of "file_name Downloaded"), reverting back to the original working directory after downloading all files, removing unnecessary comments and made headers a constant, because it is used in multiple functions now. I also deleted the sleep because it is usually not necessary (unless there is some flood protection on the website, maybe).


First off, I have to say this is a very clean and efficient design.

I'm hoping class IBeltPrinter BeltPrinter() is a typo, because I've never seen C# code like that.

Variable names for local variables (and parameters) should start with a lower case letter.

I would move the setup, labelCommands and tear down into their own methods.  It will keep the PrintLabel method much cleaner

public void PrintLabel(string price, string desc, string barcode)
{
    ExecuteSetup(/*variables*/);
    ExecuteCommands(/*variables*/);
    ExecuteTeardown(/*variables*/);
}

Come to think of it, you could have a base class that has the PrintLabel method, and virtualExecuteSetup,ExecuteCommands, andExecuteTeardown` methods, that have generic printer commands.  You could then extend that base class as required.

I would also consider putting the Factory definitions in an IDictionary.  This will eliminate having a potentially huge switch statement.

private readonly static IDictionary<[whatever], IBeltPrinter> SupportedPrinters = new Dictionary<[whatever], IBeltPrinter>
    {
        {[ZebraQL220], new ZebraQL220Printer()},
        {[ONeal], new ONealPrinter()},
    }

Then your factory call would be

public IBeltPrinter CreatePrinter([whatever] printer)
{
    if (!SupportedPrinters.ContainsKey(printer))
        throw new PrinterNotSupportedException(printer)

    return SupportedPrinters[printer];
}


Get username from full name - PowerShell function

i think the comments cover the why of things, but please feel free to ask if you have any questions. [grin]
#region >>> fake reading in a list of names
#    in real life, use Get-Content
$InStuff = @'
Čedomir Đorđević
JANKOV ZORAN
Stojić Gradimir
Vučićević R Željko
Magda Boškić
'@ -split [System.Environment]::NewLine

<# intended output
cedomir.djordjevic
zoran.jankov
gradimir.stojic
zeljko.vucicevic
magda.boskic [lastname @ end]
#>
#endregion >>> fake reading in a list of names

function Get-UserNameFromFullName
    # your "Get-UsernameFromFullName" name leaves the "N" in "Username" in lowercase
    #    that is not consistent with your use of that in other names of items
    {

    <#
    where is the Comment Based Help?
    #>

    [CmdletBinding ()]
    Param
        (
        [Parameter (
            Position = 0,
            # the following are switches that default to "$False"
            #    that means there is no need to add "= $True"
            #    the simple presense of the attribute flips it to "$True"
            Mandatory,
            ValueFromPipeline,
            # the following requres the pipeline object contain a property named ".FullName"
            #    is that always going to be the case?
            #    if not, then the "ValueFromPipeline" above will handle bare values
            ValueFromPipelineByPropertyName
            )]
            [string]
            $FullName,

        [Parameter (
            Position = 1,
            # making this mandatory makes little sense when a default is supplied
            #Mandatory,
            # does it make any sense to use the following attribute?
            ValueFromPipelineByPropertyName
            )]
            # don't use "First" and "Last" for _position_ info when the same words are used for the name parts
            #    it's needlessly confusing
            #[ValidateSet ('First', 'Last')]
            [ValidateSet ('Start', 'End')]
            [string]
            $LastNamePosition = 'Start'
        )

    begin {}

    process
        {
        # properly supporting the pipeline requires one to have a "process" block.
        #    otherwise all code is run in a virtual "end" block ... and that does not correctly support pipeline input

        # mixing camelCase and PascalCase for variable names is confusing [*grin*]
        #    the recommended style for PoSh is PascalCase
        #$usernameComponents = $FullName.ToLower().Split(" ")
        # the 2nd sample name has a trailing space
        #    the ".Trim()" removes that
        # good practice in PoSh is to avoid using double quotes since that can trigger unwanted expansion of $Vars
        $UserNameComponents = $FullName.Trim().ToLower().Split(' ')

        switch ($LastNamePosition)
            {
            'Start' {
                # "index -1, index 0" for the $UserNameComponents skips any middle name or initial
                $UserName = '{0}.{1}' -f $UserNameComponents[-1], $UserNameComponents[0]
                }
            'End' {
                $UserName = '{0}.{1}' -f $UserNameComponents[0], $UserNameComponents[-1]
                }
            # this is a binary choice, so the "default" is not needed
            #Default { $firstName = $UserNameComponents.Length -1; $lastName = 0 }
            }

        # there is no need to assign the output to anything
        #    whatever is left unassigned will be sent out
        # there is also no need for "return"
        #    that is disrecommeded since it gives the false impression that ONLY the item to its right will be returned
        # the "-replace" operator can be chained. so can the ".Replace()" method
        #    that allows us to skip breaking things into an array of chars
        $UserName -replace
            'č', 'c' -replace
            'ć', 'c' -replace
            'đ', 'dj' -replace
            'š', 's' -replace
            'ž', 'z'

        } # end >>> process

    end {}

    } # end >>> function Get-UserNameFromFullName

run with all names, no parameters, and using the pipeline ...
$InStuff |
    Get-UserNameFromFullName

output ...
djordjevic.cedomir
zoran.jankov
gradimir.stojic
zeljko.vucicevic
boskic.magda

run with all parameters listed and only one input value ...
Get-UserNameFromFullName -FullName $InStuff[-1] -LastNamePosition End

output = magda.boskic


Try not to use using namespace std.
The parameters in main() are only necessary if you're executing from the command line.
You're not calling std::srand() nor including <cstdlib>.  However, if you're using C++11, both std::srand and std::rand are not recommended due to certain computational complications (the C++11 pseudo-random number generators can be found under <random>).  But, for a simple program, it may not matter.

In general, here's how to call std::srand():

// casting may just be necessary if warnings are generated
//     that will alert you if there's a possible loss of data
// prefer nullptr to NULL if using C++11
std::srand(static_cast<unsigned int>(std::time(NULL)));

Only include this once, preferably at the top of main().  This is preferred because

It'll help you keep track of it, especially if it'll need to be removed at some point.
If called repeatedly, you'll receive the "same random number" each time.

It's best to keep variables as close in scope as possible.  Here, dice1 and dice2 can be initialized in the while-loop:

unsigned int dice1 = rand() % 6 + 1;
unsigned int dice2 = rand() % 6 + 1;

roll, however, will need to stay where it is so that the loop will work.
The bool-checking can be shortened:

// these are similar
while (checkWinning(roll) == true)
while (checkWinning(roll))

// these are also similar
while (checkWinning(roll) == false)
while (!checkWinning(roll))

checkWinning() takes int roll, but roll is already unsigned int.  They should match.
checkWinning()'s closing curly brace shouldn't have a ;.  It's not a type.
bool winner seems redundant; just return true or false.  Also, the conditions seem a little unclear.  If the sum constitutes a win or a re-roll, how do you specifically distinguish the two?  They both return true.  I'd at least rename the function for clarification.  There's also a Boolean enum, but that may be overkill here (or even unnecessary as there are only two ending outcomes).
There should be a final outcome message, indicating a win or a loss.  Also, you're not giving the player the option to play another game if victorious (and until loss).


Create own implementation of vector which has moving operations and push_back for rvalue

Have I implemented all move operations in my class Vector?

Yes. And no. You have a bug. You are not resetting the size of the moved Vector, but resetting its buffer, which can break code like this:

Vector<int> vec;
vec.push_back(1);
Vector<int> v = std::move(vec);
if (vec.size() == 1)
    vec[0] = 8; // undefined behavior!

Also, what is tmp? Did you mean to use rhs?

  Is it correct implementation of method push_back for rvalue ?

No. In

buffer[size++] = v;

you are not taking advantage that v is a rvalue reference. You are copying v into the buffer, but that is not needed, as v points to a rvalue. You can move it to the buffer:

buffer[size++] = std::move(v);

Although you have implemented all move operations for Vector, you forgot the copy operations. But maybe you just hide them because you didn't want any feedback on them.

Nonetheless, you could have written your move constructor like this, which is more readable IMO (and doesn't include the bug mentioned above):

Vector(Vector&& rhs) : size(std::exchange(rhs.size, 0)),
                       capacity(std::exchange(rhs.capacity, 0)),
                       buffer(std::echange(rhs.buffer, nullptr))
{}

You can do the same thing for operator=(Vector&&).

However, consider using the copy-swap idiom, for a exception safe way of implementing the Rule of Five.


Complexity

Pedantically, the time-complexity is \$ O( m \times n ) \$, where m is str.length and n is substr.length. This matters when \$ \left| m-n \right| \$ is large.

The Space complexity is \$ O(1) \$. You do not allocate any size-based memory structures.

Safety

It all looks good. There are no threading issues, no leaks, no problems.

Correctly

Nope, I don't like the lack of neat handling for invalid inputs.... you should be null-checking, etc. Getting a raw 'NullPointerException' looks bad.

Edit: Note that Josay has pointed out that your code (and my code below) produce different behaviour to String.indexOf() when the search term is the empty-string/empty-array.

Alternative

I think your code is fine, but... I tend to use loop break/continue more than most... and, this saves a bunch of code in this case...

Also, for readability, I often introduce a limit variable when the loop-terminator can be complicated....

Consider the following loops which do not need the count variable:

int limit = len - sublen + 1;
searchloop: for (int i = 0; i < limit; i++) {
    for (int j = 0; j < sublen; j++) {
        if (str[j+i] != substr[j]) {
            continue searchloop;
        }
    }
    return i;
}
return -1;


Providing factory method to Lazy when factory exists on another lazy instance?

In conjunction with the rest of the code, the following line exhibits a bug:

Contract.Requires(typeof(TResult).Equals(lazyFactory.ReturnType));

The problem is that my IObjectContext.ObjectSet() method has the generic return type IObjectSet<TEntity>, and lazyFactory doesn't have type information for TEntity.

Specifically, the type parameter for lazyFactory is unknown because it's obtained using GetMethod(). As a result, Equals() returns false and the constraint fails with an exception.

I solved the problem by modifying GetLazyFactory to accept a method name string and obtain the MethodInfo itself, calling MakeGenericMethod() as necessary.

public static Func<TOut> GetLazyFactory<TIn, TOut>(Lazy<TIn> dependency, string factoryName)
    where TOut : class
{
    Type outT = typeof(TOut);       // Expected return type of factory method
    MethodInfo factoryMethodInfo =  // Should return TOut
        typeof(TIn).GetMethod(factoryName);

    if(outT.IsGenericType)
    {
        // Get generic type argument of TOut, making sure exactly 1 exists.
        Type tParam = outT.GetSingleGenericArgument();

        // We must specify the generic type or Type.Equals() will yield false.
        factoryMethodInfo = factoryMethodInfo.MakeGenericMethod(tParam);
    }
    return new LazyFactory<TIn, TOut>(dependency, factoryMethodInfo).Invoke;
}


Coordinates as a matrix
This:
x_co = [np.random.uniform(0, 2) for i in range(n_particles)]
y_co = [np.random.uniform(0, 2) for i in range(n_particles)]
return x_co, y_co

is a little baffling. You call into Numpy to generate uniformly distributed numbers (good) but then put it in a list comprehension (not good) and separate x and y into separate lists (not good).
Consider instead
return np.random.uniform(low=0, high=2, size=(2, n_particles))

and similarly for set_initial_velocities:
return np.random.uniform(low=-1, high=1, size=(2, n_particles))

All of the rest of your code, such as the calculations for xdata/ydata should similarly vectorize over the new length-2 dimension eliminating distinct code for x and y.


Comments

// Does stuff depending on what integer the user enters

That is not a good comment.  A comment should say why the code does something if it is not clear and the code should say what it does (if the code is unclear, you can use a comment, but this is also a signal you should write clearer code), this comment is just plain noise.

If you are using the comment to remember what the code does, not just because some teacher/book said to, a comment here is perfectly fine:

// Choose action based on input

Duplicated code

case 1:
    System.out.printf("Enter first number: ");
    fnum = scanner.nextInt();
    System.out.printf("Enter second number: ");
    snum = scanner.nextInt();
    answer = fnum + snum;
    System.out.println("The answer is: " + answer);
    break;

case 2:
    System.out.printf("Enter first number: ");
    fnum = scanner.nextInt();
    System.out.printf("Enter second number: ");
    snum = scanner.nextInt();
    answer = fnum - snum;
    System.out.println("The answer is: " + answer);
    break;

Anything catch your eye there?  Lots and lots of copy/pasted code.  Most of that can be moved to before or after the switch:

System.out.printf("Enter first number: ");
fnum = scanner.nextInt();
System.out.printf("Enter second number: ");
snum = scanner.nextInt();

switch (operation) {
case 1:
    answer = fnum + snum;
    break;

case 2:
    answer = fnum - snum;
    break;
}

System.out.println("The answer is: " + answer);

Output

This really is a nitpick for now, but this:

System.out.println("           Calculator V1.0         ");

Will display the same as this:

System.out.println("           Calculator V1.0");

Methods

This is a pretty straightforward program, but you should start separating unique components of your program and creating more methods.  For example, you could create a method for input, a method for calculating the answer, and a method for output.

Enums

Another thing you should look into is using an enum to designate the selected operation.  Using case Operation.Addition: is clearer than case 1:, and there is a very limited set of data that allowed, which is demonstrated and enforced by the enum, which only accepts the allowed set, and is not enforced by an int.

Bug

Your division operation has a bug:

snum = scanner.nextInt();
answer = fnum / snum;

What happens when the user enters 0?  Your program will crash.  You must always test for division by 0 in cases like this:

snum = scanner.nextInt();
if (snum == 0) {
    System.out.println("Invalid input - cannot divide by 0.");
    break;
}
answer = fnum / snum;