I have found myself doing code duplication from time to time, and often will find them in the code. It screams at you "fix me!".

I would recommend a book, Refactoring by Martin Fowler on Amazon. It is an excellent resource and has step to step guides to refactoring code as the example you provided here.

Using Martin Fowlers techniques, I refactored the second half of your code step by step. The first thing was to simplify the conditionals:

if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-reset' )
     || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-reset' )
) {

Became a query instead:

if($this->isBulkReset()) {
...

protected function isBulkReset() {
    return $this->isBulkAction('bulk-reset');
}

protected function isBulkDelete() {
    return $this->isBulkAction('bulk-delete');
}

protected function isBulkAction($action) {
    return (isset($_POST['action']) && $_POST['action'] == $action)
    || (isset($_POST['action2']) && $_POST['action2'] == $action);
}

Next I looked at some similarities in the functions, like these two:

$delete_ids = esc_sql( $_POST['my_CheckBoxes'] );
$reset_ids = esc_sql( $_POST['my_CheckBoxes'] );

I changed them in both functions:

$recordIds = $this->getRecordIds();

foreach ($recordIds as $id) {
...
protected function getRecordIds() {
    return esc_sql($_POST['my_CheckBoxes']);
}

Next I joined the two functions:

 if($this->isBulkDelete() || $this->isBulkReset()) {
        $recordIds = $this->getRecordIds();

        foreach ($recordIds as $id) {
            if($this->isBulkDelete()) {
                self::delete_customer($id);
            } else {
                self::reset_record($id);
            }
        }

        wp_redirect(esc_url(add_query_arg()));
        exit;
    }

Then I noticed that $recordIds is a totally unnecessary temporary variable, so I removed it and just did the query directly in the foreach:

if($this->isBulkDelete() || $this->isBulkReset()) {
    foreach ($this->getRecordIds() as $id) {
        if($this->isBulkDelete()) {
            self::delete_customer($id);
        } else {
            self::reset_record($id);
        }
    }
    wp_redirect(esc_url(add_query_arg()));
    exit;
}

This is how it typically progresses, small steps. But in the end, you will have more separation and cleaner code. The big secret here is that as you progress, you will see new ways in organising your code that you could not see before.

Heads up! This code is untested, simply example refactoring techniques.


Triggering methods that change instance state on other objects using a Dictionary

This looks ok to me on first glance.

I can only suggest the use of an Enum to strongly type the events that you are registering.

This allows you to search the code base quickly and avoids any typo's you may make:

    private string instanceVar;
    private Dictionary<string, Action> eventHandlers;

    public TestObject(string newInstanceVar)
    {
        this.instanceVar = newInstanceVar;
        eventHandlers = new Dictionary<Events, Action>();
        eventHandlers.Add(Events.event0, PrintInstanceVar);
        eventHandlers.Add(Events.event1, InstanceVarToUpper);
        eventHandlers.Add(Events.event2, ChangeOwnInstanceVar);
    }

    public enum Events
    {
        event0,
        event1,
        event2
    }


Your first question: you could make range return a list of bigints, and reduce over it

(reduce * (range (bigint 1) 101))

your second question: :

you dont have to explicitly use seq, clojure will automatically treat your string as a seq
you dont have to use the full-blown string to number converter, you could for example use int to get the char code:

(map #(- (int %) (int \0)) "1234")`

for other ways of getting digits of a number, check out this thread


Counting occurrences of values in C Array (Shannon Entropy)

Firstly, you know the size of the number of buckets you want to use here, so there is no reason to use dynamic allocation (specifically, double *probabilityOfX = calloc(sizeof(double), 256);). This could simply be:

double probabilityOfX[256];
memset(&probabilityOfX, 0.0, 256);

You don't need to free this memory at the end then, either, reducing the possibility for memory leaks.

Of course, this is fine for small values (like what can fit in a uint8_t), however, using a uint32_t (or larger), this will pre-allocate a large array which could potentially be very sparse. In this case, what you actually want is a dictionary data structure (like a hashmap). Since C doesn't have anything like this inbuilt, I'm going to switch over to C++ so we can use std::unordered_map and some other nice things like std::vector (instead of raw uintx_t pointers):

double entropyOfDistribution(const std::vector<uint32_t>& vec)
{
    std::unordered_map<uint32_t, unsigned> counts;

    // Store the number of counts
    for(uint32_t value : vec) {
        ++counts[value];
    }

    double sum = 0.0;
    // Note the cast as otherwise we'll be doing integer
    // division and hence rounding to an int -
    // thanks @syb0rg for pointing that out.
    const double num_samples = static_cast<double>(vec.size());

    for(auto it = counts.begin(); it != counts.end(); ++it) {
        double probability = it->second / num_samples;
        sum += probability * log2(probability);
    }

    return -1.0 * sum;
}


You are improving, that's nice.
Since the project is quite minimal, I would just highlight few points for consideration.
Misleading variable names
words and out are misleading, what does out mean, your variables should explain themselves clearly and be as unambiguous as possible, words gives the intent of holding multiple words but actually, it holds just a word.
You might not need it
wrong list is totally unnecessary here, you might have implemented it for future purposes but right now, it isn't really used, define only what you are currently using. So it means guess in wrong is an irrelevant check
guessed happens to append only correct guesses, that's misleading, you might want to make it append both correct and wrong guess and it makes the variable wrong even more irrelevant.


A small printf-like function using variadic templates

I find this to be a sweet demo, but I don't like the traps in it for the unwary. Like you mention, there is little validation of parameter counts. There is also a chance that the same location can be replaced multiple times, e.g. with a call to ext::format("%1", "%2", "%3, "%4", "hi!") resulting in "hi!". Perhaps you might consider that a bonus.

What I find most surprising in the code is this:

std::string replacement_string{(std::ostringstream{} << val).str()};

I would probably have tended towards auto replacement_string{std::to_string(val)}; or, more likely, just embedded that in the call to regex_replace. Do you do this for compatibility with existing code that provides an overload for operator<< but not to_string?

Finally, I'm torn about the use of regex. It seems like a pretty big hammer without a lot of need, here, however it does keep the code short and sweet, and implicitly avoids an infinite loop that a flawed implementation might have with ext::format("%1", "%1").

Reviewing the tests, I find the Does_Not_Alter_Format_String test to be surprising as well. I would have thought the const qualifier would indicate this well enough.


Find the maximum number of consecutive zeros in an array

Just a few short comments on your code:

Separation of concerns:

You should separate functionality into different parts. Currently your main method does everything. For small applications like this, that may not be a problem, but as soon as you have larger applications, it becomes more and more unpractical.

You should thus extract your "logic" into a method:

private static int countSuccessiveZeros(int[] values) {
   int maxLength = 0;
   int tempLength = 0;
   //....
   // Looping here
   return maxLength;
}

Now if you wanted to not count zeros, but twos, you could simply modify the code to the following:

private static int countSuccessive(int[] values, int target) {
   int maxLength = 0;
   int tempLength = 0;
   //Your loop here, instead of 0 use target to compare
   return maxLength;
}

This also makes your main-method more readable:

public static void main(String[] args) {
   int[] values = {1, 2, 0, 0, 2, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7, 0};
   int successiveZeros = countSuccessive(values, 0);
   System.out.println("Maximum number of consecutive zeros : " + successiveZeros);
}

Naming:

Very nice, a compliment. Your variable names are short, clear, descriptive and follow Java conventions (camelCase). Keep it up ;)


The algorithm you have implemented is known as counting sort.  Its run-time cost is linear in the size of the input – faster than any comparison-based sorting algorithm can possibly get.  (At the cost of being also linear in the difference of the maximum and minimum element in the input.)  Congratulations if you've come up with this idea on your own.  Since they already give you the largest number in the array as additional input, it seems very likely that they wanted to see this algorithm.  (Of course, you can find the maximum yourself in linear time, if needed.)

Remarks about your code:

The rangePosition array is initialized with an exact copy of twentyMillion and then only ever read.  Why did you create it instead of using twentyMillion directly?
If twentyMillion contains a negative number, your implementation will explode.  Maybe you simply forgot to mention that all the inputs are guaranteed to be non-negative?  Otherwise, you'd also need to know the minimum value and normalize your keys to that.  (This could also help you save something if the minimum is much larger than zero.)
If the highestNumber is extremely large, you will get a problem.  For example, you will probably not be able to allocate a new int[Integer.MAX_VALUE] without receiving an OutOfMemoryError.  (And if you allow for negative numbers in the input, you might even need an array larger than Integer.MAX_VALUE!)  And even if you could allocate it, iterating over it will take forever.  If you want to make your code more robust, you could decide by some heuristic whether the combination of twentyMillion.length and highestNumber warrants the overhead of counting sort or you'd be better off using a comparison-based O(n log(n)) fallback-algorithm.
twentyMillion is a poor name for a variable that does not necessarily name an array of length 20M.


Import mess
You fail to bring GPIO into the namespace by using something along the lines of from RPi import GPIO. You also import time but don't use it. And you import everything from urlparse using from urlparse import *. This form is frowned upon as it polutes your namespace and may override something else. Better use import urlparse or from urlparse import urlparse, parse_qs.
Global layout mess
It is good practice to put top-level code into functions and call them in a if __name__ == '__main__' clause. That way you can start an interactive session and import your script for testing purposes without having code running as a side effect of your import:
def init_GPIO(ledpin=18):
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(ledpin,GPIO.OUT)

def init_webserver(port=8123):
    httpd = SocketServer.TCPServer(('0.0.0.0', port), MyRequestHandler)
    httpd.serve_forever()

if __name__ == "__main__":
    init_GPIO()
    init_webserver()

Note that I also turned your constants into parameters with default values. In this case it can make testing much more easier.
You also don't need your alias (Handler = MyRequestHandler) and can use the class directly.
Request handler
There is a more idiomatic way of checking if 'led' is in the query string; by using EAFP:
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        urlcomp = urlparse(self.path) # split url in components
        query = parse_qs(urlcomp.query) # Get args as dictionary
        try:
            led_state = query['led']
        except KeyError:
            pass
        else:
            turn_on = led_state == ["on"]
            GPIO.output(ledpin, turn_on)
        self.send_response(200)

It is recommended that you call the send_response method since, even if the raspberry-pi handled the request and turned the led on or off, your browser is still waiting for a reply of your webserver. Not calling self.send_response(200) should result in a timeout of your browser at some point.
If you want to send back data to the browser on top of the status code, you can write whatever content you want into self.wfile which will stream is to your browser. You can use it to make it simpler to control your raspi. You can also cusomize the message based on how you handled the action.
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        urlcomp = urlparse(self.path) # split url in components
        query = parse_qs(urlcomp.query) # Get args as dictionary
        try:
            led_state = query['led']
        except KeyError:
            message = "
No commands processed
"
        else:
            if led_state in (["on"], ["off"]):
                GPIO.output(ledpin, led_state == ["on"])
                message = "
Led turned {}
".format(led_state[0])
            else:
                message = "
Unknown action {}
".format(led_state)
        # Build links whatever the action was
        message += """

                      Turn on the led

                      Turn off the led

"""
        self.send_response(200)
        # Custom headers, if need be
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # Custom body
        self.wfile.write(message)

If you want to read the body from a file, just use regular python file manipulation:
with open('control.html') as html:
    self.wfile.write(html.read())


Writing to a file in Golang across concurrent go routines

Go doesn't guarantee atomicity ... so I built a simple Go interface to do that

Okay, but is your implementation atomic? The only atomic operations guaranteed to be atomic in Go are through the sync/atomic package (or things like func (*Cond) Wait under sync).

If you need true atomic write, use the atomic package. However, using log is usually sufficient.

Your implementation looks like it's trying to be concurrent, not atomic. Rather than rolling your own concurrent writer interface, use the standard API.

You're right, fmt (& os write functions, etc.) do not provide concurrency. However, the log package does.

You can see that they use mutex locks for the Output function, which is used by almost everything else.

This should perform nearly identical to your use case, because you open the file with O_APPEND, and log appends.

So open a file, and pass it to log.New().

For example:

package main

import (
    "log"
    "os"
)

func main() {
    f, err := os.OpenFile("testfile", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)

    if err != nil {
        log.Fatal(err)
    }

    logger := log.New(f, "", 0)
    logger.Output(2, "wow")
}


Sorting possibly unstable and general jsfiddle/jquery problem

You are using the built-in sort of Array, which is not guaranteed to be stable per the documentation. You will have to write your own sort algorithm from scratch.

Other than that,

It is considered better form to have a single comma separated var statement
Calling append() inside a loop gives poor performance, just collect everything in a string, and call append() once
You could cache $('#healthplans tbody') since you call it more than once
You should not skip the newline after an if statement
You should consider using hasOwnProperty when using for (item in dataSet[i])
You did not declare item with var
You call too many things item, I am assuming that the property in dataSet is more of itemId ?
All that gives this :

var applyData = function (dataSet) {
    var i,
        itemId
        item,
        itemRow,
        html = '';
        $table = $('#healthplans tbody'),

    $table.empty();
    for (i = 0; i < dataSet.length; i++) {
        itemRow = '';
        for (itemId in dataSet[i]) {
            item= dataSet[i][itemId];
            if (typeof item=== 'number')
              item= '$' + item;
            itemRow += '' + item+ '	';
        }
        html += '
' + itemRow + '
';
    }
    $table.append( html );
}

I did not comment on the sort function, since that most likely will be throw away.


Implementation of a deque using an array in Python 3

It's not clear at all to me what the mid pointer represents.  It doesn't seem like it stays in the middle of the array.
Why not use collections.deque?  https://docs.python.org/2/library/collections.html#collections.deque
Implementing an efficient deque is much easier with a linked list than with an array IMO.


Stack Exchange Data Explorer query to find upvoted questions with only downvoted answers

Answering your questions in reverse order…

Your HAVING clause is clearer than than an anti-join condition in the WHERE clause.  It is also more efficient — tick the "Include execution plan" checkbox to see how much more complicated the anti-join is.  You could do better, though:  MAX(a.Score) < 0 also means that all answers have a net negative score.

Given the choice between selecting MAX(q.Score) and grouping by q.Score, I'd prefer the latter.  Both are annoying, but the SQL standard requires that you do one or the other, so that all columns are either mentioned in GROUP BY or are aggregated.

I can provide some style tips, but keep in mind that these are my personal recommendations.  I don't believe that there is a standard SQL style guide — and certainly nothing as formalized as PEP 8.

Fill in the description to your Data Explorer query.  Otherwise, there is a huge gap between the information contained in the title and the SQL.  Detail exactly what the query does.  Mention your motivation for writing the query.  State what the sort order is.
Indent more.  The FROM, WHERE, GROUP BY, HAVING, and ORDER BY clauses are all subsidiary to the SELECT, and therefore should be at the next indentation level.
Finishing the query with a semicolon is a good habit.
Move comments to the right to be less obtrusive.
I like to put commas before the selected columns.  That convention makes it easier to add and remove columns.
Prefer comparing with 0 instead of comparing with any other constant.

SELECT q.Id AS [Post Link] -- Alias makes Data Explorer do magic link rendering
     , q.Score AS [Score]
     , COUNT(a.Id) AS [AnswerCount]
     , AVG(CAST(a.Score AS float)) AS [AvgAnswerScore]
    FROM Posts AS q
        INNER JOIN Posts AS a
            ON q.Id = a.ParentId
    WHERE
        q.Score > 0        -- Question has a positive score
    GROUP BY
        q.Id, q.Score
    HAVING
        MAX(a.Score) < 0   -- Best answer has a negative score
    ORDER BY
        [Score] DESC,
        [AnswerCount] DESC;

I'd like to point out: good job remembering to CAST(a.Score AS float) before taking the average.  SQL Server is tricky, in that AVG() of ints is an int.


According to the W3C (http://validator.w3.org/)

Your form tag is not valid.
Technically it must have an action attribute:

  required attribute "ACTION" not specified in:
  <form name="myForm" id="myForm">

  The attribute given above is required for an element that you've used, but you have omitted it.

There are a couple of warnings:

  Warning: NET-enabling start-tag requires SHORTTAG YES
  <input type="text" id="id" /   >
                                      ^^^  <!-- auto closing tag -->

  The sequence  can be interpreted in at least two different ways, depending on the DOCTYPE of the document. For HTML 4.01 Strict, the '/' terminates the tag '). However, since many browsers don't interpret it this way, even in the presence of an HTML 4.01 Strict DOCTYPE, it is best to avoid it completely in pure HTML documents and reserve its use solely for those written in XHTML.


Let's read a random Goodreads book in an optimal way

After I've gone through your code, I decided to rewrite it because using regex to parse html isn't a good idea at all.
When you're parsing html, is recommended to use BeautifulSoup, so I'll rewrite your code using it.

First, I'll start from the imports:
from bs4 import BeautifulSoup as bs
import requests

Nothing too fancy so far, we're importing the modules we need in order to have our work done.

You had in your code a magic number (30), which we can define at the top of our program, just below the imports:
MIN_RATING_COUNT = 30

You had other numbers in your code which didn't make sense to me, so I removed them. Just let me know what their purpose was (if any) if there's any difference between my proposed solution and yours.

Moving on, we can now build a function which returns a bs object on which we can later work.
def get_html_source():
    """Docstring here."""
    html_source = requests.get(URL).text
    return bs(html_source, 'html.parser')

Now, let's build another four functions which will get us the rating count, title, pages and rating of a random book.
def get_book_rating_count(soup):
    """Docstring here."""
    return soup.find('span', attrs={'class', 'value-title'}).get_text()

def get_book_title(soup):
    """Docstring here."""
    return soup.find('h1', attrs={'class': 'bookTitle'}).get_text()

def get_book_pages(soup):
    """Docstring here."""
    return soup.find('span', attrs={'itemprop': 'numberOfPages'}).get_text()

def get_book_rating(soup):
    """Docstring here."""
    return soup.find('span', attrs={'itemprop': 'ratingValue'}).get_text()

As I was testing this out, I've noticed that book_rating_count might have different value formats so let's build another function to treat each case:
def to_float(rating_count):
    """Docstring here."""
    rating = rating_count.split()[0]
    return float(rating.replace(',', '.'))

Regarding the title, we can build another function to nicely format it: remove the newlines in it and replace &amp; with &:
def format_title(book_title):
    """Docstring here."""
    return ' '.join(book_title.split()).replace('&amp;', '&')

Last, but not least, let's build our main function:
def main():
    """Docstring here."""
    while True:
        soup = get_html_source()
        book_rating_count = get_book_rating_count(soup)

        if to_float(book_rating_count) > MIN_RATING_COUNT:
            book_pages = get_book_pages(soup)
            book_title = format_title(get_book_title(soup))
            book_rating = get_book_rating(soup)

            print('Title: {}\n'
                  'Pages: {}\n'
                  'Rating: {}\n\n'.format(book_title, book_pages, book_rating))

If you're also going to terminate the program using CTRL + C, I suggest you put your main function into a try/except block.
try:
    main()
except KeyboardInterrupt:
    print("You've decided to close the program")

The final code:
from bs4 import BeautifulSoup as bs
import requests

URL = "https://www.goodreads.com/book/random"
MIN_RATING_COUNT = 30

def to_float(rating_count):
    """Docstring here."""
    rating = rating_count.split()[0]
    if ',' in rating:
        return float(rating.replace(',', '.'))
    return float(rating)

def format_title(book_title):
    """Docstring here."""
    return ' '.join(book_title.split()).replace('&amp;', '&')

def get_html_source():
    """Docstring here."""
    html_source = requests.get(URL).text
    return bs(html_source, 'html.parser')

def get_book_rating_count(soup):
    """Docstring here."""
    return soup.find('span', attrs={'class', 'value-title'}).get_text()

def get_book_title(soup):
    """Docstring here."""
    return soup.find('h1', attrs={'class': 'bookTitle'}).get_text()

def get_book_pages(soup):
    """Docstring here."""
    return soup.find('span', attrs={'itemprop': 'numberOfPages'}).get_text()

def get_book_rating(soup):
    """Docstring here."""
    return soup.find('span', attrs={'itemprop': 'ratingValue'}).get_text()

def main():
    """Docstring here."""
    while True:
        soup = get_html_source()
        book_rating_count = get_book_rating_count(soup)

        if to_float(book_rating_count) > MIN_RATING_COUNT:
            try:
                book_pages = get_book_pages(soup)
            except AttributeError:
                book_pages = 'No pages available'
            book_title = format_title(get_book_title(soup))
            book_rating = get_book_rating(soup)

            print('Title: {}\n'
                  'Pages: {}\n'
                  'Rating: {}\n\n'.format(book_title, book_pages, book_rating))

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You've decided to close the program")

If you let the above run for several minutes, you'll eventually get an AttributeError for the simple fact that some books don't have the number of pages, so I also added that into a try/except block.
Other changes that I've done:

I've added if __name__ == '__main__'
I've split the code in several functions so that each of them does its own job

Recommendations regarding your code-style:

in comments, there should be only one space after #;
there should be only one space before and after = operator;
instead of randomly using comments inside your code, just add docstrings to your functions (see PEP257 for more info);
instead of name = "He called me \"Bla\" again!" you can do name = 'He called me "Bla" again!' and vice-versa.

You can also read more about Python's style-guide, here.

Performance:
If you'll have many <30 books one ofter another, you don't have what to do but wait. As for your question regarding multithreading, threads only actually speed up I/O operations - because of the GIL.
CPU-bound operations (like the parsing/searching BeautifulSoup is doing) can't actually be done in parallel via threads, because only one thread can do CPU-based operations at a time. So you still may not see the speed up you were hoping for with this approach.
When you need to speed up CPU-bound operations in Python, you need to use multiple processes instead of threads. Luckily, you can easily do this using the multiprocessing module.


A standard way to do this is to break the function up into smaller 'private' (static) functions, each with one thing to do. One can pass the default to the counting function in case we are not provided the argument. This allows separation of the code which counts and the UI.

Total is always going to be called with (0, 0, 0), it's unnecessary to provide these arguments. In fact, the storage of Total in dynamic memory is probably unnecessary. No need to updateTotal, use of the counters directly is fine. In fact, there is going to be 1 total, might as well make it static.

fgetc returns an int, char ch is not enough to tell EOF, which is -1. You've defined BUF_SIZE, an excellent optimization, but never use it. I'd go from fgetc to fgets. Note that this assumes that the file is text and doesn't contain a '\0' inside, (eg, modified UTF-8.)

You've included getopt and unistd, making your code POSIX C99, but you're not using those. Removing them makes your code more general C99 (now your code will compile on more compilers.)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

//stores the Total count of lines words and bytes
struct Total {
    size_t lines, words, bytes;
} total;

//count the bytes, lines and words
//gives incorrect results on binary files with embedded 0
//a word is delimited by everything that {isgraph}
//using the unix definition of a text file, {lines = count('\n')}
static int readFile(FILE *fp) {
    char buffer[1024], b;
    int startWord = 1;
    size_t i;
    while(fgets(buffer, (int)sizeof buffer, fp)) {
        i = 0;
        do {
            b = buffer[i++];
            if(b == '\n') {
                /* This will not recognize '\l' in old Mac text files opened
                 with "wb"? Hmm. */
                total.lines++;
                startWord = 1;
            } else if(b == '\0') {
                break;
            } else if(isgraph(b)) {
                //if there's a visible char, there's a word
                if(startWord) total.words++, startWord = 0;
            } else {
                startWord = 1;
            }
        } while(1);
        total.bytes += i;
    }
    return ferror(fp) ? 0 : 1;
}

int main(int argc, char *argv[]) {
    FILE *fp = 0;
    char *fn = "<no file>";
    for(int i = 1; i < argc; i++) {
        fn = argv[i];
        fp = fopen(fn, "r");
        if(!fp || !readFile(fp)) break;
        fclose(fp), fp = 0;
    }
    if(argc <= 1) readFile(stdin);
    if(fp) fclose(fp);
    if(errno) return perror(fn), EXIT_FAILURE;
    /* https://stackoverflow.com/a/2524675/2472827 */
    printf("%zu lines; %zu words; %zu bytes total.\n",
        total.lines, total.words, total.bytes);
    return EXIT_SUCCESS;
}

Some see typedef struct as problematic, and, in my opinion, it's not needed here; see Linux kernel coding style. INT_MAX could be as little as 32,767; it's never going to be less than zero, so I'd prefer unsigned, or size_t in this context. What if there are other chars besides '\n', ' ', '\r', '\t'? I've included <ctype.h> to get rid of the ambiguity. There was a bug counting the word at the end of the line. Now, a line is defined as the number of '\n' (UNIX style.) A word is delimited by isgraph.


I find it more readable if you write the method like the following:

static bool TryParse(string quadDotted, out IpV4Address result)
{
    result = default(IpV4Address);

    if (quadDotted == null)
    {
        return false;
    }

    var elements = quadDotted.Split('.');
    if (elements.Length != 4)
    {
        return false;
    }

    var address = new byte[4];
    for (var i = 0; i < 4; i++)
    {
        if (!byte.TryParse(elements[i], out address[i]))
        {
            return false;
        }
    }

    result = new IpV4Address(address);
    return true;
}

or:

static bool TryParse(string quadDotted, out IpV4Address result)
{
    bool canParse = false;

    if (quadDotted != null)
    {
        var elements = quadDotted.Split('.');
        if (elements.Length == 4)
        {
            var address = new byte[4];

            // the following part can also be transformed in a do-while cycle
            canParse = byte.TryParse(elements[0], out address[0]);
            for (var i = 1; i < 4 && canParse; i++)
            {
                canParse = byte.TryParse(elements[i], out address[i]);
            }
        }
    }

    result = canParse ? new IpV4Address(address) : default(IpV4Address);
    return canParse;
}


Hi there thanks for sharing your code, I have a few comments/suggestions.

Implement the __str__ method

In your code, you have a method specifically designed to print out what your card looks like. Using card.print_card() the __str__ method is a special method designed to return a string representation of our object. In your case it would look something like this.

def __str__(self):
    return str(self.value) + " of " + str(self.suit)

Calling could would look like this

print(card)

Method Names

A lot of the method names you've chosen provide information about the class as well. If I want to print a Card object, to me it would make sense to say, card.print() and not card.print_card() I already know I'm dealing with a Card. This kind of sounds like it can print any card, not just the instance I'm dealing with.

Some more examples from your code

deck.show_deck() vs deck.show()

player.player_draws_card_from_deck() vs player.draw_card_from_deck()

Player IS a Deck

In your current code, you have a player class derived from a Deck. This means that every Player IS a Deck. To me it makes more sense to use composition over inheritance. I.e. a Player HAS a Deck. But even then, a player doesn't really have a deck either, they have a hand like you have in your example.

Your game can deal with players (with hands) and one or more decks. Players could be able to draw cards FROM decks. It could be 2 different decks, or all from one deck.

Consider the following.

player1 = Player("Bob")
player2 = Player("Jim")

deck = Deck(shuffled=true) # deck used by all players
discard_pile = Deck()

player1.draw_from(hand_size=5, deck)
discard_pile.add(player1.hand())
player2.draw_from(hand_size=5, deck)
discard_pile.add(plater2.hand())

Notice here how I created another Deck instance to act as the discard pile. Really a Deck is just a bunch of cards right? I Deck doesn't have a "playing" pile and a "discard" pile. What if my game doesn't ever discard cards? By having multiple decks to represent multiple piles of cards, then I have full control. So e.g. If I want to make a solitaire game, that could be represented by a number of smaller "decks" that get added to. The managing of when cards getting added/removed can be handled in some Game class.

Unneeded class variables

Consider these 2 methods

def draw_card_from_deck(self):
    self._draw_from_deck = self.card_list.pop()
    return self._draw_from_deck

def return_card_to_deck(self):
    self._return_to_deck = self.card_list.append(self._draw_from_deck)
    return self._return_to_deck

Implementing adding/removing cards like this severely limits flexibility. At the moment, the only card I can add back to the deck is the last one I took off. But what if I run into this scenario.

As a player, I want to take a card off the top of the deck, and replace it with a different card from my hand.

This seems like a fairly reasonable thing to want to do, but at the moment, as soon as I draw 2 cards without placing one back, that other card is gone forever as it's no longer the self._draw_from_deck value anymore.

What if I had code like this

card = player.draw(deck)
card_to_insert = player.get(Card(5, "Spades"))
if card_to_insert:
    deck.place(card_to_insert)

If I had the functionality to take any card object and place it to the deck, suddenly we don't need to worry about what the last card was to be taken or the last card that was put back (if we want these values we can of course still hold onto them)

General tips and things to watch out for

Consider this line self.shuffled_cards = random.shuffle(self.card_list) and now look at this documentation about the random.shuffle method here https://docs.python.org/2/library/random.html your code isn't doing what you think it's doing here. (hint, in-place)

In your list of values, you have a mix of data types, integers and strings. I would stick to just one data type per collection. Since you want to use strings to represent "Jack", "Queen" etc. I would stick with Strings for everything "1", "2", "3" etc. And parse the integer value from it where needed.

Using PEP8 standards, any method without a leading underscore can be considered "public" and I should be able to use freely and not need to worry about unexpected results. What happens if I do the following.

deck = Deck()
deck.construct_deck()
deck.construct_deck()
deck.construct_deck()
deck.show_deck()

We constantly append to the same list.

Being able to compare cards for equality would be useful, consider overriding the __eq__ and __hash__ methods. And if you want to be able to do card1 < card2, you can also override __lt__ and __gt__

Final Comments

My final suggestion would be, try and make a card game using what you've written. See what problems you run into, what works, what doesn't work. Something straight forward like War.

Hopefully you found this review helpful!


A bit of style

Before anything, let's rewrite/reorganise the code a bit to make it more pythonic but also easier to test.

Python has a style guide called PEP8. Among other things, you do not follow the naming and spacing conventions. You might find interesting to know that there are various tools to check your code (against PEP8 but also for various other things : pep8, pylint, pychecker, pyflakes and even tools to fix style automatically like autopep8.

Also, it is usual (and very useful) to use an if __name__ == '__main__': guard so that you have your definitions (classes, functions, constants, etc) on one hand and your actual program doing something on the other hand.

So far, your "improved" code looks like :

def reverse_number(a):
    degreMax = find_degree(a)
    result = 0
    while a != 0:
        r = a % 10
        a = a // 10
        result = result + r*10**degreMax
        degreMax = degreMax - 1
    return result

def find_degree(a):
    degre = 0
    while a >= 10:
        a = a/10
        degre = degre + 1
    return degre

def is_palindrome(a):
    test = False
    if reverse_number(a) == a:
        test = True
    return test

def next_palindrome(a):
    while not is_palindrome(a):
        a = a + 1
    return a

if __name__ == '__main__':
    nb_test = int(raw_input())
    inputs = []

    for i in range(0, nb_test):
        a = int(raw_input())
        inputs.append(a)
    # inputs = [5, 10, 303, 800]

    for i in range(0, len(inputs)):
        print next_palindrome(inputs[i])

So far, I haven't done anything relevant as far as performances are concerned and you might think I'm wasting your time here. I'm almost done.

More style

So far, I've done cosmetic changes. A few other changes can be performed to make your code more beautiful but also potentially faster (even if it is very subtle).

Python has a divmod function which does exactly what you are trying to do in reverse_number.
You don't need a temporary variable in is_palindrome.
You don't need to provide first argument to range if you start at 0 and step is 1.
You don't need temporary variable a in your main.
In Python 2 (which is the version I am guessing you are using), range creates a list which might be more than what you want. If you just need something to iterate on, xrange is what you need (in most cases this is what you need and it's why it is the behavior for range in Python 3).
It is the convention to name _ a variable whose variable is not used such as i in your code initialising the input list.
Whenever you are using range and len to iterate over a container, you are most probably doing something wrong. Python provides you a way to iterate over something that can hardly be easier :

for i in inputs:
    print next_palindrome(i)

It's easy/concise/hard to get wrong/fast.

to create a list and fill it, instead of having a boring loop and append, Python has a very expressive way to do it : list comprehension. If you have never read about them, make yourself a favor and just google it. In your case, defining your inputs gets down to this :

    inputs = [int(raw_input()) for _ in xrange(nb_test)]

you can use division assignment /= to write a /= 10 instead of a = a/10. Also (and this is more common), you can use += and -= in various places of your code.
you don't even need to store inputs into an array, you can just compute and print answers as you do over inputs.

At this stage, your code looks like :

def reverse_number(a):
    degreMax = find_degree(a)
    result = 0
    while a != 0:
        a, r = divmod(a, 10)
        result = result + r*10**degreMax
        degreMax -= 1
    return result

def find_degree(a):
    degre = 0
    while a >= 10:
        a /= 10
        degre += 1
    return degre

def is_palindrome(a):
    return reverse_number(a) == a

def next_palindrome(a):
    while not is_palindrome(a):
        a += 1
    return a

if __name__ == '__main__':
    nb_test = int(raw_input())
    inputs = [int(raw_input()) for _ in xrange(nb_test)]
    # inputs = [5, 10, 303, 800]

    for i in inputs:
        print next_palindrome(i)

User interface

A last note before diving into performances. It might be convenient to tell the user what you are asking him. Otherwise, one might think your program is just computing stuff when it is just waiting for input.

nb_test = int(raw_input("Nb tests? "))
inputs = [int(raw_input("Test ? ")) for _ in xrange(nb_test)]

Mesuring performances

In order to improve performance, it is best to be able to measure it while ensuring correctness. This can be achieved through unit tests. Without being bothered with a full unit testing framework, you can just write things like :

def unit_tests():
    assert next_palindrome(5) == 5
    assert next_palindrome(10) == 11
    assert next_palindrome(80) == 88
    assert next_palindrome(12345678) == 12355321
    assert next_palindrome(1234567890) == 1234664321
    assert next_palindrome(12345678901) == 12345754321
    # assert next_palindrome(123456789012) == ?? too slow..

As your code probably gets too slow for bigger inputs, it's a good option to add a few tests with huge inputs.

Improving performance

Finally!!

You'll probably be disappointed to see that most of the logic you've written can be rewritten using standard functions (this has been said by others):

def is_palindrome(a):
    s = str(a)
    return s == ''.join(reversed(s))

But for a more dramatic improvement, we'll have to look for a totally different algorithm, one that will be very efficient for very huge values. This can be done if you spot a pattern in the different solutions for the different tests we have written.

Let's consider a number with n digits : $$d1,d2,...,dn$$ and let's try to split it in the middle :

if n is odd, we have $$n = 2*k+1$$ and we have 3 parts : $$d1,d2,..,dk$$ in the piece of the left, $$dk+1$$ in the middle, $$dk+2..dn$$ in the piece on the right. Based on the comparison of the left part and of the right part, the next palindrom the left part and its reversed with either dk or dk+1 in the middle.
if n is even, the same logic applies without a middle component.

A few edge cases are to be considered but the following code works on basic cases :

def next_palindrome(a):
    s = str(a)
    n = len(s)
    k, r = divmod(n, 2)
    if r:
        left, mid, right = s[:k], s[k], s[k+1:]
        assert len(left) == len(right) == k
        assert s == left + mid + right
        print(s, left, mid, right)
        mid_n = int(mid)
        if left:
            left_n, right_n, right_n_rev = int(left), int(right), int(right[::-1])
            if left_n > right_n and left_n > right_n_rev:
                return int(left + mid + left[::-1])
            else:
                return int(left + str(mid_n+1) + left[::-1])
        else:
            return mid_n # 1-digit number
    else:
        left, right = s[:k], s[k:]
        assert len(left) == len(right) == k
        assert s == left + right
        print(s, left, right)
        left_n, right_n, right_n_rev = int(left), int(right), int(right[::-1])
        if left_n > right_n and left_n > right_n_rev:
            return int(left + left[::-1])
        else:
            new_left = str(left_n + 1)
            return int(new_left + new_left[::-1])

I've tried (unsucessfully) to give meaningful names to variables.


Website for allowing data evaluation from submission

Perhaps the templates can be generated by a function.  Pass in a list of the attribute names, and it returns a template string.  Or pass in the table name, and query the column names to make the template.  Then use render_template_string() instead of render_template().

This code is rough and untested, but outlines what I'm thinking:

def column_headers(attrs):
    headers = (f'{attr.replace("_"," ").titlecase()}	'
               for attr in attrs)
    return '\n'.join(headers)

def columns(attrs):
    column_refs = (f'{{record.{attr}}}	' for attr in attrs)
    return '\n'.join(column_refs)

def make_template(attrs):
    template_string = ["""
        {% extends "records.html"%}
        {%block recordcontent%}

                """,
                column_headers(attrs),
                """

                {% for record in user_records.items %}

                    {{ loop.index }}
                    """,
                    columns(attrs),
                    """

                {% endfor %}

        {% endblock%}
        """]
        return '\n'.join(template_string)

FridgeFreezerTemplate = make_template("""
                                      unit_type
                                      temperature
                                      employee_name
                                      comment
                                      date_submitted
                                      """.strip().split())

@app.route("/unit_temp_records/<int:page_number>")
def unit_records(page_number):
    """
    records = pagiantion object
    page number = the current page

    """
    records = FridgeFreezerTempTable.query.filter_by(user=current_user).paginate(per_page=5,
             page=page_number, error_out=True)
    return render_template_string(FridgeFreezerTemplate, user_records=records, table=table)


Extension method for getting custom Principal Claim

Sometimes breaking things up into smaller manageable chunks makes them easier to swallow

Break the responsibilities up into more focused concerns.

public static class PrincipalExtension {
    /// <summary>
    /// Retrieves the Firm Id claim if it exists
    /// </summary>
    public static long? GetFirmId(this IPrincipal principal) {
        return long.TryParse(principal.FindFirstOrEmpty(nameof(User.FirmId)), out var firmId)
            ? firmId
            : default(long?);
    }
    /// <summary>
    /// Retrieves the first claim that is matched by the
    /// specified type if it exists, String.Empty otherwise.
    /// </summary>
    public static string FindFirstOrEmpty(this IPrincipal principal, string type) {
        return principal is ClaimsPrincipal p
            ? p.FindFirst(type)?.Value ?? string.Empty
            : string.Empty;
    }
}

FindFirstOrEmpty handles the finding of the claim value if it exists.

This allows the main function to perform its designed role.


Any identifier with two underscores is reserved for the implementation. Using such an identifier yields undefined behaviour. Change your include guard. Something along QUICKSORT_GAMDSCHIEE_H is perfectly fine.

The user interface of quicksort should only take a std::vector. That way one cannot use size() by accident:

void quicksort(std::vector<int> & v) {
    quicksort_impl(v, 0, v.size() - 1);
}

Make it hard to use your code in a wrong way.

You can return immediately in both partition and quicksort if ileft == iright and spare yourself some other if.

  I think instead of having swap.cpp I could've simply used std::swap, right?

Exactly, or at least re-use it:

void swap(std::vector<int> & v, int i, int j) {
    std::swap(v[i], v[j]);
}

Instead of int we should use std::vector<int>::size_type (which will be size_t usually).

There's no reason to limit your quicksort to std::vector<int> it works fine for any std::vector<T> as long as T provides operator<.

To your "faster quicksort algorithm" question: you can find a std::vector where quicksort will take \$\mathcal O(n^2)\$ instead of \$\mathcal O(n \log n)\$. It's average time complexity is \$\mathcal O(n \log n)\$. Mergesort on the other hand is always \$\mathcal \Theta(n \log n)\$ time complexity.

Usually std::sort will be fast enough for all your use cases.


Instead of selecting .open and .open2, you could change your selector to see if there is a child <ul>.

$('li:has(ul)').hover(function() {
  $(this).find('ul').slideDown(400);
}, function() {
  $(this).find('ul').slideUp(400);
})

Edit: you can also hide all the child <ul> nodes at once instead of individually.

$('li ul').hide();

Reference

Here are the three main features of jQuery that I used. Each link uses <api.jquery.com> which is a great place to learn about various jQuery functions.

:has() selector
.hover()
.find()


Majorly refactored my code, is this good enough?

Personally I'd make the UserFinder class source-independent.
This could be either by seeing the Xml and Test sources as a mapper and the UserFinder as a model (some kind of DataMapper):

public interface UserMapperInterface {}
public class XmlSource : UserMapperInterface { // ... }
public class TestSource : UserMapperInterface { // ... }

public class UserFinder {
     public UserFinder(UserMapperInterface $source) { // ... }
     public UserFinder() { // use default source }
}

This way you make the GetUserById method source-independent. Basic usage would be:

UserFinder t = new UserFinder(new TestSource());
// UserFinder t = new UserFinder(); // using the default source
t.GetUserById(43);

This way you seperate the source logic from the operations and you can easily add new sources without touching the UserFinder class.


Is this the rigth way to write power and factorial functions with nasm?

sub rsp, 0x10 ; Allocate 2 bytes on the stack

The comment is not correct! 0x10 is an hexadecimal number equal to 16 in decimal.

cmp rdi, 0 ; if == 0
jne power_init

If you need to compare with zero, it's usually better to test the register to itself:

test rdi, rdi
jnz  power_init

dec edi
cmp edi, 0
je power_end

The cmp edi, 0 instruction is redundant since the dec edi instruction already provides the necessary zero condition status.

  For example, by executing the functions I make some changes in the registers and I don't know if I have to revert them to their original value a the end with push and pop.

If you write these functions and your program uses these functions, then it's up to you to decide if you deem it useful to preserve any or all of the registers. If someone else will be using your functions your comments should make it absolutely clear what registers get clobbered!

The recursive factorial function can do without the prologue/epilogue code and is a bit complicated.

; IN (esi) OUT (eax) MOD ()
; Calculate eax = esi!
Factorial:
    mov  eax, 1
    cmp  esi, eax
    je   .return       ; esi was 1 -> eax = 1
    push esi           ; (1)
    dec  esi
    call Factorial     ; -> EAX
    pop  esi           ; (1)
    imul eax, esi
.return:
    ret

The power function can do without the prologue/epilogue code. There's no need to put ESI on the stack. If you want you could preserve the EDI register, but that's up to you to decide.

; IN (esi,edi) OUT (eax) MOD (edi)
; Calculate eax = esi ^ edi
Power:
                      ; push edi
    mov  eax, 1
    sub  edi, eax
    jb   .return      ; edi was 0 -> eax = esi^0 = 1
    mov  eax, esi
    jz   .return      ; edi was 1 -> eax = esi^1 = esi
.more:
    imul eax, esi
    dec  edi
    jnz  .more
.return
                      ; pop edi
    ret


My two most important remarks concern comments and global variables.

Python is a language that is designed to be easily readable.  Your three comments simply restate the obvious, and are therefore obnoxious or harmful.  (Redundancy simply doubles the burden of code maintenance, as you have to ensure that your comments are consistent with the code.)

The most important kind of documentation in Python is the docstring — and you didn't write any!

The use of global variables makes it difficult to understand and maintain your code.  The presence of a global variable means that a reassignment could have effects beyond the scope of a function.  That defeats one of the principal advantages of packaging code into functions, which is to make it clear what the inputs and outputs are for a particular chunk of code.

Simple rewrite

Your "restart" feature doesn't actually work.  I've removed it in the code below, and am leaving it as an exercise to you to fix it.

import time, random

def comment(human_equiv_age):
    """
    Print a remark based on the human-equivalent age.
    """
    if human_equiv_age < 25:
        print("You're a young cat or dog")
    elif human_equiv_age < 50:
        print("You're a middle aged cat or dog")
    else:
        print("You're an old cat or dog")

def main():
    """
    Ask the user for inputs to an animal age conversion, and print
    the result.
    """
    print("Welcome to the animal age calculator")
    time.sleep(1)
    choice = int(input(
        "Which age would you like to convert? (Enter the corresponding number)\n"
        "1. Human ---> Dog\n"
        "2. Human ---> Cat\n"
        "3. Dog ---> Human\n"
        "4. Cat ---> Human\n"
        "5. Generate a random human age\n"
    ))
    time.sleep(1)
    if choice == 5:
        print("You have chosen to generate a random human age.")
        time.sleep(1)
        print(random.randint(1,122))
        time.sleep(1)
    elif 1 <= choice <= 4:
        input_age = int(input("What age would you like to start with?\n"))
        if choice == 1:
            print("You have chosen Human ---> Dog and the Human age is", input_age)
            chrono_age = input_age
            human_equiv_age = 11 * chrono_age if chrono_age < 3 else 22 + (chrono_age - 2) * 4
            output_age = human_equiv_age
        if choice == 2:
            print("You have chosen Human ---> Cat and the Human age is", input_age)
            chrono_age = input_age
            human_equiv_age = 15 if chrono_age == 1 else 25 + (chrono_age - 2) * 4
            output_age = human_equiv_age
        if choice == 3:
            print("You have chosen Dog ---> Human and the Dog age is", input_age)
            human_equiv_age = input_age
            chrono_age = human_equiv_age / 11 if human_equiv_age < 33 else (human_equiv_age - 22) / 4 + 2
            output_age = chrono_age
        if choice == 4:
            print("You have chosen Cat ---> Human and the Cat age is", input_age)
            human_equiv_age = input_age
            chrono_age = 1 if human_equiv_age == 15 else (human_equiv_age - 22) / 4 + 2
            output_age = chrono_age
        time.sleep(1)
        print("Your new age is:", output_age)
        time.sleep(1)
        comment(human_equivalent_age)

main()

Some additional remarks:

Python supports double-ended inequalities, like 1 <= choice <= 4.  Note that I haven't used that feature in the comment() function, though.  Can you see the bug in your code, and why I didn't use double-ended inequalities there?
Make the distinction between calendar years and human-equivalent years clear.  Those two quantities don't really have the same units, and that made your comment() function messy.
Your formulae for choices 3 and 4 are the same.  Surely, the Cat→Human calculation is not the inverse of the Human→Cat calculation.

There are other changes I would make, but I'll leave it at this to keep the review simple.


Rspec test to confirm rejection of four invalid dates

The reason is that if this test fails, you'll have to separately determine which of the 4 sub-expectations has failed.

Depending on the output of your test reporter, this may or may not be a practical problem.

  This test is testing only one thing at a time (is obviously malformed input resulting in exceptions).

Actually, you're testing:

invalid digits raise an error
non-date characters raise an error
nil raises an error
negative numbers raise an error

That said, if you're essentially doing manual fuzzing and don't care about those distinctions -- though I'd say they seem useful in this particular case -- then I don't see an issue with this.

Testing rules and best practices are helpful, but don't get too bogged down in them.  If you know your own testing goals, and understand why it might be ok to depart from a best practice, by all means do so.


Window::Init() performs OpenGL initialization and creates the GL window, I do not completely agree with this: I'd avoid to perform expensive tasks inside ctor (which should, IMO, just initialize the object in a consistent state). Initialization may be done lazily when required (better, I think) or made explicit with a public Initialize() method (which has the disadvantage to be another function to call and the overhead of the checks to determine if it has been called or not but where you can use virtual functions without worries).

Your actual Window::Init() returns a bool which is simply unused. However when initialization fails the object is not in a valid state and any other function call may simply crash. Calling code has to any clue and it can't gracefully exit. Feel free to throw an exception (even easier if you have a separate Initialize() method) instead of returning a bool:

if (!glfwInit())
    throw std::runtime_error("GLFW failed to initialize.");

Also note that if you log something to console then errors should go to std::cerr instead of std::cout:

std::cerr << "ERROR::GLFW::INIT : GLFW failed to initialize" << std::endl;

If you properly handle error cases (instead of returning an unused flag to signal an error) then you do not need to repeat clean-up code in your initialization function because dtor will take care of it:

Window::~Window()
{
    if (m_IsInitialized)
        glfwTerminate();

    if (m_Window != nullptr)
        glfwDestroyWindow(m_Window);
}

About m_Window: why it's public? There is almost never a good reason to have a public field. Note that if, for any reason, you have to expose this pointer to the external world then I strongly suggest to use std::shared_ptr, you may also go one step further and implement a custom delete function that will call glfwDestroyWindow() (I think it's much easier to add few assertions in this case then track an access violation because memory has been released somewhere). Also this opens the door to more complex scenarios (for example using std::move() to transfer window ownership to another Window instance).

Jumping back to ctor, you can use an initializer list:

Window::Window(const char* title, int width, int height, bool vsync)
    : m_Title(title),
      m_Width(width),
      m_Height(height),
      m_VSync(vsync)
{
}

It does not really matter for PODs however you may (and should) declare all those members as const (and * const) then you must use this syntax.

You're not validating inputs, that's a bad thing! Is, for example, a negative width allowed? Throw the right exception as soon as possible and you won't need to hunt a bug later.

if (width < 0)
    throw std::invalid_argument("Width cannot be negatie.");


What's the point of catching a NullPointerException? When do you expect it to happen?
I don't really like that this method mutates the list passed in as a parameter - and then also returns it, even though the returned value is actually redundant as the calling code already has a hold of the now modified list. You're kind of sharing the result of the operation in two ways at once, which feels redundant.

And I know it's often done that way, but I think it's bad practice nevertheless, and can lead to confusion.

Personally I'd prefer to be more explicit about what's going on, and either a) make a deep copy of the original list, and return an independent version of it (with entries removed), without affecting the original one - or b) make this method void, like Collections.sort().

See command-query separation principle. Making a method look like a query can lead me to believe it's a pure function, with no side effects, whereas it actually does cause side effects, mutating the input data.
The name is very vague - "remove", remove what?
Is the blacklisted data ("FIRST", "SECOND", "THIRD") likely to ever change? In the spirit of making this code more modular I would consider extracting that list to a separate parameter.

Single responsibility principle indicates that a method should have one clear responsibility, and one could argue that filtering out certain entries and knowing the blacklist are two responsibilities. Your mileage may vary though, depending on the cnotext - which I don't know.
Not a biggie, but whitespace is out of control (iterator.hasNext();     ), catch(NUllPointerException e){}), not to mention it's NullPointer..., not NUllPointer.
Depending on how Column class is implemented, which I can't see - if it's a light-weight object and if its equals() method would compare Column instances by their value (getValue())... then we could leverage Collections.removeAll and save ourselves writing the iterative removal by hand.

Eg. assuming

class Column {
    private final String value;

    public Column(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public boolean equals(Object o) {
        // if a Column instance, compare it by value
    }

    // don't forget hashCode
}

we could just do that:

/* could be a Set actually since order doesn't matter,
 * only Set hasn't got such a convenient initializer in standard Java API */
private static final Collection<Column> BLACKLISTED_COLUMNS = Arrays.asList(
    new Column("FIRST"),
    new Column("SECOND"),
    new Column("THIRD"));

be it a constant, or a collection computed in run-time, doesn't really matter. And then it gets as simple as that:

List<Column> columns = // ... getting the data from wherever
columns.removeAll(BLACKLISTED_COLUMNS);

And that's it, job done. As I said, this solution may not be applicable in your case - I have no way of knowing.


Sample n items without replacement in Prolog

In SWI-Prolog you could do this that way:

sample_swi(Domain, N, Sample) :-
    random_permutation(Domain, Permutation),
    length(Sample, N),
    append(Sample, _, Permutation).

Be careful, this predicate is not a true relation (just as in your code).


Possible SQL injection vulnerability searching for a product by ID?

On demand -> issues mentioned in comments, reviewed & posted as an answer:

The answer to your question has already been given: Yes, you have a serious vulnerability, and the first step to solving this is using the extensions that aren't deprecated, like PDO  and mysqli.
Both of these extensions support the easiest, and pretty solid  (not perfect, but solid) prodection from injection attacks: prepared statements. Learn to use them, learn to love them.

The rest of your code is, I'm afraid to say pretty bad. A lot of the issues are the result of your using the mysql_*  extension, but there are other issues, too.
A line-by-line review pointing out issues as we go:

$pid = $_REQUEST['product_id'];

This statement can, and probably will at some point, produce notices. If the product_id parameter isn't set, you'll get an "undefined index" notice. When writing, and testing, new code, always set your error_reporting to E_STRICT | E_ALL (which, if you're running php 5.5+ will show E_DEPRECATED notices for your using the mysql_* extension). And set display_errors  to true, so you can See the problems. Anyway, always check if an index exists, before using it:

$pid = isset($_REQUEST['product_id']) ? $_REQUEST['product_id'] : null;

Next - Concatenating raw values into a query is never a good idea. Your query appears to have id = '<someValue>' as a WHERE clause, which suggests that id  is a string, but that wouldn't make sense. You're also assuming that the client will behave nicely, and not request a product_id  value that contains single quotes (which would mess up your query!). Nor do you seem to mind negative values, or any other non-valid input for that matter. Worst of all, its laughably easy for me to send a request that'll result in a valid query that performs a full table scan (a products table can be quite large, so this would be something that can be exploited in a DOS attack):

//the product_id value:
$pid = "1' OR '1";
//the resulting query would be
$query1 = "SELECT * FROM products WHERE id = '1' OR '1'";
//which, basically amounts to:
$query1 = 'SELECT * FROM products';

It's quite obvious that this is not what you want, you don't want your code to echo The product was found when you're actually querying to see if any product exists. Especially if that query basically selects all records in your table.
So this statement needs to be reworked:

$query1 = "SELECT * FROM products WHERE id = '"
. $pid . "'";

Given that you're using an extension that doesn't support prepared statements, the best thing you can do is actually casting the values, and using printf to insert the value of $pid in your query string.
Also: avoid SELECT * whenever possible. Select the fields you need, and name them. Be explicit.

I'd also add some basic validation, though like is_numeric, to make sure the request parameter is a valid id  value. If not, the client might attempting an injection attack. Anyway, the simple fix here would be:

$queryString = sprintf(
    'SELECT * FROM products WHERE id = %d',
    (int) $pid
);

I left out the validation, that's code you'll have to write yourself first...

Onwards - Making the resource parameter optional in mysql was, IMHO, a sure fire way to breed bad practices, and error-prone code. You've fallen into this trap... don't worry, we all have at some point, we've all written the infamous or die, and used mysql_query assuming that the last active connection would be the connection we needed. But most of us have found out the hard way that this isn't always the case... So please, fix this bit, too:

$result = mysql_db_query($dbname, $query1)
    or die("Failed Query of " . $query1);

The or die is just smelly, IMHO. I don't like code that just gives up like that, wrap this snippet in a function, and replace the or die  with throwing an exception, so that you can handle the error a bit cleaner than just dumping a query onto the screen (which is showing that the product_id parameter is used in this query, so it's basically sending an injection-attack-invitation).

You are also not passing a connection resource to mysql_db_query. I know it's an optional parameter, but you'd think it'd be nice to know what connection is actually being used to query this product stuff, if only to show that you actually know what DB this table is on, and to prevent bugs popping up, when you start adding multiple connections to the project.

$thisrow=mysql_fetch_row($result);

Again, in light of my aversion for or die constructs, I'd much rather see code actually bothering to check the return value of functions, like here: checking if $result is a resource, or if it's false or even true. If $result is true, your or die  statement won't stop the code from executing, BTW. I know it's not very likely to happen in this case, but you never know, if, down the road, the SELECT gets replaced with an INSERT or UPDATE, the or die is going to cause you grief.

$thisrow=mysql_fetch_row($result);
if ($thisrow)

Why are you fetching a row, if you're only checking to make sure the id is found in the database. Why not use mysql_num_rows, apart from the mysql extension being deprecated, of course.

TL;TR

The best thing for you to do now is to rewrite the code entirely. Preferably using PDO or mysqli  and prepared statements. It should look something along the lines of:

if (isset($_REQUEST['product_id']))
{
    $db = new PDO($dsn, $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $stmt = $db->prepare('SELECT id FROM products WHERE id = :id');
    $stmt->execute([':id' => $_REQUEST['product_id']]);
    if ($row = $stmt->fetch(PDO::FETCH_OBJ))
        echo 'Found product with id: ', $row->id;
    else
        echo 'Product not found';
}
else
{
    echo 'Please select a product or something...';
}


By storing the return value in a different variable and placing the distance in the queue, the magic number can be avoided:

class Solution(object):
    def updateMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        if not matrix:
            return matrix

        row_length = len(matrix)
        col_length = len(matrix[0])

        result = [[None for j in range(col_length)] for i in range(row_length)]

        queue = deque()

        # put all 0 cells in queue, set all other cells to a big number
        for row_index in range(row_length):
            for col_index in range(col_length):
                if 0 == matrix[row_index][col_index]:
                    queue.append((row_index, col_index, 0))

        # work from the 0 cells outwards while the queue is not empty
        while queue:
            i, j, dist = queue.popleft()
            if 0 <= i < row_length and 0 <= j < col_length and result[i][j] is None:
                result[i][j] = dist
                queue.append((i-1, j, dist+1))
                queue.append((i+1, j, dist+1))
                queue.append((i, j-1, dist+1))
                queue.append((i, j+1, dist+1))

        return result


Button incrementing from 0 to 9 and repeating

Your code is ok. But there are always other ways to get the same result which may be more elegant.

private void counterButton_Click(object sender, EventArgs e)
{
    szám=(szám +1) % 10;
    this.Text = szám.ToString();
}

or you can do:

private void counterButton_Click(object sender, EventArgs e)
{
    szám=(9==szám)?0:szám+1;
    this.Text = szám.ToString();
}


Computing a mathematical function in MIPS assembly

There are multiple issues:

first, try to make the program work: These two lines are contradictory

ori      $8, $0, 3         #put x into $8
ori      $8, $0, 1         #put x into $8

Perhaps the real idea is to move a function parameter to $8.

The second thing is redundant calculation:
Instead of squaring x twice, you should be able to

mul $8, $8
mflo $13
mflo $14

To catch the result in two registers.

There's no need to reserve registers for all the immediates, as one can at least add the last coefficients 16 and (-4) with

addi $x, $x, 16

Multiplications with small constants are also often better executed with a series of shifts and adds. Especially here x*4 equals x<<2 and x*2 == x+x, which leads to one less instruction for both operations.


In general this code looks pretty good.  I do have a couple of small pythonism comments:

dict.get() returns None if key not present:

This:

if 'name' in user and user.get('name') == BOT_NAME:

Can simply be this:

if user.get('name') == BOT_NAME:

... since dict.get() will return None if the key is not present and I presume BOT_NAME will never be None.

Iterating over 0 length item:

This:

if messages and len(messages) > 0:
    for message in messages:

Can simply be this:

if messages:
    for message in messages:

... since the for loop will not have anything to do if the length is zero.

Also, I am not sure what this if is testing for:

if messages:
    for message in messages:

If guarding against None, then it would be more pythonic as:

if messages is not None:
    for message in messages:

And if the check is a surrogate length check, then it isn't necessary at all, and the if could be removed.


Is there anything can be improved in this JavaScript module?

I really like this code.

Still, 2 observations:

The code is awfully optimistic, no default error handling ?
success gets data, textStatus, and jqXHR. I would pass all 3 to the callback function.


You can write a function to compare two "position" strings and a function to compare "priority" strings. Then a resulting comparison function could be written easily by calling the two already defined functions.

Now for the actual review, you don't need the if(b[1] == 'mobile-bottom') check in the if(a[1] == 'mobile-top') case, checking first if if(b[1] == 'mobile-top') is enough, in the other case, you can simply return -1.

Similarly, if(a[1] == 'mobile-bottom'), you only need to consider if(b[1] == 'mobile-bottom'), otherwise, you can simply return 1.


Organizing interfaces for player movement in chess game

A player doesn't move left or right, they move a game piece
A rook is not a player. A player has a rook (2 actually, but I digress).

When thinking about interfaces/class hierarchies it's useful to think in terms of "is a" or "has a" relationships. Bob is a player. A rook is a piece. A player has a rook.

I would modify your interfaces a bit.

interface IPlayer
{
    string Name { get; }
    bool MovePiece(IPiece piece, int row, int rank);
}

interface IPiece
{
    int Row { get; set; }
    int Rank { get; set; }

    bool CanMoveTo(int row, int rank);
}

You may want to consider using standard chess notation for clarity and cohesion with the problem domain, but using Cartesian coordinates will make the code simpler to write. I added a CanMoveTo method so each piece can store its own logic for checking to see if it's allowed to move to a position that the player attempts to move it to. This design may not be perfect (or even good), but should get you pointed in the right direction.


If it's readability you're mostly worried about, then you could change the style of your code:

public City(int id,          BlockPos startingPos,
            int citySize,    int edgeLenght,
            int pathExtends, Block groundBlock,
            Block pathBlock, boolean hasMainStreets,
            boolean hasPaths) {
    this.id             = id;
    this.startingPos    = startingPos;
    this.chunkLength    = citySize;
    this.cityLength     = citySize * 16;
    this.edgeLength     = edgeLenght;
    this.mapLength      = cityLength + edgeLenght + blockStart;
    this.pathExtends    = pathExtends;
    this.hasMainStreets = hasMainStreets;
    this.hasPaths       = hasPaths;
    this.groundBlock    = groundBlock;
    this.pathBlock      = pathBlock;
    this.blockStart     = edgeLenght;

}

Columnising is a useful trick which can make things more readable.

Yes, there is still visibly a lot of parameters clogging up the screen, but it's not so much that you can't put it all in one constructor. It also helps to remember KISS (Keep It Simple, Stupid), don't overcomplicate unless you need to.


Settings Model to read multiple settings files and writes to one

The module should import os.path instead of ntpath.

os.path is the cross-platform equivalent of ntpath, it automatically picks the appropriate path module for the OS your code is running on. So it will use ntpath behind the scenes when running on Windows, but you will also be able to use the code on more operating systems than just Windows.  (See the note at https://docs.python.org/3/library/os.path.html)


Your code is very nice! There is almost nothing for me to fault.

However, your try except statement is far too large in the try and is a bare except. Let's say, for whatever reason, your .format raises an error. You could have put the correct answer, however for reason beyond your control, the program failed. And you the user gets '1 x 3 = 3', when they put 3.

To amend this you can use the else part of the try except else finally:

try:
    user_input = int(user_input)
except ValueError:
    self.feedback = "invalid answer. Please enter numbers."
else:
    if user_input == self.answer:
        self.points += 1
        self.feedback = "right"
    else:
        self.feedback = "{} {}".format(self.question, self.answer)
    self.set_question()
    self.attempts += 1

You could say that you don't want to do user_input = int(user_input).
If this were the case then you can have the try as just int(user_input),
and have the else as your old try.

If I were to improve this more:

Better class names.

MyApp is not descriptive and is definitely not my app. TimesTabelsApp could be an alternate, unless you wish to add more to it. The same as above goes for MyWidget. You could likewise call this TimesTabelsWiget.
Put almost everything in the Python 'main'.

Window.size = (200, 100), should be in the main. It will still be global!
Try to avoid large library's when python comes built in with things you need.

I don't think I should need to install NumPy, when CPython already has randint. Sure, it's not as convenient, but asking an end user to install an entire library for something so small is kinda annoying. I know numpy is pip install numpy away, but Python can do this.

from random import randint
a, b = randint(1, 11), randint(1, 11)

A single line at the begging of each function, class and module is enough to document your code entirely.

def set_question(self):
"""Set the internal question and answer."""

Sure it's something that can be understood from the code, but what if I don't want to read the code, or can't.
Finally, I don't know why you need self.attempts = 1e-10. It seems kinda strange. And gives a large answer in set_score. I think it's to not get a ZeroDivisionError in set_score.

So you could try this:

try:
    score = self.points / self.attempts
except ZeroDivisionError:
    self.feedback = "You didn't attempt any answers"
else:
    self.feedback = "{:3.0f}% of right answers".format(score * 100)


Generating combinations of n elements in groups of k

Main loop could be simplified a little

There's not too much to say about the current program.  It works and it seems like it is using the fastest method possible.  It basically adds one to the last array element and moves left when an "overflow" happens.  At the end of handling all the "overflows", it moves back to the right, resetting each digit.

The one thing that I would change is basically that when you are moving back to the right, there's no need to use the main loop to do that.  It causes extra compares of (p >= 0) which are always going to be true and extra ++a[p] which are unnecessary.  You could instead handle moving to the right in its own nested loop.  Here's how it would look like:

do {
    if (++a[p]>n-k+p) {
        // Overflow, move to the next element on the left.
        p--;
        continue;
    }
    // Resolve overflows by resetting digits to the right.
    while (p < k-1) {
        a[p+1]=a[p]+1;
        p++;
    }
    newCombo(a,n,k);
} while(p>=0);

An interesting challenge

What if I asked you to write a program that prints out the N'th combination instead of all of them.  In your given example with n=6 and k=4, the 0th combination would be 0 1 2 3 and the 14th (and last) combination would be 2 3 4 5.  I find this task to be much more difficult (and useful) than generating all combinations.


Hash Tables: Ice Cream Parlor solution in javascript

The error was because of a silly mistake, in the binary search, it should be while(left<=right):

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the whatFlavors function below.
function whatFlavors(cost, money) {
  // Solution starts here
  var dict1={};

  var len=cost.length;

  for(var i=0; i<len; i++) {

    if (cost[i]<money) {
      if(dict1[cost[i]] !== undefined)
      {
       if(Array.isArray(dict1[cost[i]]))
       {
         dict1[cost[i]].push(i);
       }
       else
       {
         dict1[cost[i]] = [dict1[cost[i]]];
         dict1[cost[i]].push(i);
       }
     }
     else
       dict1[cost[i]] = i;
    }
  }

  cost.sort(function(a,b) {return a-b});

  for(var j=0; j<len; j++){
    var left=0;
    var right=len-1;
    if(cost[j]<money){
      var ser=money-cost[j];
      while(left<=right){
        var mid=Math.floor((left+right)/2);

        if(ser===cost[mid]){
          var val1=cost[j];
          var val2=cost[mid];
          break;
        }
        if(ser<cost[mid]){
          right = mid-1;
        }
        else{
          left = mid+1;
        }
      }
      if(val1 !== undefined && val2 !== undefined ){
        break;
      }
    }
  }

  var index1;
  var index2;
  if (val1===val2) {
     index1 = dict1[val1][0];
     index2 = dict1[val2][1];
  }
  else{
     index1 = dict1[val1];
     index2 = dict1[val2];
  }

  if (index2 > index1) {
    console.log(index1+1, index2+1);
  }
  else{
    console.log(index2+1, index1+1);
  }
  // Solution ends here
}

function main() {
    const t = parseInt(readLine(), 10);

    for (let tItr = 0; tItr < t; tItr++) {
        const money = parseInt(readLine(), 10);

        const n = parseInt(readLine(), 10);

        const cost = readLine().split(' ').map(costTemp => parseInt(costTemp, 10));

        whatFlavors(cost, money);
    }
}


Computing exponential function by Taylor Series without overflow

Well the exponential function is map from reals to reals (usually denoted f:R→R), so I would have expected the use of reals for all variables (i.e., x and n). However, I'll base my answer using integers, as that is what you've used.

Using larger integers

Fortran's basic integer precision has a largest integer value of 2147483647, which is exceeded for 4**16=4294967296. However, you certainly can specify a larger integer type (see the link) and easily fit 4**19=274877906944. This would be as easy as specifying the kind:

integer :: x,n

would become

integer, parameter :: i_8 = selected_int_kind(15)
integer(i_8) :: x, n

And you easily get the values you desire.

Alternative implementation

Instead of specifying larger precision, you could express the Taylor-expansion of the exponential as
$$
e^x = 1 + x\cdot \left(1 + \frac{x}{2}\cdot\left(1 + \frac{x}{3}\cdot \left(\cdots\right) \right) \right)
$$
and write your function as,

f=1.0
do i=n-1,1,-1
   f = 1.0 + x * f / i
end do

(here n is your number of terms you want). Fortran will implicitly cast i and x as reals (since they are multiplying/dividing a real in f), so you don't need to worry about larger precision in your integers. This version could also fit easily into a function where you can have the user specify the n and x values:

real function my_exp(n, x) result(f)
   integer, intent(in) :: n, x
   f=1.0
   do i=n-1,1,-1
      f = 1.0 + x * f / i
   end do
end function

which is small enough that a simple contains will be fine for your program (i.e., using a module isn't needed).

Other odds-and-ends

Modern Fortran (well, since Fortran 90) does not require the use of capitals for keywords, so you don't need to have your program yell at you that it is printing something or that you're going to specify the types of all variables (i.e., you can use implicit none, real and integer). Most IDEs I know have support for Fortran syntax, so you'll know when you're using keywords.

While initializing f=1.0 in the main will do what you expect, you may want to break the habit of doing so now because you may (accidentally) carry it over to functions where it will have different behaviour.


function to check if anchor tags contain href attributes with 301

I have never attempted such a task, but I will assume that you entertained the cURL techniques (including CURLOPT_NO_BODY and CURLINFO_HTTP_CODE) as suggest at 1 and 2.
As for parsing an html document, using regex may outperform a legitimate parser, but you might enjoy more accurate scaping if you use a DOM parser.
Since your focus is on performance, I'll [cringe] suggest regex to parse your html.
Your pattern ~<a(.*?)href="([^"]+)"(.*?)>~ uses lazy quantifiers and this can slow things down a little.  Also, your <a(.*?)href will allow the matching of <a data-href and <abbr href -- which is not what you intend.
Your intention is to capture ONLY the url inside of the href attribute, so don't bother matching more than you need.  You can probably get away with a wordboundary after a and a space before href, then reset the fullstring match with \K to only retain the href's value.  If this isn't strong enough validation, then you could add a lookahead to confirm that the opening tag is completed properly.

~<a\b.*? href="\K[^"]+~ or
~<a\b.*? href="\K[^"]+(?=".*?>)~

Either way, your code can skip the sanitizing step.  Thank goodness because $vowels contains data that are not all vowels.
strpos() can return false or 0 as the offset.  This means that you must not rely on the type juggled condition using merely !.  You must explicitly check for false or if you are on a php version that enjoys str_contains() -- that'll work.
I personally condemn the use of the "stfu operator" (@), but because I am not familiar with this task, I'll avoid calling it an abomination.
function contains_http_301_link(string $content, string $current_site): bool
{
    preg_match_all('~<a\b.*? href="\K[^"]+~', $content, $matches);
    foreach ($matches[0] as $url) {
        if (strpos($url, $current_site) !== false) {
            continue;
        }
        $headers = @get_headers($url, 1);
        if($headers && strpos($headers[0], '301') !== false) {
            return true;
        }
    }
    return false;
}

I could possibly include the $current_site filtration into the regex but it may do more harm than good.

If you were going to entertain (and benchmark) a DOM parser script, then perhaps use this:
function contains_http_301_link(string $content, string $current_site): bool
{
    $dom = new DOMDocument;
    $dom->loadHTML($content);
    $xpath = new DOMXPath($dom);
    foreach ($xpath->query("//a[not(contains(@href, '$current_site'))]/@href") as $href) {
        $headers = @get_headers($href->nodeValue, 1);
        if($headers && strpos($headers[0], '301') !== false) {
            return true;
        }
    }
    return false;
}


Raise a list of integers to powers and return uniques

Use a Hashset

This seems to be a more intuitive data structure to use since you need all of your values to be unique.

The code would change very little, but you could eliminate checking if the value is already in the List.

Use built in functions before creating your own methods

When writing to a file, you shouldn't need to check if a file doesn't exist and explicitly create it. This should happen automatically.

Use the System.IO.WriteAllText method

This also closes the file automatically, freeing you from needing to do that manually. (It basically replaces the method you wrote, so you may be able to get rid of that entirely).

You've already done similar in your GetInput function by using File.ReadAllText

Only use a one line method if it increases readability

Private Function ConvertStringToIntegerArray(ByVal arrayOfStrings As String()) As Integer()
    Return Array.ConvertAll(arrayOfStrings, Function(str) Int32.Parse(str))
End Function

The above method doesn't really have a purpose. It doesn't increase readability much since the build in method explains pretty well what it does with the name ConvertAll. Of course if you feel that your method name makes your code more human readable you should use it.


There is not much to say, just two notes:

Common mistake of redundant boolean check: some_boolean ? true : false -> some_boolean.
You can either use the bang find method or check the returned value, but not just use without a check.

So simply:

def authenticate!
  authenticate_or_request_with_http_basic do |access_key, secret_key|
    @current_app = App.find_by_access_key(access_key)
    @current_app && @current_app.secret_key == secret_key
  end
end


Should view related methods be included in models?

This could should not be in either the model or the view.  Rather is should be contained in the submission_helper, or if you really wanted to look into making it less procedural and more OO, then it should be handled by a presenter, a pattern in rails that steps in between the model and the view.

Jeff Casimir has developed a presenter for RoR called Draper (https://github.com/jcasimir/draper) which is definetly worth checking out, but in the mean time, the proper place for this is a helper method.

Its best to avoid logic in your view code, as its likely to change, and be distributed amongst many files, making it hard to maintain.  Putting it in a helper at least allows for a single source of that knowledge, so that if it has to change in the future it is easy to update.

Hope this helps.


Can you elaborate on that a bit? I fell like I do have a common interface (Callback) which prevents the dispatching method from having to do anything outlandish. For instance if I catch an exception and want to send it to the onError callback it looks something like

for (Callback cb : callbacksFor(Event.ERROR))
    cb.call(this, someException);.

  That's the dispatching method, right?

Right.

Problem here is that you pass the current object (having a state an business logic) as data to the callback. But you should only sent data transfer objects (without business logic and immutable by any chance).

So the common interface of the callback should look like this:

interface Callback{
   enum Key {EXCEPTION, DATA_1,DATA_2,DATA_3, ... }
   void onError(Map<Key, Object);
}

and you sample would change to:

Map<Key, Object> currentState = copyInstanceMembersToMap();
currentState.put(Key.EXCEPTION, someException);
for (Callback cb : callbacksFor(Event.ERROR))
    cb.call(currentState);

Then the callbacks themselves decide which data to use.

And you can use the same callback interface for other listeners as well.

Unfortunately you loose the type safety for the values in that map.
But you could get that back a little:

public abstract class GenericEnum {
    enum Key {
        EXCEPTION {
            @Override
            public <Exception> Exception getFrom(Map<Key, Object> map) {
                return (Exception) map.get(this);
            }
        },
        DATA_1 {
            @Override
            public <String> String getFrom(Map<Key, Object> map) {
                return (String) map.get(this);
            }
        },
        DATA_2 {
            @Override
            public <File> File getFrom(Map<Key, Object> map) {
                return (File) map.get(this);
            }
        };
        public abstract <T> T getFrom(Map<Key, Object> map);
    }

    public static void main(String[] args) {
        Map<Key, Object> testMap = new HashMap<>();
        testMap.put(Key.EXCEPTION, new java.lang.Exception());
        testMap.put(Key.DATA_1, "test");
        testMap.put(Key.DATA_2, new File(System.getProperty("user.home")));
        Exception value1 = Key.EXCEPTION.getFrom(testMap);
        String value2 = Key.DATA_1.getFrom(testMap);
        File from = Key.DATA_2.getFrom(testMap);
        String value3 = Key.DATA_2.getFrom(testMap); // ClassCastException

    }

}


Hands of Straights (LeetCode) Arrange the card

Lines like False -> False indicate that there is a better way.

helper :: Int -> [[Int]] -> Bool
helper v [] = True
helper v xss = let (a, b) = splitAt v xss
  in verify a && length a `mod` v == 0 -- length a <= v, so why not just length a == v?
  && helper v (removeHead a [] ++ b)

removeHead :: [[Int]] -> [[Int]] -> [[Int]]
removeHead [] acc = acc
removeHead (x:xss) acc = removeHead xss
  $ acc ++ [tail x | not $ null $ tail x]

Left folds like removeHead can often be turned into right folds:

removeHead :: [[Int]] -> [[Int]]
removeHead [] = []
removeHead (x:xss) = [tail x | not $ null $ tail x] ++ removeHead xss

removeHead needs no explicit recursion. Data.List.NonEmpty lets us avoid partial functions (and giving verify a name :) ).

import Data.List.NonEmpty

solve :: Int -> [Int] -> Bool
solve v = helper v . NE.group . sort

helper :: Int -> [NE.NonEmpty Int] -> Bool
helper v [] = True
helper v xss =
  let (a, b) = splitAt v xss
      (straight, a') = unzip $ map NE.uncons a
  in all (==1) (zipWith subtract straight (tail straight))
  && length a == v
  && helper v (catMaybes a' ++ b)


Method to draw an open or closed polyline

A closed polyline is really a polygon. For clarity, why not just call it a polygon?  There is no point in trying to do too much in the same function. Not only would the calling code be clearer, the implementations would be simpler too, without the special cases.

void Polyline(IList<Point> points)
{
    var n = points.Count - 1;
    for (int i = 0; i < n; i++)
    {
        AddLineSegment(points[i], points[i + 1]);
    }
}

void Polygon(IList<Point> points)
{
    Polyline(points);
    if (points.Count >= 3)
    {
        AddLineSegment(points[points.Count - 1], points[0]);
    }
}


Find the shortest whole repetitive substring (part 2)

You don't follow PEP8's naming conventions, which makes your code slightly harder to read for those used to it.
You should use is when comparing to booleans. Or you can remove the comparison and use not.
Which reads better, while not node.isEnd.
While loops are normally better written as for loops.
As then you don't have to define a variable outside it's scope, and then increment it in the loop.
Using a trie is a bit much here.
It makes the code more complex for no measurable improvement to the code.

Instead I'd change your code to just be the code in you __name__ == '__main__'.
This is as it's the part that's doing most of the work.

Keeping the outer for loop, and the if. You can change the while loop to be a generator of substrings,
and then you compare all slices to the first slice, and if they are all the same yield the size.
If any of them are not go to the next sub-length.

def whole_substrings(word):
    for sub_length in range(1, len(word) // 2 + 1):
        if len(word) % sub_length == 0:
            sub_slices = (
                word[start:start+sub_length]
                for start in range(0, len(word), sub_length)
            )
            first = next(sub_slices, None)
            for i in sub_slices:
                if i != first:
                    break
            else:
                yield sub_length
    yield len(word)

You can use this in two ways the less cryptic min, or the more cryptic next.
As it guarantees the items are returned in sorted order.

To further improve this you can change the for sub-length loop to be \$O(\sqrt{n})\$, rather than \$O(n)\$.
If you yield the product and the 'other half' of the product, i.e. 3 * 5 == 15, so you'd yield 3 and 5, by just by finding 3.


I think you can potentially remove the impact of the network altogether by using offline Wikipedia dumps. Wikipedia itself asks to not crawl them:

  Suppose you are building a piece of software that at certain points
  displays information that came from Wikipedia. If you want your
  program to display the information in a different way than can be seen
  in the live version, you'll probably need the wikicode that is used to
  enter it, instead of the finished HTML.

  Also, if you want to get all the data, you'll probably want to
  transfer it in the most efficient way that's possible. The
  wikipedia.org servers need to do quite a bit of work to convert the
  wikicode into HTML. That's time consuming both for you and for the
  wikipedia.org servers, so simply spidering all pages is not the way to
  go.

  Please do not use a web crawler to download large numbers of articles. Aggressive crawling of the server can cause a dramatic slow-down of Wikipedia.

as far as improving HTML parsing, you can replace html.parser with a faster lxml:

bs = BeautifulSoup(req.text, 'lxml')

Note: this requires lxml package to be installed.
make visited_urls a set - this would dramatically improve the lookups
instead of locating all links and then filtering them, you can ask BeautifulSoup to locate only "wiki" links by using a a[href^="/wiki/"] CSS selector - this would also lead to removing the "href" attribute presence check:

for link in bs.select('a[href^="/wiki/"]'):
    if link["href"] not in visited_urls:

there is also this SoupStrainer class that would allow you to parse only a part of the document - see if you can apply it to skip some irrelevant parts of the pages
I am not sure if you actually need a UrlNode class, but if you think you do, __slots__ should improve performance and memory usage:

class UrlNode:
    __slots__ = ['url', 'prev']


Simple function to create Tokens from user input

It's not clear whether you want to support only y, n and numbers as your question states, or any characters besides y & n as your code implies :)

Basically you can divide the problem to two sub problems:

Split the input string to words I'm using the split methods from std but if you have more complex requirements, you can use the regex crate
Map the words to tokens. A simple equality check (==) or match is enough. There is no need to parse() everything.

As you've not specified what's allowed as a delimiter, I'll assume that it's whitespace.

#[derive(Debug)]
enum InputToken {
    Number(i64),
    Boolean(bool),
    Error(String),
}

fn main() {
    let input = "1 -2 +4 y n & abc";
    let tokens = input.split_whitespace();

    for x in tokens {
        println!("{:?}", parse_token(x));
    }
}

fn parse_token(input: &str) -> InputToken {
    match input {
        "y" => InputToken::Boolean(true),
        "n" => InputToken::Boolean(false),
        token => match token.parse::<i64>() {
            Ok(num) => InputToken::Number(num),
            Err(e) => InputToken::Error(format!("Invalid input token [{}]: {:?}", token, e))
    }
}

}


The first step would be to refactor out the instanciation of the Oauth2 client:

# lib/analytics_oauth2_client
class AnalyticsOAuth2Client > OAuth2::Client
  def initialize(client_id, client_secret, options = {}, &block)
    client_id || = ENV['GA_CLIENT_ID']
    client_secret || = ENV['GA_SECRET_KEY']
    options.merge!(
        authorize_url: 'https://accounts.google.com/o/oauth2/auth',
          token_url: 'https://accounts.google.com/o/oauth2/token'
    )
    super(client_id, client_secret, options, &block)
  end
end

And then maybe we should devise a strategy to save those pesky oauth tokens:

class AccessToken < ActiveRecord::Base
  # @expires_at [Int]
  # @access_token [String]
  # @refresh_token [String]
end

class GoogleAnalyticsController

  # ...
  def oauth_callback
    @client = AnalyticsOAuth2Client.new
    token = @client.auth_code.get_token(params[:code], :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])
    @saved_token = AccessToken.create!(token.to_hash)
    session[:oauth_token] = @saved_token.id
    redirect_to new_report_path
  end
end

And we need a controller method to get the access token from the session:

def authorize!
  # ... @todo redirect to back to authentication if no `session[:oauth_token]`
  stored_token = Token.find!(session[:oauth_token])
  @token = OAuth2::AccessToken(AnalyticsOAuth2Client.new, stored_token.attributes)
  @client = GoogleAnalytics.new(token: @token)
end

And we need to shove the token into GoogleAnalytics:

class GoogleAnalytics
  include ActiveModel::Model

  attr_writer :token
  attr_accessor :user

  def initialize(attrs: {})
    super
    @user ||= Legato::User.new(@token) if @token
  end
end

Then we consider the separation of concerns - models should not deal with authentication - thats a controller concern. You should pass whatever authorized object the models needs
from the controller. Dependency injection is commonly used for this:

class Report
  attr_writer :client

  def get_keywords(oauth_code)
    self.url = @client.fetch_url(self.web_property_id)
    self.keywords = # Get keywords for self.url from another service
    keyword_revenue_data(oauth_code)
  end
end

class ReportsController
  # ...

  def create
    @report = Report.new(client: @client, params[:report])
    @report.get_top_traffic_keywords
    create!
  end

  # ...
end