Embarking on a Tic Tac Toe journey with JavaFX

This

GridPane board = new GridPane();
for (int row = 1, col = 1, cell = 0; row <= 3; row++, col -=2) {
    board.add(cells[cell++], row, col++);
    board.add(cells[cell++], row, col++);
    board.add(cells[cell++], row, col);
}

just looks odd. The initialiszing of 3 variables , incrementing of one of then and decrementing one of them in one single for() is a little bit to much IMHO.

how about using a more obvious loop like

for (int cell = 0; cell < cells.length; cell++) {
     board.add(cells[cell], cell / 3, cell % 3);
}

ok, one has to know if he/she reads this, that this will lead to

  (0 , 0 , 0)
  (1 , 0 , 1)
  (2 , 0 , 2)
  (3 , 1 , 0)
  (4 , 1 , 1)
  (5 , 1 , 2)
  ...

but it is less code without the strange incrementing and decrementing.

The creation of the buttons should be improved. Like now you are creating a new Image for each button. Just create the Image once and reuse it like

Image image = new Image("http://i.imgur.com/KAQPbPd.png");
Button[] cells = new Button[9];
for (int i = 0; i < cells.length; i++) {
    cells[i] = new Button("", new ImageView(image);
    registerOnAction(cells[i]);
}

much better now, ins't it ?


Create random list of size n using 2 enums in F#

I second Mark Seemann's remark regarding enums. It makes much more sense to use discriminated unions to describe the entities in your domain.

A randomizing function will never look completely nice and functional, as it uses a side-effect by definition. Nevertheless, I think there isn't much point in passing around the random seed. It can be initialized once in the beginning of your function.

I think things get much clearer when the function randomHand has the call to List.init as its last line, showing that it creates and returns a list. The card generating function could in principle be made into a lambda, but I couldn't squeeze it into less than 7 lines and fslint doesn't like it...

Here's my suggestion:

type Suit = Club | Diamond | Spade | Heart
type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace
type Card =
  { Suit: Suit
    Rank: Rank }

let randomHand size =
  let randomSeed = System.Random ()
  let randomCard _ =
    { Suit = match randomSeed.Next(1, 5) with
             | 1 -> Club | 2 -> Diamond | 3 -> Spade | 4 -> Heart
             | _ -> failwith "random value out of bounds"
      Rank = match randomSeed.Next(2, 15) with
             | 2  -> Two   | 3  -> Three | 4  -> Four | 5  -> Five | 6  -> Six
             | 7  -> Seven | 8  -> Eight | 9  -> Nine | 10 -> Ten  | 11 -> Jack
             | 12 -> Queen | 13 -> King  | 14 -> Ace
             | _ -> failwith "random value out of bounds" }
  List.init size randomCard

Since System.Random.Next() is not bound to a range by its type (int), I had to handle the potential case that it might return a value out of bounds.


What you could use is a function that returns whether an opcode is valid.

private boolean isOpCode(Object opCode){
    return opcode == OP_0 || opcode == OP_1NEGATE || (opcode >= OP_1 && opcode <= OP_16);
}

Then in your code you posted, call the function, and throw an exception if it returns false.

if(!isOpCode(opCode)){
    throw new OpCodeInvalidException("decodeFromOpN called on non OP_N opcode");
}

Replace Object with whatever the opcodes are.

And make a new class that extends from Exception. It's generally bad practice to throw Exception.


Comparing columns values and change their places by condition

Since inner joins are used, you'll only ever be returned rows where the first_actor_id is smaller than the second_actor_id, so the code works as intended.

If I understand correctly, you want the code to check that first_actor_id is smaller than second_actor_id AND second_actor_id is bigger than first_actor_id. However, those two conditions are the same so you only need one of them.

As a sidenote, your code will not work as intended for the following reasons: (1) It will bring back any actors who have starred in ONE movie together, rather than two, and (2) it does not list the movie names they have starred in.

The first problem is easy to fix; add HAVING count(*) >= 2 to the end of the statement.

The second problem depends on the version of SQL Server you are using (use SELECT @@VERSION to find out):

If you're running SQL Server 2017 or later, exchange count(*) in the SELECT for STRING_AGG(fi.title, ', ') (documentation linked) – this will give you a comma-separated list of films.
If not, the best way to concatenate strings from a group is the "stuff XML path" method. A quick search online should explain how this trick works.


For starter, I'd rewrite get_env a bit and introduce intermediate variables for readability:

def get_env(self):
    if not self._environment:
        cwd = os.path.dirname(os.path.abspath(__file__))
        madlib_dir = os.path.join(cwd, '..', 'templates', 'madlib')
        loader = jinja2.FileSystemLoader(searchpath=madlib_dir)
        self._environment = jinja2.Environment(loader=loader)
    return self._environment

Next I would cleanup your @property usage; since the raw decorator already defines the getter property, you can get rid of the first method:

class Template(object):
    def __init__(self):
        self._environment = None

    def __call__(self, temp_name):
        return self.get_env.get_template(temp_name)

    @property
    def get_env(self):
        if not self._environment:
            cwd = os.path.dirname(os.path.abspath(__file__))
            madlib_dir = os.path.join(cwd, '..', 'templates', 'madlib')
            loader = jinja2.FileSystemLoader(searchpath=madlib_dir)
            self._environment = jinja2.Environment(loader=loader)
        return self._environment

Lastly, since the initialization of _environment is meant to be done (and thus checked) only once, why not take advantage of attribute access that already offer us this kind of flexibility:

class Template(object):
    def __call__(self, temp_name):
        return self.environment.get_template(temp_name)

    def __getattr__(self, attribute):
        if attribute == 'environment':
            cwd = os.path.dirname(os.path.abspath(__file__))
            madlib_dir = os.path.join(cwd, '..', 'templates', 'madlib')
            loader = jinja2.FileSystemLoader(searchpath=madlib_dir)
            self.environment = env = jinja2.Environment(loader=loader)
            return env
        return super(Template, self).__getattr__(attribute)

This way, __getattr__ is only called the first time self.environment is accessed and never again. But... Hold on... The only usefull method of this class is __call__... Better write a function instead; this will bring the check back at each call but will make the intent clearer:

def load_template(template_name):
    if not hasattr(load_template, 'environment'):
        cwd = os.path.dirname(os.path.abspath(__file__))
        madlib_dir = os.path.join(cwd, '..', 'templates', 'madlib')
        loader = jinja2.FileSystemLoader(searchpath=madlib_dir)
        load_template.environment = jinja2.Environment(loader=loader)
   return load_template.environment.get_template(template_name)

So now, no need to pass an object around everywhere, just call the function when you need to.

And if you want to, EAFP can also help reduce the overhead of the hasattr test:

def load_template(template_name):
    try:
        environment = load_template.environment
    except AttributeError:
        cwd = os.path.dirname(os.path.abspath(__file__))
        madlib_dir = os.path.join(cwd, '..', 'templates', 'madlib')
        loader = jinja2.FileSystemLoader(searchpath=madlib_dir)
        load_template.environment = environment = jinja2.Environment(loader=loader)
   return environment.get_template(template_name)


I suggest some minor improvements in the regular expression:

make sure that the same separator is used between day and month and between month and year with a backreference (?P=sep),
replace numbered capture groups with named, and make non-needed groups, if there wer any, non-capturing with ?:. Consequently, finditer and groupdict are used, and the day is obtained from the match with int(date['day']), etc. This will make the code somewhat more human.

More importantly, I suggest that you get rid of days, months and years lists altogether. These data can be stored in dictionaries in dates list and filtered prior to appending to dates.
As a consequence, you won't need a loop over range(len(days)).
The validation conditions can be OR'ed together without losing clarity, and I propose to make it a separate function date_is_valid(day: int, month: int, year: int) -> bool.
Also, the only parametre in date_detector can be made typed: def date_detector(text: str):.
To sum suggested modifications up:
import re

def date_is_valid(day: int, month: int, year: int) -> bool:
    return (month not in (2, 4, 6, 9, 11)   # 31 days in month (Jan, Mar, May, Jul, Aug, Oct, Dec).
    or day < 31 and month in (4, 6, 9, 11)  # 30 days in month (Feb, Apr, Jun, Sep, Nov).
    or month == 2 and day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
                                            # February, 29th in a Gregorian leap year.
    or month == 2 and day < 29)             # February, 1st-28th.

def date_detector(text: str):
    date_pattern = re.compile('''
    (?P<day>[12][0-9]|3[0-1]|0?[1-9])   # to detect days from 1 to 31
    (?P<sep>[./-])                      # to detect different separations
    (?P<month>1[0-2]|0?[1-9])           # to detect number of months
    (?P=sep)                            # to detect different seperations
    (?P<year>2?1?[0-9][0-9][0-9])       # to detect number of years from 1000-2999 years
     ''', re.VERBOSE)

    dates = []
    for match in date_pattern.finditer(text):
        date = match.groupdict()                            # convert Match object to dictionary.
        del date['sep']                                     # we don't need the separator any more.
        date = {key: int(val) for key, val in date.items()} # apply int() to all items.

        if date_is_valid(date['day'], date['month'], date['year']):
            dates.append(date)

    if len(dates) > 0:
        for date in dates:
            print(date)

data = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012'

date_detector(data)
```


Use function syntax/memo when possible
Use destructuring
Use object literal shorthand
Define defaults for width and height
handleClick is just onClick renamed
Use tooling for formatting your code (eslint, prettier)
Prefer ternary over if (not always true)
Have a well defined API for your components (ListElement needs text, not the entire item, and doesn't really need index)

const ListElement = React.Memo(({ handleClick, label }) => (

{label}

));

const ListComponent = React.Memo(
  ({
    items,
    listDetails: {
      size: { height, width }
    },
    onClick
  }) => (

      {items.map(({ text }, i) => (
        <ListElement label={text} key={i} handleClick={() => onClick(i)} />
      ))}

  )
);

ListComponent.propTypes = {
  items: PropTypes.arrayOf(
    PropTypes.shape({
      text: PropTypes.string.isRequired
    })
  ).isRequired,
  listDetails: PropTypes.object.isRequired
};

// Not quite sure I'm setting defaultProps correctly here, but you get the idea
ListComponent.defaultProps = {
  listDetails: { size: { height: DEFAULT_HEIGHT, width: DEFAULT_WIDTH } }
};

You can also update propTypes with the shape of listDetails or change so that ListComponent takes size as an attribute instead, depending on what makes sense in your scenario.


Control game ticks/frames of updates and rendering separately

I think sourcing the game-loop out is basically a good idea to improve separation of concerns. But I would go farther: I would implement a strategy pattern which makes the behavior of the game loop exchangeable. Futhermore I would source out the loop itself, too.

public interface IGameLoop{
    void Start();
    void Stop();
}
public interface IUpdateBahvior
{
    bool TryUpdate();
}
public interface IRenderBehavior
{
    bool TryRender();
}

Example implementation:

class SynchronGameLoop : IGameLoop
{
    private bool _isRunning;
    private readonly IUpdateBehavior _updateBehavior;
    private readonly IRenderBehavior _renderBehavior;

    public SynchronGameLoop(IUpdateBehavior updateBehavior, IRenderBehavior renderBehavior){
        _updateBehavior = updateBehavior;
        _renderBehavior = IRenderBehavior ;
    }

    public void Start(){
        if(_isRunning) return;
        while(_isRunning){
            _updateBehavior.TryUpdate();
            _renderBehavior.TryRender();
        }
    }
    public void Stop()
    {
        _running = false;
    }
}

class AsyncGameLoop : IGameLoop ...

class StatisticProvidingGameLoop: IGameLopp ...

This system offers you the possibility to exchange the game loop behavior at run-time. So If you decide to implement a game loop that offers statistic information(update count, update time, render count) for debugging purpose, you free to exchange this, without altering your code.

The separation into two *behavior interface provide the possibility to implement completely independent strategies, for this two functionality. But if you wish to, one class can implement both interfaces and can make the functionality dependent on each other. So while implementing your engine, you don't define what kind of game loop and update/render behavior is finally used. For example in XNA, you can switch between fixed time steps and variable one. All this is easily possible with the strategy pattern.


Calculating COUNT(*) of a MAX() + GROUP BY query

To determine the number of distinct groups a distinct query over the grouping columns is sufficient. No temp table is needed.

SELECT COUNT(DISTINCT col1, col2) FROM tbl

Depending on the data type of your grouping columns it might be beneficial to define a two-column index on (col1, col2).

Have a look at MySQL's GROUP BY Optimization documentation to see how this works.


Making a dynamic query based on a cookie change

First suggestion is that you shouldn't write the same code twice.

Your $_GET-if-conditions can be put into a separate function.

$this->handleCookieByGetParameter('c', 'qanda_questions_category');
$this->handleCookieByGetParameter('t', 'qanda_questions_tag');

public function handleCookieByGetParameter($parameter, $name)
{
    if ( isset($_GET[$parameter]) ) {
        if ( empty($_GET[$parameter]) ) {
            unset_cookie($name);
        } else {
            set_cookie($name, $_GET[$parameter]);
        }
    }
}

and then I recommend that you check your error before you handle your other stuff:

if ( !$this->category_cookie && !$this->tag_cookie ) {
    return header("Location: /myweb/questions".make_url_query($_GET, [],['c','t']));
    // better an RedirectException
}

$query_where = $query_join = '';

if ( $this->category_cookie ) {
    $query_where .= "AND qa.category = :c";
    $this->parameters[":c"] = $_COOKIE['qanda_questions_category'];
}

if ( $this->tag_cookie ) {
    $query_join  .= " INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
                  INNER JOIN tags ON tags.id = qt.tag_id";
    $query_where .= " AND tags.name = :t";
    $this->parameters[":t"] = $_COOKIE['qanda_questions_tag'];
}

return $this->index($query_where, $query_join, __FUNCTION__);

my next step would be to look to extract the query code into a separate function, so I could use it for other methods too.


First of all, your checksum function should probably be named checksum and actually return the checksum, rather than simply printing it.

Now, you're not taking advantage of what the std::basic_ifstream API actually gives you. First, read() returns a basic_istream&, which is convertible to bool. That bool tells you if the complete read succeeded or not. So all you have to do is:

uint32_t checksum(std::ifstream& file)
{
    uint32_t sum = 0;

    uint32_t word = 0;
    while (file.read(reinterpret_cast<char*>(&word), sizeof(word))) {
        sum += word;
    }

    // ??

Now, when read() fails, that means our file has run out (assuming we had a valid file to begin with). But, we have other information. There is also gcount() which

  Returns the number of characters extracted by the last unformatted input operation.

If the read partially succeeded, we can mask off the other bytes and add the remainder. Thus, the full solution might be:

uint32_t checksum(std::ifstream& file)
{
    uint32_t sum = 0;

    uint32_t word = 0;
    while (file.read(reinterpret_cast<char*>(&word), sizeof(word))) {
        sum += word;
    }

    if (file.gcount()) {
        word &= (~0U >> ((sizeof(uint32_t) - file.gcount()) * 8));
        sum += word;
    }

    return sum;
}

Doing the masking looks kind of terrible though, so instead we could simply zero out word every time so we can just add the result:

uint32_t checksum(std::ifstream& file)
{
    uint32_t sum = 0;

    uint32_t word = 0;
    while (file.read(reinterpret_cast<char*>(&word), sizeof(word))) {
        sum += word;
        word = 0;
    }

    sum += word; // add the last word, could be 0
                 // if the file size is divisible by 4

    return sum;
}


Some general remarks:

The method name removeAll is misleading, as it does not remove
all elements from the array. I would call it for example removeMatching.
The method parameter is a closure, but acts as a predicate, so
predicate might be a better name.
The counter variable in the method is actually the array index
so you could call it index.
The method documentation can be improved (details at the end of
this answer).

Your concrete problem about modifying the loop counter inside the
loop can easily be solved by traversing the array indices in
reverse order:

for var index = count - 1; index >= 0; index-- { ... }

Using stride() allows you to have a constant loop variable:

for index in stride(from: count - 1, through: 0, by: -1) { ... }

Putting it all together:

extension Array {

    /// Removes all items that satisfy the predicate:
    mutating func removeMatching(predicate: (T) -> Bool) {
        for index in stride(from: count - 1, through: 0, by: -1) {
            if predicate(self[index]) {
                removeAtIndex(index)
            }
        }
    }
}

An alternative implementation would be

extension Array {

    /// Removes all items that satisfy the predicate:
    mutating func removeMatching(predicate: (T) -> Bool) {
        self = self.filter { !predicate($0) }
    }
}

The first method removes the matching elements, while the second method
creates a new array and then replaces self. Which one is more
efficient depends how many elements are actually removed in relation
to the array size.

Notice that in Swift 2, Element should be used in place of T.

As mentioned above, the inline method documentation can be improved
(I took this information from the SO thread Swift Documentation Comments). Example:

extension Array {
    /// Removes all items that satisfy the `predicate`
    ///
    /// :param: predicate A boolean predicate.
    mutating func removeMatching(predicate: (T) -> Bool) {
        self = self.filter { !predicate($0) }
    }
}

Now "Option-Click" will show you

Addendum: A removeAll(where:) was added to the Swift Standard library in Swift 4.2, so there is no need to define your own method for that purpose anymore.

As explained in SE-0197 this method is supposed to be both safe and efficient.


Java enum containing a hash map for look up

Your code is very neat and clean, there is only one thing that I would change:

private static Map<String, String> mMap;

to

private static final Map<String, String> mMap = Collections.unmodifiableMap(initializeMapping());

The reasons:

By not declaring it final and not using a call to unmodifiableMap it is mutable, and it would be possible to modify the reference using reflection or to use .remove("ABC") on the map. Declaring it as final makes sure that the referenced map cannot change and unmodifiableMap makes sure that no changes can be done to the map itself.
Multi-threading issues. As it currently stands, if two threads would call the getDescriptionByCode method at the same time you would initialize the mapping twice, which is not needed.

This also of course requires a slight change in your initializeMapping():

private static Map<String, String> initializeMapping() {
    Map<String, String> mMap = new HashMap<String, String>();
    for (Maps s : Maps.values()) {
        mMap.put(s.code, s.description);
    }
    return mMap;
}

Besides this, it all looks good. Well done!


Given an integer, return its binary representation. You cannot use any Integer.toXXXString methods

A single loop would be preferable.

public static String toBinaryString(int n) {
    char[] buffer = new char[32];
    for (int i = buffer.length - 1; i >= 0; i--) {
        buffer[i] = '0' + (n & 1);
        n >>>= 1;
    }
    return new String(buffer);
}


Accessing an unreturned list within a function in Python without disturbing Scipy

Unfortunately I don't know SciPy or anything about the problem you're solving. I can however comment on coding style.

Style is important

Python has a style convention referred to as PEP 8. The full specification can be found on Python's website. One often repeated mantra is "readability counts", because code is often read more than written. Because consistency improves readability, and conventions enforce consistency, I think following the PEP 8 style guide is important. It will make it easier for other people to understand your code.

The following sections describe the changes I think you could make to improve the style and in turn readability of the code.

Use newlines to separate logical units

This will make the code look better organized and it will make it easier to at a glance get a grasp of what parts the program is composed of.

import scipy.optimize as spop
ObservedSpeeds = [85, 64, 97 ,82, 12, 30, 47, 20, 45, 90, 60, 42, 50, 67, 28] #This is not the actual dataset, I actually have a data set of 525,600.
def ErrorCalc(alpha,ObservedSpeeds):
    yPredList = [0,ObservedSpeeds[0]] #First prediction is 0 and the second prediction is the first observation
    for iters in range(2,len(ObservedSpeeds)):
        yPredList.append(np.multiply((1-alpha),yPredList[iters-1]) + np.multiply(alpha,ObservedSpeeds[iters-1]))
    NewList = [np.abs(y-o) for y,o in zip(yPredList,ObservedSpeeds)]
    NewError = np.mean(NewList)
    return NewError

becomes

import scipy.optimize as spop

ObservedSpeeds = [85, 64, 97 ,82, 12, 30, 47, 20, 45, 90, 60, 42, 50, 67, 28] #This is not the actual dataset, I actually have a data set of 525,600.

def ErrorCalc(alpha,ObservedSpeeds):
    yPredList = [0,ObservedSpeeds[0]] #First prediction is 0 and the second prediction is the first observation

    for iters in range(2,len(ObservedSpeeds)):
        yPredList.append(np.multiply((1-alpha),yPredList[iters-1]) + np.multiply(alpha,ObservedSpeeds[iters-1]))

    NewList = [np.abs(y-o) for y,o in zip(yPredList,ObservedSpeeds)]
    NewError = np.mean(NewList)

    return NewError

snake_case vs CamelCase

In Python, snake_case style is used for variable and function names while CamelCase is used for class names. To someone used to this convention (like me), your code is very confusing at first.

This includes changes to ErrorCalc, ObservedSpeeds, NewError etc.

Allow operators some space

I think the most significant possible style change would be to add some spacing around or after some operators. Generally putting a space after , and spaces around binary operators like +, - etc improve readability a lot.

Conclusion

With a few minor changes, your code can become much easier for other (and yourself) to understand. Learning this is something that will benefit you in the future as well.


That's some nicely presented code.  I found it very easy to read and understand.
A vector of rows isn't the best structure for a matrix.  The reason is that each vector has its storage elsewhere, so you lose locality of access.  A better structure is a flat array (or vector) of elements, and a knowledge of the stride from one row to the next.  (we can make the stride be the same as the row length, for simplicity; separate members for width and stride can be useful in more advanced scenarios).
    std::vector<int> m;
    std::size_t width;

public:
    # Constraint: x * y must not overflow size_t
    matrix(std::size_t x, std::size_t y)
        : m(x*y, 0),
          width{x}
    {
    }

I've made the dimensions be size_t, as that's the natural type for a size or count in C++.
Now, when we need to index into the array, we need to multiply the y value by width and add x:
int get_value(std::size_t x, std::size_t y)
{
    return m[x + y*width];
}

We can improve on this, by returning a reference to the value.  Instead of having a "get" and "set" method, we have a single method (for now), and we can give it a more convenient name:
int& operator()(std::size_t x, std::size_t y)
{
    return m[x + y*width];
}

This means that instead of having to write
mm.assign_value(0,0,1);

we can instead use the more intuitive
mm(0,0) = 1;

Now it's time admit to a slight lie above.  We actually need two methods, because if we have a const matrix, we should be allowed to read, but not write, its elements.  So we also need:
const int& operator()(std::size_t x, std::size_t y) const
{
    return m[x + y*width];
}

For printing, it's helpful to provide an operator<<().  Mine would look like this:
friend auto& operator<<(std::ostream& os, const matrix& m)
{
    for (std::size_t row = 0;  row < m.height;  ++row) {
        for (std::size_t col = 0;  col < m.width;  ++col) {
            os << m.m[col + row*m.width] << ' ';
        }
        os << '\n';
    }
    return os;
}

I added a height member to make this easier.

With these changes, see how much easier it is to use:
#include <iostream>

int main()
{
    // create a matrix object
    matrix mm(4,6);

    // print elements
    std::cout << mm;

    // grab a value and print it to console
    std::cout << mm(0,0) << std::endl;

    // assign a new value (v = 1) to element (0,0)
    mm(0,0) = 1;

    // re-print the updated matrix
    std::cout << mm;
}

Here's the full version of matrix after my edits:
#include <ostream>
#include <vector>

class matrix {
    std::vector<int> m;
    std::size_t width;
    std::size_t height;

public:
    matrix(std::size_t x, std::size_t y)
        : m(x*y, 0),
          width{x},
          height{y}
    {
    }

    int& operator()(std::size_t x, std::size_t y)
    {
        return m[x + y*width];
    }

    const int& operator()(std::size_t x, std::size_t y) const
    {
        return m[x + y*width];
    }

    friend auto& operator<<(std::ostream& os, const matrix& m)
    {
        for (std::size_t row = 0;  row < m.height;  ++row) {
            for (std::size_t col = 0;  col < m.width;  ++col) {
                os << m.m[col + row*m.width] << ' ';
            }
            os << '\n';
        }
        return os;
    }
};

Further exercises

If you actually want a public get_row() (and get_column()), these will need new implementations, perhaps copying values.
Think about providing a get_subarray(x, y, width, height) to give a view of part of the matrix - you'll need new members for offset and stride.  See how we can now more easily implement get_row() and get_column() using this new method.
Make the matrix a template, so we can have elements of whatever type we choose, rather than only int.


Is it bug free?  No.

These two corner-cases have been missed:

parameter values containing '=', i.e. 'example.com?foo==bar' (double equals) or '?foo=k=v'
cannot handle parameters called 'toString' and 'valueOf' (amongst others.)

The first may well count as malformed URL, but Chrome handles it and pass through == unencoded in location.search.  To handle this, go back to basic indexOf usage.

The second problem's just pedantic really.  You could try and work around it using !params.hasOwnProperty(n) instead of !(n in params), but you'll still get stuck if someone passes a parameter called hasOwnProperty.  The only way I see around this is to fall back to some dire array-based collection populated something like:

var keys = [], params = [];
for (...) {
    var n = ..., v = ...;
    var i = keys.indexOf(n);
    if (i >= 0) {
        if (!(params[i] instanceof Array)) {
            params[i] = [params[i]];
        }
        params.push(v);
    } else {
        params[i] = v;
        keys.push(n);
    }
}

I guess you'd then have to resort to returning an array of arrays rather than an object.  i.e. each element of the array returned would either be [key, value] or [key, [values]], although client might find it easier to work with if you returned something like [key, value1, value2, ...] (which caters nicely for properties without values.)


Sorting of nested categories inside a Common Table Expression

Instead of using some large number base, I'd use an array.

Start with ARRAY[display_order] AS global_display_order.  For each additional level, array_append(global_display_order, display_order).  Arrays are compared element by element; ties are resolved by putting the shorter array first — which is what you want.

For readability, instead of the table aliases c0 and c1, I suggest parent and child.


Inserting into Group_roles table for all rows in Group table

if not exists
    (SELECT gr.*
     FROM Group.g INNER JOIN GROUP_ROLES gr ON g.id = gr.group_id INNER JOIN ROLE r ON gr.roles_id = r.id
     WHERE r.name = 'newRole' AND g.name IN ('Group1', 'Group2', 'Group3', 'Group4', 'Group5'))
begin
INSERT INTO GROUP_ROLES (group_id, roles_id)
    SELECT g.id AS group_id, r.id AS roles_id
    FROM Group g CROSS JOIN ROLE r
    WHERE r.name = 'newRole' AND g.name IN ('Group1', 'Group2', 'Group3', 'Group4', 'Group5')
end

Basically, you can INSERT the results of a SELECT query into the table.  So first get the SELECT query right so that it returns the five rows that you want and then just add the INSERT clause at the beginning.  Note that I gave the columns aliases that matched the destination columns, but that's actually unnecessary.  I did it purely because I find having two id columns confusing.

SQL Server documentation of INSERT with a SELECT subquery.

According to INSERT INTO SELECT to avoid duplicates, you could also write

INSERT INTO GROUP_ROLES (group_id, roles_id)
    SELECT g.id AS group_id, r.id AS roles_id
    FROM Group g CROSS JOIN ROLE r
    WHERE r.name = 'newRole' AND g.name IN ('Group1', 'Group2', 'Group3', 'Group4', 'Group5')
      AND NOT EXISTS (SELECT gr2.*
         FROM Group.g2 INNER JOIN GROUP_ROLES gr2 ON g2.id = gr2.group_id INNER JOIN ROLE r2 ON gr2.roles_id = r2.id
         WHERE r2.name = 'newRole' AND g2.name IN ('Group1', 'Group2', 'Group3', 'Group4', 'Group5')
           AND gr.group_id = gr2.group_id AND gr.roles_id = gr2.roles_id)

I don't know that that's better though.

You can avoid the EXISTS checks entirely if you put a UNIQUE index on group_id and roles_id in the GROUP_ROLES table.  Although you'll want to catch exceptions in that case.

For the obvious reasons, I haven't tested any of this.  You can test the SELECT queries pretty easily, and it's not much harder to test the if not exists notation.


Python common file operations generalization

The code is straighforward and reads good; there is not much to say per se. I would just advise to use f.readlines instead of list(f).

However, there exist a pattern in Python when you need to wraps functions using a common behavior: decorators.

I suggest having a decorator taking the open_mode as parameter:

import pickle
from functools import wraps

def opening(access_mode='r'):
    def decorator(func):
        @wraps(func)
        def wrapper(filename, *args, **kwargs):
            with open(filename, access_mode) as f:
                return func(f, *args, **kwargs)
        return wrapper
    return decorator

@opening()
def read_lines(file_):
    return file_.readlines()

@opening('w')
def write_lines(file_, data):
    file_.writelines(data)

@opening('rb')
def load_pickle(file_):
    pickle.load(file_)

@opening('wb')
def save_pickle(file_, data):
    pickle.dump(data, file_)

Usage is the same.


No need to check if the variables are instanceof Date. A dates value is its time so when you make (less than/greater than) comparisons with a Date instance (x) you're essentially comparing it to +x or x.valueOf() which will be the same as x.getTime(). Therefore the below will always be equivalent:

function equal(a, b) {
    if (a instanceof Date && b instanceof Date) return +a == +b; //compare the 2 dates times as noted in the above statement +x == x.getTime() == x.valueOf()
    return a == b;
}

function lessThan(a, b) {
    return a < b;
}

function greaterThan(a, b) {
    return a > b;
}


Function for creating unique strings for urls

Algorithm

  Every call must generate a unique string of alpha numeric characters.
  Most important: Zero chance of string duplication.

"zero chance" is really hard to achieve, if it's even possible.
Your algorithm is essentially based on the current time in microseconds.
Since systems may adjust their clock, for example with NTP,
the same microsecond may happen again,
resulting in a non-unique string.

Striving for a unique random string is known challenge,
see for example the uniqid function.
The documentation offers some recommendations for cryptographic security,
and I think it might be a good idea to incorporate uniqid into your algorithm.

  Repeat calls should reflect a high degree of dissimilarity.

If I call the function twice in a row I get values with a similar prefix, for example:

qf1p1dojax7n7m08no1f
qf1p1drbj0nbnahjqg1f

gp70pxdfghnbnaetckpa
gp70pxg8j0q4q3hlfcpa

This is because in the microseconds parts are too similar in consecutive calls.
You seem to be using the microseconds part as a 6-digit random number.
You would get better results with a proper pseudo random generator,
for example one of the recommendations from uniqid.

Readability

The implemented algorithm is quite straightforward:

Prepare 3 strings of at least 10-digits:

a 12-digit string from the first 6 decimal digits of the microseconds elapsed since the current timestamp seconds, concatenated with its reverse
a 10-digit string from the current timestamp
a 10-digit string from the reverse of the current timestamp

Count from 0 until 9 to generate a 20-letter string:

Create a 3-digit number using i-th positions from the prepared strings
Encode the 3-digit number as a base-36 number, so that it becomes a 2-letter string
Concatenate the 2-letter encoded strings to get a 20-letter string

Unfortunately this flow of logic is not easy to see in the implementation,
because the variable names are not helping.

Instead of the array $time_array,
it would be better to use 3 variables with descriptive names.
If you extract the big logical steps to functions, for example one to generate a 3-digit number, and another to encode a 3-digit number in base-36, the code could read almost like a story.

Technique

Instead of $mod = $num - ($mult * 36) you could simply use the modulo operator: $mod = $num % 36.

Instead of hard-coding 36, which has to be the length of $letters,
it would be better to store it in a variable, and derive its value from the length of $letters.
So that if one day you change the alphabet (for example add capital letters too),
then you won't have to remember to replace all the 36 with the new value,
the program will "just work".

Instead of implementing base-36 encoding yourself,
you could use the existing base_convert function.
It's not 100% the same, because it uses slightly different alphabet,
and you would need to convert the number parameter to string.


Dice roll simulator (updated) created using Python 3.5 and PyQt5

Nice code, so only some comments.

ONE_DIE_PARMS = 1427, 30, 162, 201
TWO_DICE_PARMS = 1265, 30, 324, 201

Never used, typo in the first of them.

In contrast, there are other magic numbers in your code which deserve names for them.

DICE = ('dice_1.png', 'dice_2.png', 'dice_3.png', 'dice_4.png', 'dice_5',
        'dice_6.png')

may become

DICE_TEMPLATE = 'dice_{}.png'
DICE = [DICE_TEMPLATE.format(i) for i in range(1, 7)]

(BTW. it's common to use plural for names of collections - DICES)

geo2 = geo[19:len(geo) - 1]

may become

geo2 = geo[19:-1]

as negative numbers in slices mean "from the end".


Creating an array of associative arrays in PHP

Instead of declaring $i=0; before the loop, you can also write :

foreach($resultSet as $i => $r)
{
  $output[$i]['key1'] = $r['col1'];
  $output[$i]['key2'] = $r['col2'];
  ...
  $output[$i]['keyN'] = $r['colN'];
}

Also, if you could rename your column in the DB query, you could have :

foreach($resultSet as $i => $r)
{
  $output[$i] = $r;
}

Which is pretty much like doing $output = $resultSet;

Edit :
If you do need to do some processing on $resultSet for whatever reason and you'd rather have different names, you can consider doing :

for (array('key1' => 'col1', ... 'keyN' => 'colN' as key => col)
{
   $output[$i][$key] = $r[$col];
}


I've had to do this exact thing before, your way is absolutely fine but I went for the other way round - checking if it was all text:

private static bool HtmlIsJustText(HtmlNode rootNode)
{
    return rootNode.Descendants().All(n => n.NodeType == HtmlNodeType.Text);
}

Then you have your public method as:

public static bool ContainsHTMLElements(string text)
{
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(text);
    return !HtmlIsJustText(doc.DocumentNode);
}

I think that makes the code slightly more concise.

I'd argue that your class should really be called HtmlUtility as per guidelines

  The PascalCasing convention, used for all identifiers except parameter names, capitalizes the first character of each word (including acronyms over two letters in length), as shown in the following examples:

  PropertyDescriptor
  HtmlTag


A Java class for calculating size of iterable/array

For arrays, you are missing a generic int size(Object[] data) method, which can be written as:

public static <E> int size(E[] data) {
     return data.length;
}

This will apply to String[] as well. You will still need one for each kind of primitive though (boolean, short, int, long, float, double, did I miss anything?)

As for your other method...

public static <T, I extends Iterable<T>> int size(I data) {

This one can be cleaned up significantly.

You don't need the <T> here. In fact, you don't need the <I> either. It doesn't matter what kind of iterable it is so you can use Iterable<?>.

As you're not defining a variable of type I anywhere in your method, nor is using that type in another obscure way, all you're really interested in is that it is an Iterable<T>. So:

public static <T> int size(Iterable<T> data) {

Will have the same effect.

Now, are you using the type <T> ? No. In fact, you are iterating over Object so all you're interested in is that it is Iterable<? extends Object>. Which is the same as Iterable<?> since all classes extends Object.

So now we are left with this:

public static int size(Iterable<?> data) {
    final int size;
    if (data instanceof Collection) {
        size = ((Collection<?>) data).size();
    } else {
        int counter = 0;
        for (Object i : data) {
            counter++;
        }
        size = counter;
    }
    return size;
}

And when introducing early return, this:

public static int size(Iterable<?> data) {
    if (data instanceof Collection) {
        return ((Collection<?>) data).size();
    }
    int counter = 0;
    for (Object i : data) {
        counter++;
    }
    return counter;
}

Now that's a method.

Side note: The only method you have that is actually useful is int size(Iterable<?> data). Otherwise it would be easier to just use data.length or data.size();. However, I understand that this is just an exercise in which case it's fine.


Recursively pop the last node from a singly linked list

Due to the Box, pattern matching with boxes is messy on stable. If you are willing to use nightly until box patterns are stabilized, you can rewrite your pop_back function (instead of just the pop_last_node function):

pub fn pop_back(&mut self) -> Result<T, LinkedListError> {
    fn pop_last_node<T>(node: &mut NodePtr<T>) -> Option<T> {
        match node.take() {
            None => None,
            // is a leaf
            Some(box Node { next: None, data }) => Some(data),
            Some(mut this) => {
                // recurse
                let ret = pop_last_node(&mut this.next);
                // put this subnode back, since it's not a leaf
                *node = Some(this);
                ret
            }
        }
    }
    pop_last_node(&mut self.head).ok_or(LinkedListError {
        kind: LinkedListErrorKind::Empty
    })
}

Try it out in the PlayPen

To make the above code work in stable, you can add an inner match instead of the box pattern.

match node.take() {
    None => None,
    Some(n) => match *n {
        // is a leaf
        Node { next: None, data } => Some(data),
        mut this => {
            // recurse
            let ret = pop_last_node(&mut this.next);
            // put the subnode back, since it's not a leaf
            *node = Some(Box::new(this));
            ret
        }
    }
}


A function for parsing words from a string without using whitespace

You should give your variables better names. For example, while you might know what the variable p1, or p2 does, people reading your code don't. Giving your variables better names also reduces the need for inline comments like # String slice position 2.

Rather than using the dict function to initialize an empty dictionary, you can just type the following: words = {}.

Finally, you don't need the parentheses around the '' in words[sub1] = (''). It can be changed to the following: words[sub1] = ''.


Is this the correct way to implement a HMAC token system?

This looks good.

I do almost exactly the same thing as a password reset mechanism. I am including it here in case it will help you with adding a timer to help prevent replay attacks.

The user receives an email with a link to click to reset their password (the $oldpassword is the nonce because once the password is changed once, it is not valid anymore and the HMAC key is the old password salt (used by the php crypt function)).

$time = time();
$userid = $user->id;
$oldpassword = hash('sha256', $password_info['Password']);
$token = "t={$time}&i={$userid}&o={$oldpassword}";
$verification = hash_hmac('sha256', $token, $password_info['Salt']);

$newpasswordurl = Router::url('user_r')->uri(array(
    't' => $time,
    'i' => $userid,
    'o' => $oldpassword,
    'v' => $verification,
));

The validation is similar.

$userid = $input['i'];
$time = $input['t'];
$expire_time = date_create_from_format('U', $input['t'])->add(date_interval_create_from_date_string(self::$settings['ResetPassword']['LinkValidityTime']));
$oldpassword = $input['o'];
$hash = $input['v'];

$p_info = self::getPasswordParts($OldPassword);

$token = "t=$time&i=$UserID&o=$oldpassword";
$correct_hash = hash_hmac('sha256', $token, $p_info['Salt']);

if ( ($hash != $correct_hash) || ($oldpassword != hash('sha256', $p_info['Password'])) ) {
    throw new ChangePasswordException("That password link is invalid, has expired or has been used.");
}


Solving Robot Paths with Pascal's Triangle

You can collapse the two base cases (n === 1 and n === 0) in getPaths() into one n < 2 condition, which then also matches the base case used in pascal().

Also Pascal's triangle only needs to be calculated if n is more than 1, so the call to pascal() can be put into the else-clause rather than at the beginning of the function.

function getPaths(n) {
    if (n < 2) {
        return n;
    } else {
        var tri = pascal(n * 2);
        var oddElement = (n + (n - 2));
        var mid = Math.floor(tri[oddElement].length / 2);
        // console.log(oddElement);
        return tri[oddElement][mid];
    }
}


SPOJ GENERAL: sorting by swaps of distance k

The above code can be optimized a little by below changes.

Replace this

        for( ; j < i - k; j++) {
            if(a[j] > a[j + k]) {
                int temp = a[j];
                a[j] = a[j + k];
                a[j + k] = temp;
                count++;
            }
        }

        for( ; j < i - 1; j++) {
            if(a[j] > a[j + 1]) {
                result = false;
                break;
            }
        }

        if(!result)
            break;

By

        int  j = i-k;
        int x = 0;
        int tmp[i/k]; // Do check for i==0 here
        for(int j = i; j >= 0; j -= k){
            tmp[x] = a[j];
            x++;
        }
        sort(tmp);
        for(int j = i; j >= 0; j -= k){
             a[j] = tmp[x]; x--;
        }

Add a check outside the main loop if its sorted or not.
But still this will be in order of \$O(N*KlogK)\$ which in worst cases \$O(N^2logN)\$. You might still get the TLE with that.

We can solve this in \$O(NlogN)\$. Trying thinking of solution in which you sort this a keeping original indexes of each element. Then calculate the number of swap by comparing the old index with new one.


You can use a Dictionary<int, int> of positions of the first occurrence of each element value.
Next, iterating over all elements of the input array, you do:

If the positions[value] is empty, store the current index i in it: positions[value] = i.
Else, calculate the distance (or cycle length).
If this distance is greater than maximum, save it as a new maximum.

This algorithm has time complexity \$O(n)\$.

The code:

public static class CycleSearch
{
    public static int GetMaximumCycle(int[] array)
    {
        Dictionary<int, int> positions = new Dictionary<int, int>();

        int result = 0;
        for (int i = 0; i < array.Length; i++)
        {
            int value = array[i];
            int position;
            if (!positions.TryGetValue(value, out position))
            {
                positions[value] = i;
            }
            else
            {
                int cycleLength = i - position;
                if (cycleLength > result)
                {
                    result = cycleLength;
                }
            }
        }
        return result;
    }
}

Usage:

int[] exampleArray = { 4, 6, 2, 2, 6, 6, 1, 55, 55, 2, 5, 6, 90, 8, 8, 8, 10, 70 };
Console.WriteLine(CycleSearch.GetMaximumCycle(exampleArray));

Output:

  10


Processing requests using the user's time zone

If your usecase is displaying localized time in views then please handle it in frontend, i.e. using http://timeago.yarp.com/

Handling timezone in backend will be big pain when you try to add caching (you will need to cache same piece of content for each timezone).


First, let's rewrite your code in idiomatic Go.

// For loop using a for clause
func NewRectangleF(height, width int, value byte) [][]byte {
    r := make([][]byte, 0, height)
    for i := 0; i < height; i++ {
        r = append(r, bytes.Repeat([]byte{value}, width))
    }
    return r
}

// For loop using a range clause
func NewRectangleR(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    for i := range r {
        r[i] = bytes.Repeat([]byte{value}, width)
    }
    return r
}

Then write and run some tests and benchmarks using Go 1.3.

$ go version
go version go1.3rc2 linux/amd64
$ go test -v -bench=.
=== RUN TestNewRectangle
--- PASS: TestNewRectangle (0.00 seconds)
PASS
BenchmarkNewRectangleFL5          50      38272524 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleRL5          50      38195877 ns/op     6340608 B/op       2049 allocs/op

The benchmarks are for a large rectangle ((2 * 1024) by (3 * 1024)) with an initial value of 5.

Not surprisingly, the results are the same because we are doing the same thing. The range form is clearly better because it's easier to read and easier to verify that it's correct.

Are the results fast? Here's a simple alternative basic implementation.

// Benchmark basic
func NewRectangleB(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    for i := range r {
        w := make([]byte, width)
        if value != 0 {
            for j := range w {
                w[j] = value
            }
        }
        r[i] = w
    }
    return r
}

The benchmark results:

$ go test -v -bench=. -run=!
PASS
BenchmarkNewRectangleFL5          50      38272524 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleRL5          50      38195877 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleBL5         500       5428041 ns/op     6340608 B/op       2049 allocs/op

The basic implementation looks faster; it uses about 86% less CPU time (5428041 ns/op vs. average 38234200.5 ns/op). It doesn't use the bytes.Repeat function. In Go 1.2 and Go 1.3 the bytesRepeat function looks slow.

// bytes.Repeat returns a new byte slice consisting of count copies of b.
func Repeat(b []byte, count int) []byte {
    nb := make([]byte, len(b)*count)
    bp := 0
    for i := 0; i < count; i++ {
        bp += copy(nb[bp:], b)
    }
    return nb
}

Let's see if we can write an optimal version by improving the repeat function and reducing the large number of heap allocations (2049 allocs/op). Plus, since make sets the underlying array to the zero value for the type, we can make a zero initial value a special case.

func repeat(b []byte, count int) []byte {
    nb := make([]byte, len(b)*count)
    if len(b) == 1 && b[0] == 0 {
        return nb
    }
    bp := copy(nb, b)
    for bp < len(nb) {
        copy(nb[bp:], nb[:bp])
        bp *= 2
    }
    return nb
}

// Benchmark optimization
func NewRectangleO(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    a := repeat([]byte{value}, height*width)
    start, end := 0, width
    for i := range r {
        r[i] = a[start:end:end]
        start, end = end, end+width
    }
    return r
}

The benchmark results:

$ go test -v -bench=. -run=!
PASS
BenchmarkNewRectangleFL5          50      38272524 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleRL5          50      38195877 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleBL5         500       5428041 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleOL5        2000       1468944 ns/op     6340608 B/op          2 allocs/op
BenchmarkNewRectangleOL0       50000         34646 ns/op       55296 B/op          2 allocs/op

The optimal implementation looks faster; it uses about 96% less CPU time (1468944 ns/op vs. average 38234200.5 ns/op) and about 99.9% less heap allocations (2 allocs/op vs. 2049 allocs/op). It's even faster for a zero initial value (34646 ns/op vs. average 38234200.5 ns/op).

We should also check that small rectangles (2 by 3  with an initial value of 5) are also reasonable.

$ go test -v -bench=.
PASS
BenchmarkNewRectangleOS5    10000000           233 ns/op          57 B/op          1 allocs/op
BenchmarkNewRectangleOS0    10000000           206 ns/op          57 B/op          1 allocs/op

Go performance is continually being improved. The version at tip, which will be released as Go 1.4, incorporates some of the optimizations in bytes.Repeat. Currently, it doesn't include the special-case optimization for a zero initial value.

// bytes.Repeat returns a new byte slice consisting of count copies of b.
func Repeat(b []byte, count int) []byte {
    nb := make([]byte, len(b)*count)
    bp := copy(nb, b)
    for bp < len(nb) {
        copy(nb[bp:], nb[:bp])
        bp *= 2
    }
    return nb
}

For Go 1.4 and later versions, we can at least write:

func NewRectangle14(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    var a []byte
    if value == 0 {
        a = make([]byte, height*width)
    } else {
        a = bytes.Repeat([]byte{value}, height*width)
    }
    start, end := 0, width
    for i := range r {
        r[i] = a[start:end:end]
        start, end = end, end+width
    }
    return r
}

The results at tip for Go 1.4 are:

$ go version
go version devel +7d2e78c502ab Sat Jun 14 16:47:40 2014 +1000 linux/amd64
$ go test -v -bench=. -run=!
PASS
BenchmarkNewRectangleFL5        1000       2061854 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleRL5        1000       2054323 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleBL5         500       5276701 ns/op     6340608 B/op       2049 allocs/op
BenchmarkNewRectangleOL5        1000       1496754 ns/op     6340608 B/op          2 allocs/op
BenchmarkNewRectangleOL0       50000         32721 ns/op       55296 B/op          2 allocs/op
BenchmarkNewRectangleOS5    10000000           221 ns/op          57 B/op          1 allocs/op
BenchmarkNewRectangleOS0    10000000           194 ns/op          57 B/op          1 allocs/op
BenchmarkNewRectangle14L5       1000       1497511 ns/op     6340608 B/op          2 allocs/op
BenchmarkNewRectangle14L0       2000        803754 ns/op     6340608 B/op          2 allocs/op

The optimal implementation is still faster; it uses about 29% less CPU time (1496754 ns/op vs. average 2058088.5 ns/op) and about 99.9% less heap allocations (2 allocs/op vs. 2049 allocs/op). It's even faster for a zero initial value (32721 ns/op vs. average 2058088.5 ns/op).

In addition to the benchmarks, we could have used profiling.

File rectangle.go:

package rectangle

import (
    "bytes"
)

// For loop using a for clause
func NewRectangleF(height, width int, value byte) [][]byte {
    r := make([][]byte, 0, height)
    for i := 0; i < height; i++ {
        r = append(r, bytes.Repeat([]byte{value}, width))
    }
    return r
}

// For loop using a range clause
func NewRectangleR(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    for i := range r {
        r[i] = bytes.Repeat([]byte{value}, width)
    }
    return r
}

// Benchmark basic
func NewRectangleB(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    for i := range r {
        w := make([]byte, width)
        if value != 0 {
            for j := range w {
                w[j] = value
            }
        }
        r[i] = w
    }
    return r
}

func repeat(b []byte, count int) []byte {
    nb := make([]byte, len(b)*count)
    if len(b) == 1 && b[0] == 0 {
        return nb
    }
    bp := copy(nb, b)
    for bp < len(nb) {
        copy(nb[bp:], nb[:bp])
        bp *= 2
    }
    return nb
}

// Benchmark optimization
func NewRectangleO(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    a := repeat([]byte{value}, height*width)
    start, end := 0, width
    for i := range r {
        r[i] = a[start:end:end]
        start, end = end, end+width
    }
    return r
}

// Go version tip (go1.4)
func NewRectangle14(height, width int, value byte) [][]byte {
    r := make([][]byte, height)
    var a []byte
    if value == 0 {
        a = make([]byte, height*width)
    } else {
        a = bytes.Repeat([]byte{value}, height*width)
    }
    start, end := 0, width
    for i := range r {
        r[i] = a[start:end:end]
        start, end = end, end+width
    }
    return r
}

File rectangle_test.go:

package rectangle

import (
    "fmt"
    "testing"
)

type nrFunc func(height, width int, value byte) [][]byte

func testNewRectangle(t *testing.T, nr nrFunc) {
    /*
        #!/usr/bin/env ruby
        HEIGHT = 2
        WIDTH = 3
        array = Array.new(HEIGHT){ Array.new(WIDTH){ 5 } }
        # [[5, 5, 5], [5, 5, 5]]
        print array
        print "\n"
    */
    height, width, value := 2, 3, byte(5)
    r := nr(height, width, value)
    if len(r) != height || cap(r) != height ||
        len(r[0]) != width || cap(r[0]) != width ||
        fmt.Sprintln(r) != "[[5 5 5] [5 5 5]]\n" {
        t.Error("Invalid rectangle:", r, fmt.Sprint(r))
    }
}

func TestNewRectangle(t *testing.T) {
    var tests = []nrFunc{
        NewRectangleF, NewRectangleR,
        NewRectangleB, NewRectangleO, NewRectangle14,
    }
    for _, test := range tests {
        testNewRectangle(t, test)
    }
}

var (
    smallHeight = 2
    smallWidth  = 3
    largeHeight = smallHeight * 1024
    largeWidth  = smallWidth * 1024
    zeroValue   = byte(0)
    fiveValue   = byte(5)
)

func BenchmarkNewRectangleFL5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleF(largeHeight, largeWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangleRL5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleR(largeHeight, largeWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangleBL5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleB(largeHeight, largeWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangleOL5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleO(largeHeight, largeWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangleOL0(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleO(largeHeight, smallWidth, zeroValue)
    }
    _ = r
}

func BenchmarkNewRectangleOS5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleO(smallHeight, smallWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangleOS0(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangleO(smallHeight, smallWidth, zeroValue)
    }
    _ = r
}

func BenchmarkNewRectangle14L5(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangle14(largeHeight, largeWidth, fiveValue)
    }
    _ = r
}

func BenchmarkNewRectangle14L0(b *testing.B) {
    b.ReportAllocs()
    var r [][]byte
    for i := 0; i < b.N; i++ {
        r = NewRectangle14(largeHeight, largeWidth, zeroValue)
    }
    _ = r
}


Assorted things pop into my head here.

What's wrong with using the String.Substring(Int32) method?
At first glance, I would tend to think your 2nd method would be faster, but they really aren't the same.  If input i is greater than test.Length, the 2nd method will throw an exception but the first method would return an empty string.
I'd suggest having the test string be the first parameter since it's really the object that you are processing upon.  Plus you could then make them static extension methods to the input string.

EDIT - Adding extension method:

namespace System
{
    public static class GiladStrExt
    {
        public static string ApplySubString(this string value, int startIndex)
        {
            // You can invoke an extension method as a straight-up call,
            // e.g. GiladStrExt.ApplySubString(test, 5) and the value
            // for test could be null.
            if (value == null) throw new ArgumentNullException("value");
            if ((value.Length == 0) && (startIndex == 0)) return string.Empty;
            // Usually one uses the extension method with non-null values
            // so all we need to worry about is startIndex compared to value.Length.
            if ((startIndex < 0) || (startIndex >= value.Length)) throw new ArgumentOutOfRangeException("startIndex");
            var sb = new StringBuilder();
            for (int i = startIndex; i < value.Length; i++)
            {
                sb.Append(value[i]);
            }
            return sb.ToString();
        }
    }
}


Finding the string from the list of array objects

Because the question is about performance and efficiency that's why some sort of benchmarking would be essential to compare different implementations. I have found BenckmarkDotNet really useful for these kind of experiments.

You can define the for loop version as your baseline and the tool will compare the other implementation against that. Here is my simplified example how to setup your environment for measurement:

[HtmlExporter]
[MemoryDiagnoser]
[SimpleJob(BenchmarkDotNet.Engines.RunStrategy.ColdStart, targetCount: 100)]
public class IterationOptimalizationExperiment
{
    private static List<Data> target;
    private const string TheOne = "TheOne";

    [GlobalSetup]
    public void Setup()
    {
        target = Enumerable.Range(0, 10000)
            .Select(i => new Data { Id = i, Type = i % 7777 == 0 ? TheOne : "NotTheOne" })
            .ToList();
    }

    [Benchmark(Baseline = true)]
    public void WithFor()
    {
        bool hasFound = false;
        for (int i = 0; i < target.Count; i++)
            if (string.Equals(target[i].Type, TheOne, StringComparison.OrdinalIgnoreCase))
            {
                hasFound = true;
                break;
            }

    }

    [Benchmark]
    public void WithForEach()
    {
        bool hasFound = false;
        foreach (var t in target)
            if (string.Equals(t.Type, TheOne, StringComparison.OrdinalIgnoreCase))
            {
                hasFound = true;
                break;
            }
    }

    [Benchmark]
    public void WithAny()
    {
        bool hasFound = target.Any(t => string.Equals(t.Type, TheOne, StringComparison.OrdinalIgnoreCase));
    }
}

And you should simply call the following command to start your experiment: BenchmarkRunner.Run<IterationOptimalizationExperiment>();

When you run it in Release mode it will dump something like this:


LeetCode: Best Time to Buy and Sell Stock II

Performance

Your solution is a single pass with time complexity \$O(n)\$. It's a small variation of the proposed solution.

Conventions

use static when no instance state/operations are used
use a clear, non-abbreviated method name CalculateMaximumProfit
always guard against bad user input in public methods
prefer the use of var when the type is obvious when reading the code
prefer whitespace between operands and operators prices.Length - 1
clean up waisted whitespace (in this case, after the return statement)

applied to your code:

 public static int CalculateMaximumProfit(int[] prices)
 {
     prices = prices ?? throw new ArgumentNullException(nameof(prices));
     var max = 0;
     for (var i = 0; i < prices.Length - 1; i++)
     {
         if (prices[i] < prices[i + 1])
         {
             max += prices[i + 1] - prices[i];
         }
     }
     return max;
 }


Implementation is good indeed, but I have some reservations calling it fast. Its complexity is O(n). As usual (including, but not limited to, Project Euler), an ultimate optimizer is math. Recall that

  $$ 1 + 2 + \ldots + n = \frac{n(n+1)}{2}$$

and

  $$ 1^2 + 2^2 + \ldots + n^2 = \frac{n(n+1)(2n+1)}{6}$$

so the result

  $$ \frac{n^2(n+1)^2}{4} - \frac{n(n+1)(2n+1)}{6} = \frac{(n-1)n(n+1)(3n+2)}{12}$$

can be achieved in O(1) time.


Java 8 String Unique Permutations in Parallel

The presented way is not a functional solution. It uses streams but it relies on forEach, which is the imperative way of using a Stream.

To make it better, we need to think about what we really want to do. We want to build all the permutations of the characters in a String. That means we need to have a method permutations(String) that will return all the permutations. Using Java 8, we can return a Stream<String> which will corresponds to the Stream of all the permutations.

To build those permutations, we can have a recursive algorithm:

If the String is empty, there are no characters, so the only result is a Stream that contains the empty String. This is the base case.
If the String is non-empty:

we remove the first character, build all the permutations without it and then prepend the first character to all the results.
then we remove the second character, build all the permutations without it and then prepend the second character to all the results.
etc. until we hit the last character.

Using Java 8, this is an implementation:

public static Stream<String> permutations(String str) {
    if (str.isEmpty()) {
        return Stream.of("");
    }
    return IntStream.range(0, str.length())
                .boxed()
                .flatMap(i ->
                  permutations(str.substring(0, i) + str.substring(i+1)).map(t -> str.charAt(i) + t)
                );
}

The base-case is handled by the if: when the String is empty, we return Stream.of(""): a Stream that contains only the empty String/

The main part is after: we create an IntStream over the indexes of the String. (Since there are unfortunately no flatMapToObj operation, we need to box each int into an Integer.) Then that's where the magic happens: for each index, we recurse by building all the permutations again, leaving the index i, and each of the result is mapped to prepend the character at index i. Since this recursive call returns a Stream<String>, this result is flat mapped (with flatMap) to have a single Stream.

With this utility method, your code is then just

permutations("ferrao").forEach(System.out::println);

That brings also a big advantage: the method is returning a Stream<String>, that is to say, the method does not actually perform the calculation. It is then up-to the caller to decide when to do it, if they want it to happen in parallel or not, and especially what the end container will be (a List, a Set, no container at all with just post-processing afterwards).

For example, to have it performed in parallel, you just need to do

permutations("ferrao").parallel().forEach(System.out::println);


A few minor notes (looks pretty good for the most part!):

Your most_significant_bit() function loop should be condensed into a for loop.  The main difference between the for's and the while's is a matter of pragmatics: we usually use for when there is a known number of iterations (which might not seem like the case here, but it's true), and use while constructs when the number of iterations in not known in advance.
I'm not a fan of you using -h as the command line argument equivalent to --hex.  Whenever I think of -h, I think of it as the shorthand of --help.  A better shorthand would be -x in my opinion.
Why do you do current_char_count += 1?  Why not current_char_count++/++current_char_count (both do the same thing in the same amount of time in this case)?


Algorithm to determine if binary tree is a Binary Search Tree (BST)

You can tremendously reduce the memory requirements of this code by acknowledging that you can replace the lists you use by single values:
private static bool IsBinarySearchTree(Node root, int max, int min)

this allows you to successively tighten the bounds on subtrees without storing the values you traversed in a list:
public static bool IsBinarySearchTree()
{
    var valid = true;
    // could be simplified to a single expression, but this is easier to understand
    valid &= IsBinarySearchTree(_root.Left, _root.Value, Int.MIN_VALUE);
    valid &= IsBinarySearchTree(_root.Right, Int.MAX_VALUE, _root.Value);
    return valid;

}

This should already be enough to write the recursive method and I think you'll learn more if I don't spoil this for you :)
But if you want a spoiler...

 private static bool IsBinarySearchTree(Node root, int max, int min)
 {
      // if there's no node
      if (root == null)  return true;
      if (root.Value <= min || root.Value >= max)
      {
          return false;
      }
      return IsBinarySearchTree(root.Left, root.Value, min)
        && IsBinarySearchTree(root.Right, max, root.Value);
 }

This simplification is possible because you only need store the smallest larger element and the largest smaller element to be able to guarantee that relation holds for the node you're currently examining.


Displaying a single record based on DocID

Starting with SQL 2008 there is a window function that does this nicely.

900,000 records even with lack of index that seems like it should be faster.

I doubt moving the condition into the join will fix the performance but it is worth a try.

SELECT TOP 1 t.Register
  FROM PxStats AS s
 INNER JOIN Therapy AS t
    ON s.ID = t.ID
   AND s.Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
   AND t.DocID = 1
 ORDER BY s.Time DESC;

If you can post the query plan.

If you remove the top 1 on average how many records would be returned?

A reach but try

declare @today datetime = (select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())));

SELECT TOP 1 t.Register
  FROM PxStats AS s
 INNER JOIN Therapy AS t
    ON s.ID = t.ID
   AND s.Date = @today
   AND t.DocID = 1
 ORDER BY s.Time DESC;


Some suggestions:

_recursive isn't a particularly descriptive name. A lot of things can be recursive. _relpoly_recursive may be a better name.
You can factor out the Poly call

s = sympy.Poly(p*rec_contracted + (1-p)*rec_deleted, p)

also note that I've removed the redundant parentheses.
Calling simplify on the result is completely useless, since rel is a Poly and Poly instances are always stored in canonical (expanded) form.
What is the value of going through the edges randomly? Don't you end up going through all of them.
As I noted in a comment, modifying the graph in-place seems problematic. I can't tell for sure just by looking at the code if it does the right thing or not. It seems that you should rather move the

H = nx.MultiGraph(G)

line to the top of the recursive function, and operate on H instead of G in the function.


Fetch and append player statistics to an Excel spreadsheet

As we can see these piece of code is repeated:

response = send_request('2017-2018-regular', value).content
df1 = pd.DataFrame(['Title'])
df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
df2.to_excel(writer, key, startrow=start_row+2, index=False)

you can define a function for it, it works like this:

def create_and_update_worksheets():
    def less_repetitive(value, start_row):
        response = send_request('2017-2018-regular', value).content
        df1 = pd.DataFrame(['Title'])
        df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

        df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
        df2.to_excel(writer, key, startrow=start_row+2, index=False)
    ...
    for key, value in worksheets:
        ...
        if isinstance(value, tuple):
            for subkey, subvalue in value:
                less_repetitive(subvalue, start_row)
                start_row += len(df2) + 4
        else:
            less_repetitive(subvalue, start_row)
    ...

Another solution is change the value in worksheets to be all tuple, but I am not sure if it works. As you didn't use the subkey, in such situation those value is not tuple now, can be changed to (('', value))

and as you don't need use subkey just replace it with _
code works like this:

def create_and_update_worksheets():
    ...
    for key, value in worksheets:
        ...
        if not isinstance(value, tuple):
            value = (('',value))

        for _, subvalue in value:
            response = send_request('2017-2018-regular', subvalue).content
            df1 = pd.DataFrame(['Title'])
            df2 = pd.read_csv(io.StringIO(response.decode('utf-8')))

            df1.to_excel(writer, key, startrow=start_row, header=None, \
                     index=False)
            df2.to_excel(writer, key, startrow=start_row+2, index=False)
            start_row += len(df2) + 4

    ...


Error handling for an Erlang 2D point class

I think the concerns about redundancy and verbosity are probably well placed.
andalso
The short circuiting logical AND is andalso. It can be used to simplify the code:
is_point({X, Y}) -> is_number(X) andalso is_number(Y).

Generally, the pattern:
// pseudo code
if f(x)
  return true
else
  return false

can be replaced with return f(x). Or in languages like Erlang where everything is an expression, f(x) alone is sufficient.
Atoms
In Erlang, it is idiomatic to use atoms as the first level of data validation:
is_point({point, X, Y}) -> is_number(X) andalso is_number(Y).

More importantly, it aids in readability and debugging. Atoms let points be distinguished from football scores:
1> point:is_point({point, 3, 2}).
true
2> point:is_point({football_score, 3, 2}).
** exception error: no function clause matching
point:is_point({football_score,3,2})
(/erlang/point.erl line 4)

Note that using atoms and good function names provides most of what we want to start debugging this type of problem. Football scores are not points and "letting it crash" provides better information than badarg.
Message passing
Labeling data with atoms lets us distinguish {rhombus, P1, P2} from {rectangle, P1, P2} and {circle, P1, P2}.
Try-catch
Taking error handling code out of point:is_point is consistent with the "unwritten code is bug free" heuristic. If crashes are problematic, the caller should wrap the call to point:is_point/1 in a try-catch-finally block. The caller can handle the exception at whatever granularity it needs. And we can avoid the close coupling that coordinated error handling requires whenever the defaults are good enough.


Checking for existing key in multi-dimensional array

You can just do this!

if (isset($array["message"]["action"])) { /*...*/ }

Proof:

<?php

error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);

$array = [
    "id" => 1,
    "name" => "foo",
    "message" => [
        "action" => "PUT",
    ],
];

var_dump(isset($array["message"]["action"])); // true

$array = [
    "id" => 1,
    "name" => "foo"
];

var_dump(isset($array["message"]["action"])); // false

No log entries.

Do note that if your value is null, then isset will also return false. You probably shouldn't be creating values with null.


You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).

Here is the improved code:

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y

print("Select operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

functions_dict = {
    '1': [add, '+'],
    '2': [subtract, '-'],
    '3': [multiply, '*'],
    '4': [divide, '/']
}

while True:
    choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
    if choice == 'q':
        break
    elif choice in functions_dict:
        num1 = int(input("Enter first number: "))
        num2 = int(input("Enter second number: "))
        print('{} {} {} = {}'.format(
            num1,
            functions_dict[choice][1],
            num2,
            functions_dict[choice][0](num1, num2)
        ))
    else:
        print('Invalid number')


Allowing messages to be passed to listeners

Personally I prefer polymorphism instead of conditions in such cases, as it helps to keep big conditions in a clean fashion - each condition in it's own class. As an example, in .NET they have generic event-handlers (subscribers) and following class system takes place (or something along these lines):

abstract class EventArgs { ... } // your abstract data class, Message if you will
class MyEventArgs : EventArgs { } // and it's implementation

abstract class EventHandler<T> // an abstract Subscriber
{
    public abstract Notify(T args); // Subscriber::notify() in your example
}

class MyEventHandler : EventHandler<MyEventArgs>  // an implementation of a subscriber for one specific case, which would be MyEventArgs
{
    public Notify(MyEventArgs args) { ... }
}


The update_cells call can update multiple cells at once. So you should calculate all new values locally and push the changes in one update. This should use only one token, instead of one per cell (untested code):

def update_sheet(sheet, table, start='A', end='C'):
    to_update = []
    for i, row in enumerate(table):
        cells = sheet.range(f'{start}{i+4}:{end}{i+4}')
        for cell, value in zip(cells, row):
            cell.value = value
        to_update.extend(cells)
    sheet.update_cells(to_update)

I also changed the names and indentation to follow Python's official style-guide, PEP8, and used an f-string for easier string formatting.

This still has the problem that it needs to get each row from the sheet, each of which does an API call. Instead you can get each column as a range and update one column at a time, which saves calls if your table has less columns than rows. For this we need to transpose the table first, though:

def update_sheet(sheet, table, columns="ABC", header=4):
    to_update = []
    table = list(zip(*table))    # transpose the table
    for col_name, col in zip(columns, table):   # iterating over columns now
        r = f"{col_name}{header}:{col_name}{len(col)+header}"  # changed range
        print(r)  # for debugging
        cells = sheet.range(r)
        for cell, value in zip(cells, col):
            cell.value = value
        to_update.extend(cells)
    sheet.update_cells(to_update)

With this it is no problem to use e.g. this table of size 2500 x 3:

import numpy as np

...
table = list(map(list, np.arange(2500*3).reshape(-1, 3).astype(str)))
update_sheet(sheet, table)


SQL query where id=… or id=… or id=… etc

The way to write that query is:

SELECT * FROM member_copy WHERE id IN (17579, 17580, 17582);

However, the real question is, where did that list of ids come from?  If the list of ids is the result of another database query, then you should be doing either a subselect or a join instead.


Your proposed getFeasibleNeighbours doesn't modify the two parameters. The visited array isn't modified at all. The cf is modified by the union-find process, but that's really more of a caching then a modification. So there isn't any concerns about the parameters of getFeasibleNeighbors.

} while (!feasibleNeighbours.isEmpty());

There doesn't seem to be any point in checking this here. It can't possibly have changed since you checked it in the middle of the loop.

while(!(feasibleNeighbours = getFeasibleNeighbours(CG, visited,  uf)).isEmpty()) {

You can do something like this, but I find it rather ugly.

In the general case of break-in-the-middle loops you have something like:

get_stuff_ready();
while(1)
{
     do_stuff_before();
     if( !some_test() )
           break;
     do_stuff_after();
}

This equivalent to:

get_stuff_ready();
do_stuff_before();
while( some_test() )
{
     do_stuff_after();
     do_stuff_before();
}

This does repeat do_stuff_before() twice. However, you can often combine get_stuff_ready() and do_stuff_before().

So you could something like:

private static List<ConstrDirectedEdge> kruskalConstruct(ConstructionDigraph CG) {

    int current = CG.srcVertexIndex();
    boolean visited[] = new boolean[CG.V()];
    visited[current] = true;
    UF uf = new UF(CG.V());
    List<ConstrDirectedEdge> solution = new ArrayList<ConstrDirectedEdge>();
    List<ConstrDirectedEdge> feasibleNeighbours = getFeasibleNeighbors(CG, current, uf);

    while( !feasibleNeighbours.isEmpty() )
    {

        ConstrDirectedEdge pickedUp = pickNeighbour(feasibleNeighbours);
        current = pickedUp.to();

        visited[current] = true;
        uf.union(CG.getVertex(current).getSource(),   CG.getVertex(current).getDestination());
        solution.add(pickedUp);

        feasibleNeighbours = getFeasibleNeighbors(CG, current, uf);
    }

    return solution;
}


Finding a vertex of a tree such that every subtree rooted at that vertex is of a uniform color

Some comments on the code:

for i in range(n-1):
    (u, v) = [int(i) for i in input().split()]

You are using i as the outer loop index, and i as the inner (list comprehension) loop index.  This is confusing, and should be discouraged.

The second line may be written more simply as:

    u, v = map(int, input().split())

The assignment:

colors = defaultdict(lambda: -1)

is overwritten by the code that creates the colors dictionary (below), and so can be removed.

You are changing the variable meaning in the following lines:

c = [int(i) for i in input().strip().split()]
colors = {i+1: v for (i, v) in enumerate(c)}

In the first line, i is a colour value; in the second line, v is the colour value and i is the index of the colour value.  For consistency, I'd used v instead of i in the first line.  Or get rid of the list comprehension index altogether:

c = map(int, input().strip().split())
colors = { i: v for i, v in enumerate(c, 1) }

Using enumerate(c, 1) eliminates the need to use i+1 as the key expression.

Is the .strip() necessary?

I'm not certain what the point of maintaining your visited set is.  Each time you start() a search from a new point, you are resetting the the visited set, and during any dfs(), you won't encounter a node you've already visited because the graph is guaranteed to be be a tree.  You just need to pass the start node for each dfs() step as a previous node (instead of a visited set) to prevent back-tracking.

Use better variable names.   I just figured out the nebs is an abbreviation for neighbours.

Faster solution hint:

I don’t believe a DFS is necessary.

Ignore all edges between vertices of the same colour
All other edges must share a common vertex (or Timofey will be annoyed)
Examine first two edges between different coloured vertices.  Continue with a linear search of remaining edges


Avoid using C Strings on C++ code to trim leading whitespace

Suggestions on your code:

Your code currently returns the input string unmodified if it contains nothing but spaces and tabs.  I'd say it should return an empty string.
You always use input.at(x) instead of input[x].  The former checks at runtime for out of range errors and in which case throws an exception, while the latter does not.  Your code ensures that you are calling them with valid indexes and no additional check is needed.
Your code begins with an if statement.

if ((input.empty()) ||
    ((input.at(0) != ' ') && (input.at(0) != '\t'))) {
    return input;
}

This special case looks redundant because your else branch already handles input that is empty or does not start with ' ' or '\t'.
Parentheses are welcome to clarify operator precedence, but you are using too many parentheses IMHO.  I would rewrite it like this:

if (input.empty() || (input[0] != ' ' && input[0] != '\t'))

I removed the parentheses around input.empty() (which is a postfix-expression), and input[0] != ' ' and input[0] != '\t' (which are equality-expressions).  I don't think people will take it wrong.
Your use of size_t instead of int is great.  In fact, std::string::size_type is guaranteed to be size_t.  However, you should use std::size_t instead of the unqualified size_t.  (See When using C headers in C++, should we use functions from std or the global namespace?)
s.substr(i) is equivalent to s.substr(i, s.size() - i), so instead of

return input.substr(pos, (input.length() - pos));

It suffices to write

return input.substr(pos);

You store the value of i to pos, break the loop, and then construct the return value based on pos.  This looks unnecessary to me.  Why don't you just directly return inside the loop when the desired i is found?

With these applied, your code is already only three lines:

for (std::size_t i = 0; i < input.length(); i++)
    if (input[i] != ' ' && input[i] != '\t')
        return input.substr(i);

(You still need to fix the trim("    ") == "    " bug.)

In fact, you can simply make use of the C++ standard library facilities and simplify your code even further:

std::string trim_left(const std::string& input)
{
    if (auto p = input.find_first_not_of(" \t"); p != std::string::npos)
        return input.substr(p);
    else
        return "";
}

If you cannot use C++17, move the declaration of p out of the if statement.


I recommend building the filter in steps, starting with an empty object {}. You then add attributes according to the selected city, category and date. And finally, you convert it to a JSON string via JSON.stringify(filter):

let filter = {};

if (this.selectedCity !== 'City') {
  filter.location = {
    city: this.selectedCity
  };
}

if (this.selectedCategory !== 'Category') {
  filter.category = this.selectedCategory;
}

if (this.fromDate !== '') {
  filter.date = {
    start: {'$gte': this.fromDate},
    end:   {'$lt':  this.toDate}
  };
}

this.filter = JSON.stringify(filter);


Graph represented by an adjacency matrix in C++

Your code looks reasonable, yet I have one suggestion: decouple algorithms from output:

std::vector<T> DFS(T const *start=nullptr) const {
    if(!adj_matrix.size())
        return std::vector<T>();
    if(start==nullptr) {
        return DFS_helper(get_random_node());
    } else {
        return DFS_helper(*start);
    }
}

std::vector<T> DFS_helper(const T& start) const {
    std::unordered_set<T> visited;
    std::unordered_map<T, T*> parents {{start, nullptr}};
    std::stack<T> s;
    std::vector<T> nodes;
    s.push(start);
    while(!s.empty()) {
        T top = s.top();
        s.pop();
        // If top is unvisited
        if(visited.find(top) == std::end(visited)) {
            // visit it
            visited.insert(top);
            nodes.push_back(top);
            for(const auto& adj_node: get_adjacent_nodes(top)) {
                s.push(adj_node);
                parents[adj_node] = &top;
            }
        }
    }
    return nodes;
}

Suppose what happens if your friend needs to run your DFS on a large graph. Most definitely, he or she will be overwhelmed with all the output. So, let the DFS return silently a list of visited nodes; only after that print the nodes if need be.


Design guideline for saving big byte stream in c#

You need to ask yourself 4 questions to start with:

How "big" is "big byte array"?
How fast is "very fast" ? Can we take 20 Hz as a design assumption?
Should data be appended in-order?
What is the expected overall size for a given file?

Just for the taste of it, appending 4MB to a file, on my 10 YO machine, takes less than 10 ms. A modern SSD and CPU will outdo this by an order of magnitude.

Anyway, knowing nothing, I would start with the most simple imaginable scheme, which is completely synchronous, and let it fail:

public static class FileSaver
{
    public static bool TrySaveData(byte[] data)
    {
        int dataOffset = 0;
        var file = GetFileName(data, out dataOffset);
        return TryAppend(file, data, dataOffset);
    }

    private static string GetFileName(byte[] data, out int offset)
    {
        string res = ...   // get the file name
        offset = ...       // depends on your format
        return res;
    }

    private static bool TryAppend(string file, byte[] data, int offset = 0)
    {
        try
        {
            using (var stream = new FileStream(file, FileMode.Append))
            {
                stream.Write(data, offset, data.Length - offset);
            }
            return true;
        }
        catch (Exception ex) { /* log some error */ }
        return false;
    }
}

Why is this good? Because by the time it fails, you'll be smart enough to answer 1-4, and then we would design something else based on real understanding of the problem.


Reviewing custom array List class of java

The CustomArrayList API is inconsistent because I can declare a list of type E to add elements of type E, but when I remove an element from it, I get an Object element:

public Object remove(int index) { /* ... */ }

Inside CustomArrayList you work with Object[] elementData. From the book Effective Java; Item 26 you could change your code to:

class CustomArrayList<E> {

  private E[] elementData;
  /* ... */

  public CustomArrayList() {
    elementData = (E[]) new Object[INITIAL_CAPACITY];
  }

  /* ... */

}

Inside remove you modify elementData in an imperative way. You could use System.arraycopy which would be more deklarative.

public Object remove(int index) {
 /* ... */
 Object removedElement = elementData[index];
 for (int i = index; i < size - 1; i++) {
   elementData[i] = elementData[i + 1];
 }
 /* ... */
}

public E remove(int index) {
  /* ... */

  if (size - 1 - index >= 0)
    System.arraycopy(elementData, index + 1, elementData, index, size - 1 - index);

  /* ... */
}

The methods get and remove contain a code duplication:

public E get(int index) {
 if (index < 0 || index >= size) {
   throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
  }
 return (E) elementData[index];
}

public Object remove(int index) {
 if (index < 0 || index >= size) {
   throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
 }

 Object removedElement = elementData[index];

 /* ... */

 return removedElement;
}

It is possible to invoke get inside remove like:

public E remove(int index) {
  E elementToRemove = get(index);

  if (size - 1 - index >= 0)
    System.arraycopy(elementData, index + 1, elementData, index, size - 1 - index);

  size--;

  return elementToRemove;
}


Just create a list of 18 ones and 18 twos, shuffle it, then reshape to 6x6:

from random import shuffle
from numpy import reshape

nums = [1]*18 + [2]*18
shuffle(nums)
arr = reshape(nums, (6, 6))

Produces (for example):

array([[1, 2, 2, 1, 2, 1],
       [2, 2, 2, 2, 2, 1],
       [2, 2, 2, 1, 1, 2],
       [1, 1, 1, 1, 2, 2],
       [2, 1, 1, 2, 1, 1],
       [1, 2, 1, 1, 1, 2]])


BigDecimal wrapper that ignores zero operands

There are big problems with your approach.

Cloning BigDecimal with .doubleValue() is broken

Cloning a BigDecimal bd using new BigDecimal(bd.doubleValue()) doesn't work in most practical cases.
For example, try this code:

BigDecimal bd = BigDecimal.valueOf(0.02d);
BigDecimal clone = new BigDecimal(bd.doubleValue());
System.out.println(bd);
System.out.println(clone);
System.out.println(bd.equals(clone));

On my computer the above code prints:

0.02
0.0200000000000000004163336342344337026588618755340576171875
false

The equality test fails for as simple values as 2d. It passes for a simple 2, but that's not very reassuring.

As such, your current implementation of cloning doubles is effectively broken, for example this test case fails:

@Test
public void multiply_2d_with_3d() {
    BigDecimalWrapper v = new BigDecimalWrapper(2d).multiply(BigDecimal.valueOf(3d);
    assertThat(v).isEqualTo(new BigDecimal(2d).multiply(BigDecimal.valueOf(3d));
}

You can fix it by replacing .doubleValue() with .toString(),
the unit test will pass.

Cloning BigDecimal is a strange thing to do

BigDecimal instances are immutable, so you can safely pass around copies.
Creating new instances is completely unnecessary.
Your current approach forces you to clone.
Since cloning is non-sense, this indicates a code smell,
and that a better solution is probably available.

Composition over inheritance

A better approach would be to avoid the strange cloning, by making the decorated object a final field in your wrapper class. Add a constructor that takes a BigDecimal, and call that one instead of super.

By the way, putting the decorated object into a field of the decorator class is the common technique when implementing this pattern (composition instead of inheritance). It makes it possible to nest multiple decorators in arbitrary order. Inheritance is a very tight coupling, composition gives you much more flexibility.

For example something like this:

class BigDecimalWrapper {

    private final BigDecimal bigDecimal;

    public BigDecimalWrapper(double num) {
        bigDecimal = new BigDecimal(num);
    }

    public BigDecimalWrapper(BigDecimal bigDecimal) {
        this.bigDecimal = bigDecimal;
    }

    public BigDecimalWrapper multiply(BigDecimal augend) {
        if (augend.compareTo(BigDecimal.ZERO) != 0) {
            return new BigDecimalWrapper(bigDecimal.multiply(augend));
        } else {
            return this;
        }
    }

    public BigDecimal bigDecimalValue() {
        return bigDecimal;
    }
}

Since the class no longer extends BigDecimal,
I added a bigDecimalValue() method to get access to the wrapped object.
The unit tests can be modified to work with this, and they pass:

@Test
public void shouldMultiply() {
    BigDecimalWrapper v = new BigDecimalWrapper(10).multiply(BigDecimal.ZERO);
    assertThat(v.bigDecimalValue()).isEqualTo(new BigDecimal(10));
}

@Test
public void multiply_2d_with_3d() {
    BigDecimalWrapper v = new BigDecimalWrapper(2d).multiply(BigDecimal.valueOf(3d);
    assertThat(v.bigDecimalValue()).isEqualTo(new BigDecimal(2d).multiply(BigDecimal.valueOf(3d));
}

You might not like that fact the BigDecimalWrapper is no longer a BigDecimal.
But maybe that's a good thing.
With your implementation,
if somebody ever tries to use a BigDecimalWrapper instance as a BigDecimal,
he might be surprised that multiplication with zero doesn't work as expected from a BigDecimal.
For this reason I think it's a good thing for BigDecimalWrapper to not pretend to be a BigDecimal.

If, however, you really want BigDecimalWrapper to be a BigDecimal,
then the most sensible solution is to keep your original implementation,
with doubleValue() replaced with toString().


Personally, I see no gain in abstracting SFML at this stage. In general I only see two situations where abstracting such a fundamental library really makes sense and that would be for:

If you want to fully test your code. In that case you need to be able to decouple from the "system" and thus from SFML.
If your engine has advanced to a stage where it isn't just a cheap tech demo, but actually something real, used for some real games. Only then does it make sense to think about, whether it would make sense to refactor the code base to potentially allow for different "backends".

Additionally, option 2 is rarely possible to do cleanly, since all the frameworks offer a different set of functionalities and switching between them with a single API on top, doesn't really work and limits the set of features to be used of said library.

As for your code and question, there's a reason why SFML splits font and text, texture and sprites, soundbuffer and sound, etc. The point is that you have a heavy resource (font, texture, soundbuffer) and a light "instance" object (text, sprite, sound). That way you can move, copy, manipulate the light instances all you want and not run into any issues performance wise, while the heavy resources need to be loaded once and then kept alive as long as the light instances are using it.

Your resource manager as such shouldn't hold on to text objects or sprites and instead just handle the heavy resources and ensure that they stay alive as long as they're used. I recommend to take a look at Thor's resource management well and Thor in general as it's a nice addition to SFML.

How you want to store text or sprites is up to you and depends on the kind of game. For most simple games, it's enough to save them directly in a game state class and if you need lots, then just use a std::vector but keep in mind the advantages and limitations of used containers.


So it looks like what you want is some sort of outer join.  I think this should work for you:

var categoryFilter = "Category1";
var query =
    from addon in dc.Addons
    select new
    {
        Addon = addon.Name,
        Amounts =
            from product in dc.Products
            where product.Category.Name == categoryFilter
            join productAddon in dc.ProductAddons
                on new { AddonId = addon.Id, ProductId = product.Id }
                equals new { productAddon.AddonId, productAddon.ProductId }
                into pas
            from productAddon in productAddons.DefaultIfEmpty()
            select (int?)productAddon.Amount ?? 0,
    };


You have a form -- by definition, a window in which text boxes and such can appear. Why are you using MsgBox and InputBox to communicate with the user?

If you instead put elements on the form and used those (particularly NumericUpDown), the code part would be so much simpler -- and far more like, well, a Windows app.

Watch this. Create a form, put three elements on it -- two NumericUpDown controls named GasAmountBox and DistanceBox, and one text control (text box or label, your choice really) named MileageOutput. Add other elements (like labels for the controls) to suit your taste.

Then, inside the form class, put something like:

Private Sub InputsChanged(sender As Object, e As EventArgs) _
  Handles GasAmountBox.ValueChanged, DistanceBox.ValueChanged
    If (GasAmountBox.Value = 0) Then
        MileageOutput.Text = "---"
    Else
        Dim mileage = DistanceBox.Value / GasAmountBox.Value
        MileageOutput.Text = mileage.ToString() & " MPG"
    End If
End Sub

Aaaaand done.

That's the entirety of the code you have to write to make the form work.  The controls take care of ensuring that the user inputs a number. You can even set the allowable range of values, so you don't have to care about negative numbers. You can add some code to, say, round the output, if you want.


Printing dynamic ascii-art shapes based on user input

I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice?

You can't do much better, since Python doesn't have the equivalent of a C-style do/while.
This is a trivial program so I doubt it's even worth adding functions (etc.); the one thing that can be improved is
if (z >= 0 and z <= 20):

can be
if 0 <= z <= 20: