String-formatting and printing functions

As you mention, the simple replacing is susceptible to problems if a replacement string includes a format specifier. But setting that aside, there are still a few things I would rather do differently.

Document. You should be sure to document your formatting language in comments; without reading the function, or the example in main, it's impossible to know that the formatting language uses curly braces around indices starting at zero, whether you can repeat or skip indices, or what happens if you provide an out-of-bounds index.

Avoid C functions? This may be personal style, but I would prefer to avoid snprintf in format_impl. I would instead probably use something like "{" + std::to_string(N) + "}". The resulting local could then be marked const, or the expression could go directly in the call to boost::replace_all.

Remove redundancy. Jeffrey's comment about std::string& and std::string&& overloads is half right. It should be relatively rare that you need to provide both overloads. In places that are doing template type deduction on parameter T, T&& can be deduced as either type. Here there is no deduction so that cannot happen. (That's the part of the comment that was half wrong - it didn't apply here.)

Instead we have to look at how fmt is being used. In format(const std::string&, ...) this immediately makes a mutable copy called temp. In format(std::string&&, ...), this moves the local to another mutable copy called temp. From there, both functions are identical. I assert that there should only be one function here.

What function? Well, you want to modify the parameter, so it needs to be mutable. If the parameter is not mutable, you'll have to make a copy. So that rules out a const std::string&. And as your example shows, you can't always convert to a std::string&&. So what's the right option? Plan vanilla std::string. If you call it with a const, the caller makes a copy; the function receives a copy that it is free to mutate. If you call it with an rvalue, the caller moves it and the function receives a copy that it is free to mutate. So the result?

template <class... Args>
std::string format(std::string fmt, Args&&... args)
{
    detail::format_impl<0>(fmt, std::forward<Args>(args)...);
    return fmt;
}

The same argument applies to print very similarly. The only question is if you'll want to explicitly mark the string it passes to format with a std::move, or trust your compiler to figure it out. (In this case it's simple enough I'd probably leave it out. But it does serve as implicit documentation to a future reader, so I'll show it here.)

template <class... Args>
void print(std::string fmt, Args&&... args)
{
    std::cout << format(std::move(fmt), std::forward<Args>(args)...);
}

Brush up on r-value references: Note that your implementation of print(std::string&& fmt, ...) was incorrect. In particular, one of the two uses of std::forward is misleading. Per Scott Meyers, it's useful to think of std::forward as a “conditional” std::move. It's useful in conjunction with the deduced T&& parameters, which he calls “universal references.” You use this correctly in the code phrase std::forward<Args>(args)..., which moves each movable sub-args, determined by the type of the corresponding Args, as deduced from the call site.

However the similar looking phrase std::forward<std::string>(fmt) is not conditional at all. It will never move fmt, as it is always casting fmt to an lvalue type. If you were to implement this function (which I recommended against in the previous point), you would want std::forward<std::string&&>(fmt) which is really just a long and hard to read way of writing std::move(fmt). This is correct because print's fmt is an l-value that was moved in, and now you want to move it onward.

The upshot This was a good exercise that ended up focusing a lot on std::move, std::forward, and r-value references in general. There don't appear to have been any functionality problems in your implementation, although it's always good to make sure with more than one test case. If you expand on this function's robustness and capability set (say fixing the limitations from the replace_all approach, or adding a way to escape braced indices so that they aren't substituted) that could make another interesting review. Thanks!


You have showDescription directly printing out the message. Avoid printing in arbitrary functions whenever possible. It's much better to have things return Strings, then print at the call site as needed. I'd change that function to:

private static String produceDescription() {
    return "You have to guess a number between " + lowerRange + " and " + upperRange + ".\n"
           + "You have " + tries + " tries.");
}

. . .

System.out.println(produceDescription());

Why? Two highly-related reasons:

Whenever possible, functions should return the data that they produce. Can you guarantee that for a function like this you will always want to directly print that data? Let the caller decide how they want to use the data that the function produces. Forcing the data to be printed makes the function less useful in the long term. As an example...
If you ever decide to adapt this program to use a full GUI, you're directly printing and will need to modify every function that is calling println. The less functions you have that are using data in a specific way, the easier it will be to alter your program later.

I would not make everything static here. Again, what if in the future you wanted to run two games at the same time (like if you created a server that allows people to connect to it and play)? I'd get rid of static everywhere, and make everything plain instance methods/properties, then just instantiate a instance of the game in main.

Main is a poor name for this class. Ideally, it should be a description of what the object accomplishes. What if you ever imported this class so it can be used elsewhere? A class called Main doesn't make it immediately obvious what it is used for. I'd change the name to something like NumberGuessingGame.

run = input.nextLine().equalsIgnoreCase("Y") ? true : false;

is redundant. Ternary expressions are cool, but they're often overused. Think about it, what does equalsIgnoreCase return? A bool (true or false). You're then using that bool as a condition to the ternary... to get the same thing that equalsIgnoreCase returned originally.

Just get rid of the ternary:

run = input.nextLine().equalsIgnoreCase("Y");

And on the topic of conditions, a little later you have:

while (triesSoFar < tries && won == false) {

won == false certainly isn't wrong, but comparing against a boolean value directly is almost always unnecessary. Just write:

while (triesSoFar < tries && !won) {

Remember, ! is read as "not". "While tries to far is less than tries, and they haven't (not) won".

tries is a bad name. It isn't representing the number of tries taken (that's triesSoFar), it's representing the max number of tries allowed. Change it to something like maxAllowedTries.

Naming is very important. It is one of the key things that allows someone to be able to read your code and quickly know what's going on. Make sure your functions and variable names accurately describe what they do, or you'll make other people's lives more difficult when they need to read your code. You'll also make your own life more difficult if you ever come back to this program, because you will eventually forget parts of this program after some time.

System.out.print("Your try: ");

Isn't actually guaranteed to print right away. print and println use a "buffer" to hold text while waiting to print. That buffer is only "flushed" (printed out) when the text exceeds a certain length, or a newline (\n) is reached. You have short text here, and because you're using print, no newline is being added to the buffer. You may find that if you made this text a little shorter, it wouldn't print until some other text had be printed as well, which will make your program confusing.

If you use print instead of println, it can be a good idea to add a call to System.out.flush() after it to make sure everything is printed when you want it to be.

Just to show a potentially appropriate use of a ternary, you have:

if (won) {
  System.out.println("You found the secret number!");
} else {
  System.out.println("You lose. The secret number was " + randomNumber + ".");
}

Which isn't bad, but it could be shorted a bit:

String message = won ? "You found the secret number!"
                     : ("You lose. The secret number was " + randomNumber + ".");

System.out.println(message);

I'm not necessarily advocating for this way, but I thought I'd show it. It allows you to get rid of the multiple calls to println.

  int guess = Integer.parseInt(input.nextLine());
  if (guess > randomNumber) {
    System.out.println("The secret number is smaller.");
  } else if (guess < randomNumber) {
    System.out.println("The secret number is higher.");
  } else {
    won = true;
    break;
  }

is a dense chunk of code. I prefer to add more spacing around things. I like blank lines above ifs and elses so it's easier to see at a glance the distinct blocks. I'd make it:

  int guess = Integer.parseInt(input.nextLine());

  if (guess > randomNumber) {
    System.out.println("The secret number is smaller.");

  } else if (guess < randomNumber) {
    System.out.println("The secret number is higher.");

  } else {
    won = true;
    break;
  }

That generally makes it easier to pick things out by eye when scanning over a document.

There's some more stuff, but unfortunately, I have to go. Good luck!


Let's review from top to bottom.

Page_Load()

No need to have a try..catch here if the code only throw inside the catch. Omitting the try..catch will lead to the same result and removes one level of indentation.

btnSignIn_Click()

Like in Page_Load() there is no need to have that try..catch either.
Classes should be named using PascalCase casing (see: .NET Naming Guidelines), hint: C_User. The same applies to naming of methods. hint: Get_LoginUser(()
By reversing the condition of if(dt != null && dt.Rows.Count > 0) you can return early hence there won't be the need of the else part which saves you another level of indentation like so

if(dt == null || dt.Rows.Count == 0)
{
    Response.Redirect("LoginUser.aspx", false);
    return;
}

DataRow dr = dt.Rows[0];
Session["username"] = dr["USERNAME"].ToString();
....

As regions may be acceptable inside a class they are phroned upon inside a method. Having a region inside a method is usually a clear sign that this method is doing to much.
Why wasting vertical space by first declaring an int and setting it to 0 and on the next line of code another value is assigned to it. Just do

Int16 userRole = Convert.ToInt16(Session["role"]);

The switch could be improved by replacing the magic numbers with meaningful constants.


Lorentz Attractor visualization using functional programming

I don't know anything about Lorentz Attractors or functional programming, but I have a few things I want to mention.

getElementById is faster than querySelector

const canvas = document.getElementById('canvas')

You can use shorthand property names in your draw function.

return { x, y, z };

You can give parameters a default value

function draw (hue = 0) {
  //...
}

and remove this line

hue = hue || 0

I don't know if it's deliberate because you have something against purple, but the hue goes to 360.

Use semicolon at the end of your lines. Technically, JavaScript can run without them, but it just... looks wrong. If anything, do it to make it a habit, since it's gonna be a problem if you code something in another language later.

It seems more appropriate to use setInterval instead of setTimeout here. You will have to handle the hue differently in that case. Making it global is an option, but not good if you are trying to avoid those. Another option could be a generator.

function draw (hue = 0) {
  const { x, y } = update();
  ctx.fillStyle = `hsl(${hue},100%, 50%)`;
  ctx.fillRect(x, y, 0.1, 0.1);
}

const hueGenerator = (function*() {
  let hue = 0;
  while(true) {
    hue %= 360;
    yield hue++;
  }
})();

setInterval(() => {
  draw(hueGenerator.next().value);
}, 5)


Declaring JavaScript variable and then overwriting it multiple times

You can using chaining, move the toLowerCase() to simplify a little and return the last statement directly:

function() {
      var el = {{element}};
      el = (el.innerText || el.textContent);
      return el.charAt(0).toUpperCase() + el.slice(1).toLowerCase();
}

I'm personally not a fan of using a single variable for many purposes (I think it interferes with readability and maintainability) so I would probably do this:

function() {
      var el = {{element}};
      var text = (el.innerText || el.textContent);
      return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}


You could simplify the above significantly:

class FGSingleton {
    static let sharedInstance = FGSingleton()

    var gameScore: Int = 0

    // METHODS
    private init() {
        println(__FUNCTION__)
    }
    func displayGameScore() {
        println("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}

And call it like this:

FGSingleton.sharedInstance.displayGameScore()


Merge/Insertion sort program taking longer than an hour to finish - C++

Performance
For the moment, let's look at only one small part:
void sort(vector<int> &vec, int left, int right, int originalsize)
{
  int insertion = right - left;
  if(insertion <= 8)    //if righ-left is less than or equal to 8
  {
     insertionSort(vec, originalsize);       // call insertion sort
  }
  if(left < right)
  {
    int center = (left+right)/2;    //calculating center of vector
    sort(vec, left, center, originalsize);    //calling sort for temp vector
    sort(vec, center+1, right, originalsize);   //calling sort for temp vector
    merge(vec, left, center, right, originalsize);    //calling merge to merge two vectors together
  }
 }

This has a couple of problems. The first has already been pointed out: when you call insertionSort, you're telling it to sort the entire array, rather than just the small section you're currently dealing with.
From there, however, it just gets worse. Because after you do an insertion sort on the entire array, you don't just return can call it good. You continue to call sort recursively as long as left < right.
So that means when you get a partition down to 8 elements, you do insertion sort on the entire array. Then you create two partitions of 4 elements--and for each of them, you insertion sort the whole array again. Then from each of those you create two partitions of 2 elements--and for each of them...yup, you insertion sort the whole array yet again.
So not only are you do an \$O(N^2)\$ insertion sort on the whole array--with the array of a million elements, you're doing it 500,000 + 250,000 + 125,000 = 875,000 times!
Comments
Some of your comments are quite good:
 while(j < tempLeft.size())      //while left vector has elements
 {
     vec[i++] = tempLeft[j++];
 }

That's a real help in showing what your intent was. Some of the other comments aren't nearly so helpful though. For example, none of these strikes me as being very helpful at all:
   for(int i = left; i < right; ++i)     //starting from 1 for original vector size
  {
    int tempval = vec[i];      //set tempval to vector value at 1
    int j;

    for(j = i; ((j > 0)&&(tempval < vec[j-1])); --j)    //for j=i while j is greater than 0 and tempval is less than the number before it
    {
      vec[j] = vec[j-1];    //set vector[j] to vector[j-1]
     }
      vec[j] = tempval;   //tempval now holds vec[j]
}

The last of those goes beyond useless and into misleading (sounds like you think it assigned from vec[j] to tempval, when you actually did the reverse).
Indentation
Indentation is an important tool in keeping code understandable. The precise parameters you choose don't seem to matter a whole lot (within reason), but whatever you do, do it consistently. This code is sadly lacking in that respect.


When you end up with a pyramid of if-else clauses like this, it's sometimes a good idea to use cond instead.  cond lets you specify a bunch of clauses, and picks the first one that matches.

For example:

def valid_phone(changeset, field) do
  phone = get_field(changeset, field)
  cond do
    phone == nil ->
      changeset
    String.length(phone) != 10 ->
      add_error(changeset, field, "n'est pas valide")
    true ->
      changeset
  end
end

Of course, that can be simplified further into

def valid_phone(changeset, field) do
  phone = get_field(changeset, field)
  cond do
    phone != nil and String.length(phone) != 10 ->
      add_error(changeset, field, "n'est pas valide")
    true ->
      changeset
  end
end

Which can be simplified further, because any cond with one clauses & a true is really just a fancy if-else expression:

def valid_phone(changeset, field) do
  phone = get_field(changeset, field)
  if phone != nil && String.length(phone) != 10 do
    add_error(changeset, field, "n'est pas valide")
  else
    changeset
  end
end


isset can take multiple inputs, and fails if any of them is not set. So, the first if clause could become:

if (!isset($_POST['login'], $_POST['email'], $_POST['password'], $_POST['password_check']))

I personally prefer using !== so that type juggling will not happen.

if ($_POST['password'] !== $_POST['password_check'])

Instead of using SELECT COUNT(*) query to fetch existing username/email in your DB, you can instead set those columns to be UNIQUE and just go to the INSERT statement. The INSERT will fail with error code 1062.
Instead of using camagru_jgengo.user everywhere, you can set the dbname in the DSN string.
While not necessary, you can switch to using crypt() instead of md5 hashing. An MD5 has a higher collision chance, and since you are using it for sending emails with verification links. Using some form of salt will protect you from sending the same verification links to multiple users.


Choose a color with probability proportionate to its weight in a group of colors

I can't think of a better algorithm.  There is a minor bug, though: you are using inclusive-inclusive ranges, when they should be inclusive-exclusive ranges.  That means that you've overweighted red by \$\frac{1}{60}\$ and underweighted green by \$\frac{1}{60}\$.

The way it the algorithm is expressed could be tweaked a bit.

The count isn't counting elements; it's more of a sum.
The block could accept two parameters |color, weight| to automatically destructure |color_weight|.
The hash isn't really being used for a lookup, so I would just keep it as an array.

def random_color(colors_with_weights)
  sum = 0
  colors_with_cumul_weights = colors_with_weights.collect do |color, weight|
    [color, sum ... (sum += weight)]
  end
  rand_num = rand(sum)
  colors_with_cumul_weights.find { |color, range| range === rand_num }.first
end

In an interview situation, I'd just accept your code as a fine answer.


Finding the value 'n' in an array that has 'n' or more larger values

Right now, after you sort the array, you're doing a linear search for the correct value. I believe you should be able to write that part of the task using a binary search instead of a linear search.

The sorting has a minimum complexity of \$O(N log N)\$, so reducing the search from \$O(N)\$ to \$O(log N)\$ won't affect the overall computational complexity, but for any more than a small number of items, it should still reduce the overall time.


I'm skeptical of accepting postal codes as Integers.  Japanese postal codes are of the format NNN-NNNN.  Accepting a String, which may contain an optional hyphen and leading zeros, would be more appropriate.

Furthermore, an API that is designed to take an integer could never be extended to countries like the UK and Canada, where postal codes are alphanumeric.  It would also be problematic for US ZIP+4 codes, which, despite being mostly numeric like Japanese codes, may overflow an Integer.  (It's odd that you take an Integer instead of an Int, but that's a moot point.)


I'll first just suggest that you read the Python style guide as it has great tips on readability.

The best way you can format time is using datetime.strftime. You can call it on a datetime object and pass a string formatted to represent each time value and it will format the data into the string format you provide. This way you can format an exact code you'd like instead of just removing milliseconds:

print (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
>>> 2015-09-17 15:43:30

Using the table here you can see all the available options if you'd like to go more specific. While I'm on the datetime, it is not clear when you call .now on your stored object. It reads awkwardly. Instead use datetime.datetime.now(). But, since that's a lot to type I'd instead suggest calling from datetime import datetime at the start, so you can then just call datetime.now().

On your second question, yes there is a better way to do the while loop. Instead of using if to check conditions and break on them, make that condition the condition of your while loop.

while chosen_time >= datetime.now():
    time_difference = (chosen_time - chosen_time.now())
    print str(time_difference) + ' until the time.'
    time.sleep(3)

The reason people usually use while True is that either the condition is not easy to make into an expression, the condition can't be evaluated when the loop is firt encountered or that they want to emulate a do while loop. But none of these is true for you, so it's not needed.

Other Notes

You almost never need to call __str__. The point of functions with two underscores on either side is that they allow on object to be passed to another function and run that way. In this case, you could use str(chosen_time). But I wouldn't use that either, instead use str.format.

print 'The time you chose is: {}'.format(chosen_time)

It replaces the {} with the parameter you pass into format. It's very useful when you have multiple parameters or need to apply particular formatting to them, so you should get used to using it.

You don't need brackets around the `time_difference calculation, so leave them out.

time_difference = chosen_time - chosen_time.now()

I agree with Ethan about the input validation, but I want to specifically note that someone could enter "12 ". That would seem too long to be an integer, but would actually require that you call int on it, which you currently don't. I suggest that you call strip on the month parameter. It will remove whitespace at the start and end of the user's input, preventing this issue.

month = raw_input('What is the month of the date? ').strip()


Use Control.Lens for code this stateful. (Control.Lens.TH must be used to define Machine.) May as well leave out type signatures this homogenous. Control.Monad.Loops often helps against explicit monadic recursion.

opReadAt target = uses mState $ (`index` target)
opReadNext = mPos <<+= 1 >>= opReadAt
opWrite target what = mState %= update target what

opBin op = do
    a <- opReadNext >>= opReadAt
    b <- opReadNext >>= opReadAt
    target <- opReadNext
    opWrite target $ op a b

opcode 1 = opBin (+)
opcode 2 = opBin (*)
opcode 99 = isDone .= True

runCode = (opReadNext >>= opCode) `untilM_` use isDone

evalWith :: Int -> Int -> Machine -> Int
evalWith noun verb = evalState $ do
    opWrite 1 noun
    opWrite 2 verb
    runCode
    opReadAt 0


Shape

A Shape is only an abstraction to unify different geometric constructs so my advice would be to make it an abstract class. (that is, a class that you cannot instantiate).

Point

Point as x and y coordinates. That's it. You have to decide if it inherits from Shape but from an OOP perspective I do agree with @simon-forsberg that it probably shouldn't.

Segment

Segment is defined by two Point and inherits from Shape.

Triangle

Triangle is three Point and inherits from Shape.

And you can keep doing that for Rectangle and Square, just being careful with how you set up your constructors. Every classes should extend Shape but Point.

Encapsulation

When you declare fields like x,y for Point, don't forget to give them a visibility modifier like private or protected (I assume you know what that means?) and then declare appropriate setter/getter.


Setting zoom for layer disappearance in Leaflet

In your case a better way is using a predefined mapping (as Map) holding the relations between zoom limits and respective jobs.Then, just iterate through the mapping and perform add/remove operation:

const zoomJobsMap = new Map([
  [6, job],
  [7, job2],
  [8, job3],
  ...
]);

map.on('zoomend', function() {
    let zoom = map.getZoom();   # get zoom value at once
    for (var [zoomLimit, jobObj] of zoomJobsMap) {
        (zoom < zoomLimit)? map.removeLayer(jobObj) : map.addLayer(jobObj);

    }
}


There are a few things which I consider required. First of all I think your code does a good job. Below I have written some of the things I would also implement.

First of all. Be careful when echoing exception message directly. Especially database exceptions has a tendency to contain connection credentials. Imagine an error happens in your application and a malicious user sees this message. He could then log-in onto your database and wreck havoc! Try to keep the amount of sensitive information out of exception messages users are able to see.

From what I can see your class wraps a PDO instance to make certain tasks easier. When you wrap your PDO instance inside a class your lose some of PDO capabilities. As far as I can see from the code I have no way to perform a transaction. This may not be useful to you now due to an older MySql version, but when you sometimes in the future upgrade (I hope you do :D) this might be desired. I would provide a way to interact with the PDO instance from outside the class. A simple pdo() method would solve that problem.

/**
 * Provides access to the application PDO instance.
 *
 * @return \PDO
 */
public function pdo() {
    return $this->dbh;
}

When looking at your execute, resultset and single methods I see three flaws. The first being a potential double execution of your query. Imagine you sometime in the future call the execute method. Then you follow that by calling the resultset or single method. Now you have executed the query twice. This may not cause bugs when you are fetching data, but if the query is an insert statement, which populates an unique column, you will get an SQL error. I would remove the calls to the PDO execute method inside the resultset and single methods. This would effectively eliminate all possible bugs of this kind. Keep in mind you should also perform some error checking to see if the current statement has been executed or you would otherwise get an error. This could be solved by setting a flag indicating if the statement has been executed.

private $executed = false;

public function execute() {
    $this->stmt->execute();
    $this->executed = true; // Set the flag.
}

The second flaw is that you are unable to close the cursor for the current statement. By closing the cursor you gain the ability to execute the statement once more with different parameters. You would also gain some (small) performance increase on huge queries. Take a look at the documentation for the closeCursor method.

public function closeCursor() {
    $this->stmt->closeCursor();
    $this->executed = false; // Reset the execution flag.
}

The third flaw which I really think is required regards your resultset and single methods once more. By default they will fetch the result-set into an object. This is a good practice when writing OOP code, but often you will find yourself fetching result sets into specific classes. Consider passing the data directly into an User class or passing an object of StdClass into the user class, so the user class can fetch the data. By passing directly into the class you save some performance and make the code more readable. I would also change the code, so you are able to fetch the result set as an array. Sometimes this may be preferred and you cannot predict the future. You could change the method signature of resultset (and single too) to something like the following:

/**
 * Fetch entire result-set of the current query.
 *
 * @param integer     $mode  A PDO constant declaring the fetch mode.
 * @param string|null $class A qualified class name to fetch the result into.
 * @param array       $args  Constructor arguments for the custom class.
 *
 * @return mixed Returns the result set according to the specified fetch mode.
 *               The default mode is to fetch an object of type StdClass.
 */
public function resultset($mode = PDO::FETCH_OBJ, $class = null, array $args = []) {

    if(!is_null($class) && in_array($mode, [PDO::FETCH_CLASS, PDO::FETCH_OBJ])) {

        return $this->stmt->fetchAll(PDO::FETCH_CLASS; $class, $args);

    }

    return $this->stmt->fetchAll($mode);

}

/**
 * Fetch one row of the current query.
 *
 * @param integer     $mode  A PDO constant declaring the fetch mode.
 * @param string|null $class A qualified class name to fetch the result into.
 * @param array       $args  Constructor arguments for the custom class.
 *
 * @return mixed Returns the result set according to the specified fetch mode.
 *               The default mode is to fetch an object of type StdClass.
 */
public function single($mode = PDO::FETCH_OBJ, $class = null, array $args = []) {

    if(!is_null($class) && in_array($mode, [PDO::FETCH_CLASS, PDO::FETCH_OBJ])) {

        return $this->stmt->fetchObject($class, $args);

    }

    return $this->stmt->fetch($mode);

}

There is also another thing which I think is important. You are creating your PDO connection in the constructor effectively making the parameters for the connection hardcoded (or so it looks from $this->user due to lack of a constructor argument). I would extract the connection functionality into a separate class. This will also allow you to use different connections with the same database class. I would write something like the following. First I would alter the constructor in your current class.

public function __construct(PDOConnection $connection) {

    $this->dbh = $connection->getConnection();

}

Then I would write the PDOConnection class.

class PDOConnection {

    private $instance;

    private $dsn;
    private $username;
    private $password;
    private $options = [];

    public function __construct($dsn, $username, $password, array $options = []) {
        $this->dsn      = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->options  = $options;
    }

    public function setAttribute($name, $value) {

        if(!$this->instance instanceof PDO) {
            throw new LogicException('Cannot set PDO attribute. Please make sure you are connected using the connect() method.');
        }

        if($this->instance->setAttribute($name, $value) === false) {
            throw new LogicException('Could not set PDO attribute: ' . $name);
        }

    }

    public function setOption($name, $value) {
        $this->options[$name] = $value;
    }

    public function getConnection() {

        if(!$this->instance instanceof PDO) {
            throw new LogicException('No database connection established.');
        }
        return $this->instance;

    }

    public function connect() {

        try {

            $this->instance = new PDO($this->dsn, $this->username, $this->password, $this->options);

        }catch(PDOException $exception) {

            throw new ErrorException('Could not connect to the database!', null, $exception);

        }

    }

    public function disconnect() {
        $this->instance = null;
    }

}

Keep in mind this code has no error checking and not been tested, so there might be an error.

The usage of these classes would be like the following. I have named your class Database since I couldn't see the original name from your post.

$dsn  = 'mysql:host=127.0.0.1;dbname=AWESOMENESS;charset=utf8';
$user = 'username';
$pass = 'password';

$connection = new PDOConnection($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CURSOR  => PDO::CURSOR_FWDONLY, // Scrollable cursors may be unavailable or very expensive on MySql
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_PERSISTENT => false
]);

$connection->connect();

$database = new Database($connection);

I hope this can help guide you in the right direction, happy coding!


Text cleaning script, producing lowercase words with minimal punctuation

Actually, your approach consists to remove or to replace with a space all that isn't a word (urls and characters that are not an ascii letter). Then you finish the job removing duplicate spaces, spaces at the beginning or the end of the string, and converting all in lower-case.

The idea makes sense.

But concretely, what is the result of this script?
It returns all words in lower-case separated by a space.

Described like that, you easily understand that you can extract the words and join them with a space. To do that, a simple re.findall(r'[a-z]+', text) suffices, but you have to remove the urls first if you don't want to catch letter sequences contained in them.

The url pattern

If you read your url pattern, you can see that the only part that isn't optional is in fact [\w-]+(?:\.[\w-]+)+ (written [\w\-_]+(\.[\w\-_]+)+ in your script: _ is already inside \w, you can put - at the end of a character without to escape it, the capture group is useless).All that comes after this part of the pattern doesn't require a precise description and can be replaced with a \S* (zero or more non-white-spaces). Even if it catches a closing parenthesis or a comma, it isn't important for what you want to do (we will see how to handle commas or dots later).

One of the weaknesses of the url pattern is that it starts with an alternation in an optional group. This means that at each failing position of the string, the regex engine has to test the three alternatives (http|ftp|https) and without the whole group for nothing.
It's possible to improve that a little if you start the pattern with a word boundary and if you replace the last alternative (https) with an optional s in the first.

The url pattern can be rewritten like this:

\b(?:(?:https|ftp)://)?\w[\w-]*(?:\.[\w-]+)+\S*

and the whole function:

import re

def cleaning2(text):
    text = re.sub(r'\b(?:(?:https?|ftp)://)?\w[\w-]*(?:\.[\w-]+)+\S*', ' ', text.lower())
    words = re.findall(r'[a-z]+', text)
    return ' '.join(words)

Note that the URL syntax can be particularly complex, and that it isn't always possible to extract an URL from a non-formatted string.

If you want to keep commas and dots:
Few changes, you only have to be sure that \S* in the url pattern doesn't eat a comma or a dot at the end of the url with a negative lookbehind (?<!...), and to add them in the character class in the re.findall pattern:

import re

def cleaning2(text):
    text = re.sub(r'\b(?:(?:https?|ftp)://)?\w[\w-]*(?:\.[\w-]+)+\S*(?<![.,])', ' ', text.lower())
    words = re.findall(r'[a-z.,]+', text)
    return ' '.join(words)


Web page downloader that supports redirects

HttpClient and associated classes provide most of the desired behavior.

HttpClientHandler already has the ability to follow redirection responses out of the box with AllowAutoRedirect property. You can also specify how many redirections to allow.

That can be extracted out into a function

static HttpMessageHandler CreateHandler() {
    var handler = new HttpClientHandler();
    // if the framework supports redirect configuration
    // set max redirect to the desired amount. The default is 50
    if (handler.SupportsRedirectConfiguration) {
        handler.AllowAutoRedirect = true;
        handler.MaxAutomaticRedirections = 5;
    }
    // if the framework supports automatic decompression
    // set automatic decompression
    if (handler.SupportsAutomaticDecompression) {
        handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip |
            System.Net.DecompressionMethods.Deflate;
    }
    return handler;
}

Creating multiple instances of HttpClient can cause an exhaustion of available sockets, so it is suggested to try keeping one instance for the duration of the application.

Specify a short time out duration for slower responses to help with time management.

static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
    var handler = CreateHandler();
    return new HttpClient(handler) {
        Timeout = TimeSpan.FromSeconds(3)
    };
});

Timeout can be adjusted to specific needs.

Cancellation tokens can also be used to help with time management.

Seeing as any exception is just being rethrown, then there is really no need for the try/catch. The exception would be handled by the caller.

HttpClient uses an asynchronous API. Its dependents should also be asynchronous all the way through and avoid blocking calls like .Result or .Wait to avoid deadlocks.

The refactored helper now looks like this

/// <summary>
/// Download html from an Internet page.
/// </summary>
public class NetworkHelper {
    static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
        var handler = CreateHandler();
        return new HttpClient(handler) {
            Timeout = TimeSpan.FromSeconds(3)
        };
    });

    static HttpMessageHandler CreateHandler() {
        var handler = new HttpClientHandler();
        // if the framework supports redirect configuration
        // set max redirect to the desired amount the default is 50
        if (handler.SupportsRedirectConfiguration) {
            handler.AllowAutoRedirect = true;
            handler.MaxAutomaticRedirections = 5;
        }
        // if the framework supports automatic decompression
        // set automatic decompression
        if (handler.SupportsAutomaticDecompression) {
            handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip |
                System.Net.DecompressionMethods.Deflate;
        }
        return handler;
    }

    /// <summary>
    /// Get the html structure of a site.
    /// </summary>
    /// <param name="url">Represents the URL of the page where to download the data.</param>
    /// <returns>Return a string that contains the html of the site.</returns>
    public async Task<string> GetHtmlAsync(Uri url, CancellationToken cancellationToken = default(CancellationToken)) {
        var response = await httpClient.Value.GetAsync(url, cancellationToken);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
}

And used

//...

var client = new NetworkHelper();
var html = await clien.GetHtmlAsync(uri);


How to get the Split value from collection?

Naming
I don't get the _ underscore prefix. This typically identifies a private field (albeit controversial). I'm pretty sure there's a consensus about simple camelCasing for local identifiers.
The name _websiteList is a bad one, for two reasons:

It's of type WebSiteAddress, which has words Web and Site; the name isn't following the established casing convention, should be _webSiteList.
It's tying the variable to its type. Would the name still make sense if the type was WebSiteAddress[]?

A better name would be, simply, webSiteAddresses.
Typing
If you want to use LINQ, you're targeting .NET 3.5+. Therefore, you can use implicit typing to improve the readability (and possibly the maintainability) of your code (although that's possibly personal preference).
Consider:

var webSiteData = _divider[1].Split('=');

The SO answer gives you a nice LINQ-oriented approach.


Execute .NET Core 3.1 background worker tasks simultaneously

Async method out-of-the-box is using multiple threads for continuations. (Everything after await is continuation). Exception of this rule if existing SynchronizationContext. Don't Task.Run asynchronous I/O-bound operation, do it only for synchronous CPU-bound one. Asynchronous programming, SynchrinizationContext & TaskScheduler.
Mixing .ContinueWith and await is not recommended as it doing the same but using different coding pattern. Mixing patterns with no reason makes the code more complicated.

If I were you, the code could look like this:
public class Worker : BackgroundService
{
    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // all methods will throw OperationCanceledException if cancellation was happened,
        // then checking if it was canceled is a kind of redundancy here.
        while (true)
        {
            var task1 = MethodOneAsync(stoppingToken);
            var task2 = MethodTwoAsync(stoppingToken);
            await Task.WhenAll(task1, task2, Task.Delay(10000, stoppingToken)); // inlining Task.Delay here changes the logic: 10 seconds counted between starts of two iterations not between finish of previous and start of next.
        }
    }

    private async Task MethodOneAsync(CancellationToken stoppingToken)
    {
        Debug.WriteLine($"MethodOneAsync started @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
        await Task.Delay(1000, stoppingToken);
        Debug.WriteLine($"MethodOneAsync finished @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
    }

    private async Task MethodTwoAsync(CancellationToken stoppingToken)
    {
        Debug.WriteLine($"MethodTwoAsync started @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
        await Task.Delay(1000, stoppingToken);
        Debug.WriteLine($"MethodTwoAsync finished @ {DateTime.Now:dd.MM.yyyy HH:mm:ss.ffff}");
    }
}

About Worker class purpose. It looks like Scheduler not Worker because it repeats some work continuously. Consider to change its name.


Google Apps Script shifting columns containing specified substring - using array functions

Just as a general note, you could avoid the temporary array by copying the array from the end. I would also use a temporary variable for simplicity:

for (r = 0; r < vals.length; r++) {
  var row = vals[r], first=row[0];
  if(first.indexOf("PO") != -1)||first.indexOf("P0") != -1)) {
    for (var c = row.length; c > 0' c--) {
      row[c] = row[c-1];
    }
    row[0] = "";
  }
}

However in this case you can let JavaScript do all the work:

  if(first.indexOf("PO") != -1)||first.indexOf("P0") != -1)) {
    row.splice(0, 0, "");
  }

Also, assuming you only need to support recent browsers, I would look at using methods like forEach and includes.


How about this?

def zipWith[A, B](ts: Traversable[Traversable[A]])(f: Traversable[A] => B): Traversable[B] = {
  ts.transpose.map(f)
}

Example:

scala> zipWith(input)(_.mkString("::"))
res10: Traversable[String] = List(1::4::7, 2::5::8, 3::6::9)


Remove specific CSS rules from WYSIWYG text

As selectors are static(known beforehand) and are not going to change, there is no need to use RegExp constructor syntax to create regex. By saying that,

var selector = "a:link, span.MsoHyperlink";
var pattern = new RegExp(selector.replace(/\./g, "\\.") + "\\s*{[^}]*?}", "gim");

seems unnecessary. With these two statements, you're creating two extra variables, an additional replace and then creating a regular expression from string.
Same is for other selector too.

What if there are 10 more CSS rules to be removed? Will you create 10 more strings, 10 more regex and 10 replacements? And what if there are 100 such rules?

The point is, this is not maintainable solution and the code written is way too much for string removals.

  possibly combine the two RegExp instances, and make sure that multiple instances of this are being removed?

The two regex can be combined using OR condition in regex with g flag to replace all occurrences.

First, using regex literal syntax to create regex

var linksRegex = /a:link, span\.MsoHyperlink\s*{[^}]*?}/gim; // First selector regex

and

var visitedLinksRegex = /a:visited, span\.MsoHyperlinkFollowed\s*{[^}]*?}/gim; // Second selector regex

Using OR condition(|), the two regex can be combined as

/a:link, span\.MsoHyperlink\s*{[^}]*?}|a:visited, span\.MsoHyperlinkFollowed\s*{[^}]*?}/

This works. But, there is duplication of the part \s*{[^}]*?} which can be removed using groups

/(a:link, span\.MsoHyperlink|a:visited, span\.MsoHyperlinkFollowed)\s*{[^}]*?}/

I'll suggest to use \s* instead of space between two selectors which will match any number of any space characters(space, tab, vertical tabs, etc.)

/(a:link,\s*span\.MsoHyperlink|a:visited,\s*span\.MsoHyperlinkFollowed)\s*{[^}]*?}/

To match the CSS rule properties of a selector use [\s\S]*?} where [\s\S] will match any character(space characters and non-space characters) thus no need of m flag anymore, while *? following it will make the regex lazy. See http://www.regular-expressions.info/repeat.html. Lazy repetition will match fewer characters to satisfy the following condition in regex. So, [\s\S]*?} will match anything until } character.

Note: . does not match new-line character even with m-multiline flag Demo. Work-around is to use [\s\S] which matches any character. See Javascript regex multiline flag doesn't work

With these changes the regex will become

/(a:link,\s*span\.MsoHyperlink|a:visited,\s*span\.MsoHyperlinkFollowed)[\s\S]*?}/gi

Here's demo.

Final Code:

var regex = /(a:link,\s*span\.MsoHyperlink|a:visited,\s*span\.MsoHyperlinkFollowed)[\s\S]*?}/gi;

textArea.value = textArea.value.replace(regex, '');

Here's working demo in action to try it out.

function replaceRules() {
  var regex = /(a:link,\s*span\.MsoHyperlink|a:visited,\s*span\.MsoHyperlinkFollowed)[\s\S]*?}/gi;

  var textArea = document.querySelector('textarea');
  textArea.value = textArea.value.replace(regex, '');
}
input {
  margin-bottom: 5px;
  color: green;
  padding: 5px;
}

textarea {
  width: 100%;
}
<input type="button" value="Remove problematic rules" onclick="replaceRules()" />

<textarea cols="40" rows="14">
body {
    background: red;
}

a:link, span.MsoHyperlink {
  mso-style-unhide: no;
  color: blue;
  text-decoration: underline;
  text-underline: single;
}

a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:purple;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}

a {
    color: gray;
}
</textarea>


Rotate a linked list to the right by k places

You started to write a class, but then stopped. You should continue. There are three things that are potentially \$O(n)\$ in this problem:

You need to know the length of the list.
You need to know the last node of the list.
You need to know the k-1th node of the list.

Two of those obviously go together, so you could justify writing a helper method that returns them both. The third one is arbitrary enough that there's not really any way to speed it up.

If you are in some kind of timed environment, you'll definitely want to wrap the list in a class and cache the last pointer and the size of the list.
If you do that, you can quickly compute k % size and then find #3, which will be \$O(n)\$.

If I were trying to write challenges for a timed competition, I would include a large list and k = 2 * n - 1.

I see several obvious methods in your code, including a more sophisticated constructor that could take an array (perhaps an outer LinkedList class), the length operation, the get_last operation, the get_item operation, the print or perhaps map operation, and obviously missing is the compare operation.

You should probably check for k == 0 before finding the last item. I can easily see a time-limit-exceeded trap being to construct a huge list, then do a rotate with k=0.


Determining length of a char* string in C++

What about:

std::cout << ::strlen("Plop Poop") << "\n";

While we are at it:

// use std::size_t to represent a size of something in memory
// It is non negative and is explicitly designed so it can represent
// the biggest in memory object.
//
// Pass C-String as 'char const*' (or const char* (samething))
// The compiler will automatically add a const to objects if required.
// BUT it will never remove a const (apart from 1 special case see below).
// Also the type of a string literal is 'char const*` (for the language lawyers yes it is an array but not relevant here as by the time we will see it is a pointer).
//
// Also, because you don't want to mutate the underlying string it gives
// you some slight protection from accidental assignment into the string.
std::size_t martinStringLen(char const* start)
{
    char const* end = start;

    // Look for the end of the string.
    // Your code increments two objects. I would just increment a single object
    // looking for the end of the string.
    for(;*end;++end){/*Empty*/}

    // The size is then just subtraction.
    return end - start;
}

// Unfortunately the special case is string literals: which is allowed to decay
// to char* for compatibility with old C code.

Other notes on your code:

int cpl(char * c)       // does work
int cpl(const char * c) // converts to char* so it can do work.

You have these two the wrong way around.
Make the int cpl(const char * c) version do the work. As noted above you are not mutating the object so it provides some slight protection from simple mistakes.

Also you will find the int cpl(char * c) version becomes unnecessary. As the compiler will automatically add const (ness) to parameters for you so you don't actually need the this version.

Other comments are same as @Konrad Rudolph

Note on the use of const.

If you put const on the right or left is a style thing. Peronally I always put it on the right. As there are a couple of corner cases (with typedef) were it does make a difference and I want to be consistent.

Note: cost always binds to the type on its left. unless it is the left-most part of a type declaration then it binds right. Read type right to left.

char const*       str1;  // const binds left to char  => (char const)*
                         // Read as: pointer to 'const char'

char const *const str2;  // const binds left => (char const) (* const)
                         // Read as: 'const pointer' to 'const char'

// From the C world (and it has leaked into C++) so a lot of people still us it
const char*       str3;  // const as left-most part binds right => (const char) *
                         // Read as: pointer to 'char const'

Basically str1 and str3 are identical. But the consistency of always thinking that const binds to the left makes it neater in my mind.

One place where it can make a difference is typedefs. This is because the typedef has already formed a type so any external const are applied to the typedef type as a whole thing (not as individual parts).

typedef char* String;
const String   str4;     // const is the left-most item so binds right.
                         // So you may expect this to be the same as str3

                         // unfortunately this is not correct as the typedef
                         // String a whole type so the const applies to `String`
                         // not to the char.

                         // Thus this is like const (char*)
                         // Which is the same as (char*) const
                         // Read: const 'pointer to char' so once set the pointer
                         // can not be moved.
 // If on the other hand you never put const in the left-most position then
 // this problem never even comes up.

So two reasons not to put const as the left-most part of the type.


MySQL queries to select messages related to a user, using UNION vs. OR

OR is really bad in Joins, in WHERE it can/should be replaced when the optimizer doesn't use indexes (and OR does).

I would prefer the Union for a simple reason, it's easier to write/understand/extend. Additionally the first two Selects are the same besides one condition, so combining them is simple.

And using aliases really simplifies reading the code.

  (SELECT dm.*
   FROM `direct_message`AS dm
   INNER JOIN direct_message_thread AS dmt
      ON dmt.chat_id = dm.id
     AND dmt.school_id = dm.school_id -- moved from WHERE as this is a join condition
   WHERE (dm.recipient_id = '10896' OR dm.creator_id = '10896')
     AND dm.school_id = '1'
   GROUP BY dm.id
   ORDER BY dmt.inserted DESC)

UNION ALL

  (SELECT dm.*
   FROM `direct_message` AS dm
   INNER JOIN direct_message_thread AS dmt
      ON dmt.chat_id = dm.id
     AND dmt.school_id = dm.school_id
   INNER JOIN direct_message_group AS dmg
      ON dmg.chat_id = dm.id
   WHERE dmg.staff_id = '10896'
     AND dm.school_id = '1'
   GROUP BY dm.id
   ORDER BY dmt.inserted DESC)


Multithreading, shared queue as synchronization point

Not a Queue!

First and foremost, your SharedQueue isn't a queue. You can only store one element in it at a time. That doesn't make it super useful - what if the producer wants to write two images?

queue.setImage(img1);
queue.setImage(img2); // blocks?

It's more of a guarantee-one-at-a-time container. A queue would be much more useful, so I'd consider actually implementing one. This is a pretty major design flaw.

Beyond that, I just have minor comments.

Move semantics

You have a lot of copies where you can do moves. For instance, in SetImage():

next_image_ = image;

should be:

next_image_ = std::move(image);

Moving is cheaper than copying (no need to incur reference counting).

Checking shared_ptr

You don't need to use .get(), you can directly check the shared_ptr:

image_processed_.wait(lock, [this]{
   return !next_image_ || stop_;
});

Clear()

You use a std::unique_lock<> to Clear() where a std::lock_guard<> is sufficient. You use the correct one in SetFinish().


Combining four functions for toggling gallery displays

The way I have read the code, it looks like you can see 1 gallery at a time or the home links but not both.

It's not much of a saving in code, but you could simplify it a little and assume that if artists-home is clicked that all galleries fade out.

            Ken
            Kina

   $('.gallery-home').click(function( e ){
        e.preventDefault();
        $('.gallery').fadeOut(function() {
            $('.artists-home').fadeIn('slow');
        });
    });

Then for showing the gallery we could use a data tag instead of class names to identify the links and galleries, then you could easily extend the code to include more galleries, with no extra js

$('.artist').click(function( e ){
    e.preventDefault();

    var artist = $(this).data('artist');

    $('.artists-home').fadeOut(function() {
        $('.gallery[data-artist' + artist + ']).fadeIn('slow');
    });
});

Please note, this code is not tested, I might have missed something


Fast way to count the numbers that are divisible by their own sum of digits inside a range

Compile without profiling, but with optimizations turned on.

bissbook:divSumDigits bisserlis$ ghc -prof -fprof-auto -rtsopts original.hs
[1 of 1] Compiling Main             ( original.hs, original.o )
Linking original ...
bissbook:divSumDigits bisserlis$ ./original +RTS -s
806095
  44,577,697,768 bytes allocated in the heap
      81,431,504 bytes copied during GC
          62,504 bytes maximum residency (2 sample(s))
          23,392 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0     85945 colls,     0 par    0.48s    0.57s     0.0000s    0.0001s
  Gen  1         2 colls,     0 par    0.00s    0.00s     0.0002s    0.0002s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time   22.36s  ( 22.79s elapsed)
  GC      time    0.48s  (  0.57s elapsed)
  RP      time    0.00s  (  0.00s elapsed)
  PROF    time    0.00s  (  0.00s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time   22.85s  ( 23.35s elapsed)

  %GC     time       2.1%  (2.4% elapsed)

  Alloc rate    1,993,498,737 bytes per MUT second

  Productivity  97.9% of total user, 95.8% of total elapsed

bissbook:divSumDigits bisserlis$ rm *.hi *.o
bissbook:divSumDigits bisserlis$ ghc -O2 original.hs
[1 of 1] Compiling Main             ( original.hs, original.o )
Linking original ...
bissbook:divSumDigits bisserlis$ ./original +RTS -s
806095
  12,176,087,768 bytes allocated in the heap
       4,273,680 bytes copied during GC
          44,416 bytes maximum residency (2 sample(s))
          21,120 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0     23449 colls,     0 par    0.09s    0.11s     0.0000s    0.0001s
  Gen  1         2 colls,     0 par    0.00s    0.00s     0.0002s    0.0002s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    2.87s  (  2.93s elapsed)
  GC      time    0.09s  (  0.11s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    2.96s  (  3.04s elapsed)

  %GC     time       3.0%  (3.7% elapsed)

  Alloc rate    4,237,427,802 bytes per MUT second

  Productivity  97.0% of total user, 94.6% of total elapsed

(Note the Total   time lines, 22.85s and 2.96s.)

I can't appreciably increase the performance any further, but I do have a couple stylistic notes.

Data.Char provides a function digitToInt :: Char -> Int, which makes writing digits much easier.

import Data.Char (digitToInt)

digits :: Int -> [Int]
digits = map digitToInt . show

No need to use list comprehensions and boolean double-checking in rangeDivisibleSumDigits, just write it as a filter on the range.

rangeDivisibleSumDigits :: Int -> Int -> [Int]
rangeDivisibleSumDigits start end = filter isDivisibleSumDigits [start..end]

sumDigits and lengthRangeDivisibleSumDigits are unnecessary functions, their names are pretty much as long as their implementations! They clutter up the top-level, they don't do anything surprising or interesting, I'd just use their implementations wherever you need to instead of adding another function to your mental burden.


Implement function in doubly linked list

Design

Why do you need a create_head_node() that takes a node as the first parameter? Seems counter intuitive. Personally I would just remove that function does not seem needed to me.

The other thing is that you don't seem to have a way to initialize an empty list (yes this can simply be the NULL pointer but it does leave it easy to accidentally have an uninitialized list).

You can make the design better by separating Node and the list into different types. That way a lot of the work for tail is removed.

i.e. It is easy to have A List and a Node.

struct Node;
struct List;
typedef struct Node Node;
typedef struct List List;

struct List
{
    Node*   head;
    Node*   tail;
    int     count;
};

struct Node
{
    int     value;
    Node*   next;
    Node*   prev;
};

Code Review

The create_head_node() seem to be more like reset the head node to this value and leak the rest of the list.

node *create_head_node(node *head, int point){
    head->point=point;
    head->p_node=NULL;
    head->n_node=NULL;
    return head;
}
----
node*  list = NULL;
list = insert_head(list, 10);
list = insert_head(list, 20);

/*
 * now lets reset the head to 30 and leak the tail (20)
 */
list = create_head_node(list, 30);

Why does it matter if there is currently no head node?

node *insert_head(node *head, int point){
    if (head==NULL){
        printf("no head exist");
        return 0;
    }

Can't I add to the head of an empty list?
Also why are you returning 0. That is an integer. An empty pointer is represented by NULL.

Again I am not sure we I can add to the tail of an empty list.

void insert_tail(node *head, int point){
    if (head==NULL){
        printf("no head exist");
        return;
    }

node *insert_at(node *head, int point, int pos){

Yes sure it is an error.

    while (pos>count)
    {
        printf("choose %d positions to add. choose again: ", count); scanf("%d", &pos);
    }

But this code can not determine the context that it is being used within. So it should not be generating an error message. You should be returning some form of status for the calling code to check. If the calling code decides an error message is appropriate then it can print the error message.

This is called the separation of concerns. Code either handles resource management (creating an maintaining a linked list) or it handles business logic (deciding if an error is critical or how to inform the user about errors).

Does this section not look exectly like insert_head()?

        node *temp=(node*)malloc(sizeof(node));
    temp->point=point;
    temp->n_node=p;
    temp->p_node=p->p_node;
    if(p->p_node!=NULL) p->p_node->n_node=temp;
    p->p_node=temp;
    return head;

int count_node(node *head){
    ....
    free(p);

You are freeing nodes that are still in the list?

A Simpler version;

#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>

struct Node;
struct List;
typedef struct Node Node;
typedef struct List List;

struct List
{
    Node*   head;
    Node*   tail;
    int     count;
};

struct Node
{
    int     value;
    Node*   next;
    Node*   prev;
};

List* createList();
void  destroyList(List* list);

int   countList(List* list);

bool insertHead(List* list, int value);
bool insertTail(List* list, int value);
bool insertAt(List* list, int value, int pos);

bool deleteHead(List* list);
bool deleteTail(List* list);
bool deleteAt(List* list, int pos);

typedef void (*Action)(int);
void visitNode(List* list, Action action);

/* Don't define a print function.
 * Use the visitor pattern to visit each node.
 * Then printing the list can simply be a function that prints each node as it is visited.
 */

/* Private Function */
Node* allocateNewNode(int value, Node* next, Node* prev)
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->value = value;
    newNode->next  = next;
    newNode->prev  = NULL;
    return newNode;
}

List* createList()
{
    List* newList = (List*)malloc(sizeof(List));
    newList->head = NULL;
    newList->tail = NULL;
    newList->count = 0;
    return newList;
}
void  destroyList(List* list)
{
    /*
     * remove all elements
     */
    Node* head;
    Node* next;
    for(head = list->head;head;head = next) {
        next = head->next;
        free(head);
    }
    /*
     * remove the list
     */
    free(list);
}
int countList(List* list)
{
    return list->count;
}

bool insertHead(List* list, int value)
{
    Node* newNode = allocateNewNode(value, list->head, NULL);
    if (list->head) {
        list->head->prev = newNode;
    }
    list->head = newNode;
    if (list->tail == NULL) {
        list->tail = newNode;
    }
    ++newList->count;
    return true;
}
bool insertTail(List* list, int value)
{
    Node* newNode = allocateNewNode(value, NULL, list->tail);
    if (list->tail) {
        list->tail->next = newNode;
    }
    list->tail = newNode;
    if (list->head == NULL) {
        list->head = newNode;
    }
    ++newList->count;
    return true;
}
bool insertAt(List* list, int value, int pos)
{
    if (pos == 0) {
        return insertHead(list, value);
    }
    if (pos >= list->count) {
        return insertTail(list, value);
    }

    Node* loop = list->head;
    while(--pos) {
        loop = loop->next;
    }
    Node* newNode = allocateNewNode(value, loop->next, loop);
    if (newNode->next) {
        newNode->next->prev = newNode;
    }
    if (newNode->prev) {
        newNode->prev->next = newNode;
    }
    ++newList->count;
    return true;
}

bool deleteHead(List* list)
{
    Node* old = list->head;
    if (list->head) {
        list->head = list->head->next;
        if (list->head == NULL) {
            list->tail = NULL;
        }
        --newList->count;
    }
    free(old);
    return true;
}
bool deleteTail(List* list)
{
    Node* old = list->tail;
    if (list->tail) {
        list->tail = list->tail->prev;
        if (list->tail == NULL) {
            list->head = NULL;
        }
        --newList->count;
    }
    free(old);
    return true;
}
void visitNode(List* list, Action action)
{
    Node* loop = list->head;
    for(;loop;loop = loop->next) {
        action(loop->value);
    }
}

void printInt(int value)    {fprintf(stdout, "%d ", value);}
void printList(List* list)  {visitNode(list, printInt);}


user3629249's answer is good. The only thing I have to add:

struct csv_line *line_pointer = NULL;

// ...

&(line_pointer + i)->value1

is awkward. Why go through the pointer addition acrobatics? Why not just

&line_pointer[i].value1


Script to access genealogy API for list of users and attributes

'''
This is a script to access the stackexchange api
    for the genealogy site
    and create a list of user dictionaries
'''

# use requests module - see http://docs.python-requests.org/en/latest/user/install/#install
import requests

# use pretty print for output

That's a pretty useless comment. It doesn't really tell me anything I didn't already know from the import

import pprint

# save output in file in format compatable with eval
#   I didn't use json or yaml since my intent is to continue on using
#   the parsed output so saves a parse step

eval also has a parse step. So you aren't saving anything by avoiding json.

pytFilename = "users.pyt"

python convention is for constants to be in ALL_CAPS

# use se api and access genealogy site
#   see https://api.stackexchange.com/docs/users for api info
url='https://api.stackexchange.com/2.1/users'
site = 'genealogy'

urlParams = {}
urlParams['site'] = site
urlParams['pagesize'] = 100
urlParams['order'] = 'desc'
urlParams['sort'] = 'reputation'

Why not put all these parameters into a single dict literal?

page = 1
notDone = True
userList = []

Python convention is for local variables to be mixed_case_with_underscores.

# replies are paginated so loop thru until none left
while notDone:
    urlParams['page'] = page
    # get next page of users
    r = requests.get(url,params=urlParams)

avoid single letter variable names. It makes it harder to figure out what you are doing.

    # pull the list of users out of the json answer
    userList += r.json()['items']

I'd use userList.extend( r.json()['items']). Also given the number of times you access the json, I'd have ajson = r.json()` line and access the json data through that.

    # show progress each time thru loop, note only so many queries allowed per day
    print r.url
    print '\tquota remaining: %s' % r.json()['quota_remaining']
    print "\t%s users after page %s" % (len(userList),page)

    # prepare for next iteration if needed
    page += 1
    notDone = r.json()['has_more']

I'd do:

json = {'has_more' : True}
while json['has_more']:
     ...
     json = r.json()
     ...

As I think it's easier to follow then a boolean flag.

# output list of users to a file in a format readable by eval
open(pytFilename,"w").write( pprint.pformat(userList) )

This isn't recommended practice. In CPython this will close the file, but it won't if you are using one of the other pythons. Instead, it's recommend to do:

with open(pytFilename, 'w') as output:
     output.write( pprint.pformat(userList) )

And that will close the file in all implementations of python.

# validate it wrote correctly
#   note this  shoasw example of how to read
readList = eval( open(pytFilename,"r").read() )

print 'wrote %s as python evaluatable list of users' % pytFilename


Using Variables

score = 0
print ("\n" * 40)
print("Your score is:\n0")

You are setting the score to 0, then printing the value 0 as the score. What if you decided, that the player starts with 100 score points? You would have to change the value in two places. Since you already have the value in a variable, it is better to print the value of the variable. Like this: print('Your score is {0}'.format(score)) Note that I also removed the newline from the output, because Your score is 0 reads much more naturally than
Your score is:
0.

Using Functions

#Set up screen
wn = turtle.Screen()
wn.bgcolor("lightblue")
wn.title("Catch the Turtle")

This comment already reads like a function name, so pack the code inside of a function. This way you don't even need the comment, because the function name tells you all you have to know. It could look like this:

def setup_screen():
    wn = turtle.Screen()
    wn.bgcolor("lightblue")
    wn.title("Catch the Turtle")

Even better you can add parameters, to be able to easily change how the screen is setup without having to read and change the setup code:

def setup_screen(background_color, title):
    wn = turtle.Screen()
    wn.bgcolor(background_color)
    wn.title(title)

That way you achieve a good level of abstraction, where you don't have to read all of the details everytime you want to change something.

The same applies to many more blocks of code that begin with such a comment that sounds like "do this and that".

Logic and Bugs

#Title
t=turtle.Pen()
t.pencolor("Blue")
t.hideturtle()
t.penup()
t.setposition(-70,350)
t.write("Catch the turtle", font=("Verdana", 18))

#Tip
text=turtle.Pen()
t.pencolor("Red")
t.hideturtle()
t.penup()
t.setposition(-70, -350)
t.write("DON'T TOUCH THE EDGES!", font=("Verdana", 18))

In the second block, you are first initializing a variable text, but then you continue using the variable t that you used in the block before. This way you are changing values that you already set, and not changing others that you expect to be changed. I think all occurences of t in the second block should be text instead. However, if you were using functions as I explained above, this problem would not occur and you would be less likely to get this bug, which is probably caused by copy-pasting code and forgetting to change it.

#Boundary check
if player.xcor() > 300 or player.xcor() < -300:
    print("GAME OVER")
    quit()

if player.ycor() > 300 or player.ycor() < -300:
    print("Game OVER")
    quit()

This is redundant. You have the same code twice, with just different conditions. You can already see why this is bad: You typed the output strings differently without realising, so in some cases when the player is out of bounds the output will be GAME OVER, in some cases it will be Game OVER. This is a bug, and a very simple example of bugs being introduced or at least made much harder to find by redundant code.

To fix it you can either combine the logical expressions into one condition:

#Boundary check
if (player.xcor() > 300 or
    player.xcor() < -300 or
    player.ycor() > 300 or
    player.ycor() < -300):
    print("GAME OVER")
    quit()

Or, even better, define a function to check the bounds (this is way more readable and maintainable):

def is_player_in_bounds():
    return (player.xcor() < 300 and
            player.xcor() > -300 and
            player.ycor() < 300 and
            player.ycor() > -300)

Note that I inverted the logical expression, because I check for in bounds, not for out of bounds. Then you use it like this:

if not is_player_in_bounds():
    print("GAME OVER")
    quit()

#Collision checking
d= math.sqrt(math.pow(player.xcor()-goal.xcor(),2) + math.pow(player.ycor()-goal.ycor(),2))
if d < 20 :
    goal.setposition(random.randint(-300,300), random.randint(-300, 300))
    score = score + 1
    print ("\n" * 40)
    print("Your score is")
    print (score)

d is a very bad name for a variable. Since this looks like a calculation of Euler distance, I assume that it is supposed to mean distance, so better call your variable distance or at least dist.

You can write score += 1 here to make it shorter.

You might want to put the ouput code into a function (e. g. print_score()), to separate logic from I/O.

math.sqrt(math.pow(player.xcor()-goal.xcor(),2) + math.pow(player.ycor()-goal.ycor(),2)) is hard to read, because of the formatting, and because it is a long formula with variable names, namespaces and method/function calls. Better put it in a function:

def euler_distance(player, goal):
    distance_x = player.xcor() - goal.xcor()
    distance_y = player.ycor() - goal.ycor()
    return math.sqrt(distance_x ** 2 + distance_y ** 2)

Using a ** b for exponentiation is faster and looks cleaner than using math.pow(). Note that player and goal are local variables here, even if they have the same name as the global ones.

Use the function like this:

if euler_distance(player, goal) < 20:
    goal.setposition(random.randint(-300, 300), random.randint(-300, 300))
    score += 1
    print_score()

Even better if you would define the bounds somewhere as variables and access them that way.

Redundance

#Set speed
speed = 1

This comment tells you nothing about the code that the code does not already tell you. It just bloats the code and requires you to read more redundant information. When you read speed = 1, it is perfectly clear that the speed is being set. Comments should tell you why the code does something (if needed), while the code tells you what it does.

def turnleft():
    player.left(30)

def turnright():
    player.right(30)

These functions do not add any value. (Hint: Just after reviewing these functions I saw why they are defined, which is using them for event handling. In this case they do add value, but I will leave the info for understanding.) player.left(30) gives you more information than turnleft(). If you read turnleft() somewhere in your code, you do not know what is turned, you do not know how much it is turned. Whenever you want to write a function that only contains one or two lines, think about whether the one line or two lines would be more readable and give you more valuable information.

def increasespeed():
    global speed
    speed +=0.5

def decreasespeed():
    global speed
    speed -= 1

Here we have the same, but even worse: The functions change global state, which can make it much harder to find bugs. Try to avoid that whenever possible. Furthermore, speed += 0.5 and speed -= 1 already tell you that the speed is increased/decreased, and they tell you how much they are changed, which is valuable information. If your only reason for defining these functions is that you can easily change how much the speed is increased/decreased, define variables instead and do speed += SPEED_INCREASE. Writing it in uppercase later reminds you not to change it.

#Set keyboard binding
turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(increasespeed, "Up")
turtle.onkey(decreasespeed, "Down")

Since we said above that not defining these functions might be better, you can use lambdas as callbacks. Lambdas are anonymous functions, that means you do not have to define them with def, but you can just use them where you need them. In the cases where you just change a variable however, you will still need the function. This is what it could look like:

#Set keyboard binding
turtle.listen()
turtle.onkey(lambda: player.left(30), "Left")
turtle.onkey(lambda: player.right(30), "Right")
turtle.onkey(increasespeed, "Up")
turtle.onkey(decreasespeed, "Down")


The #1 improvement you can make for code readability is adding comments. Plain code, even the most expressive plain code, rarely makes any sense on its own. In addition to comments, a use case showing the code in action is very helpful. Tests, too.

As for the code itself:

bool must_be_2x2(std::vector<std::vector<std::string>>& letters)

Vectors of vectors are rarely a good idea, and never a good idea for matrices. If you want a 2×2 matrix, you have to allocate three vectors: the vector for the matrix itself, then one vector per row. If you fail to properly allocate every row vector, you'll probably end up triggering UB.

Plus, accessing elements is slow. When you want to access an element of a vector of vectors, first the base vector has to be accessed and loaded... then the row vector has to be accessed or loaded. That's twice as many dives into main memory, which is painfully slow. And cache misses are more likely because a vector of vectors takes up more memory.

You can see the headaches yourself right in the code of must_be_2x2()... which, by the way, I think you have messed up the logic. A 2×2 matrix done as a vector of vectors would look like { { a, b }, { c, d } }. There are at least three ways to have a matrix less than 2×2:

{ { a, b } }: a 1×2 matrix.
{ { a }, { b } }: a 2×1 matrix.
{ { a, b }, { c } } or { { a }, { c, d } }: a ragged row matrix with 2 rows, and one row with 2 elements while the other row has 1 element.

must_be_2x2() ultimately "correctly" detects all 3 failure conditions (and I put "correctly" in quotes because it doesn't correctly work, but we'll get to that)... but it only seems to do so by a fluke. If I pass in a 1×2 matrix like case 1, this function will not return false... it will throw an exception. That's because you check the size of row 1 and row 2... but you never check that there are actually 2 rows. If there are 0 rows, calling letters.at(0) or letters.at(1) will throw; if there is only 1 row, calling letters.at(1) will throw.

So for the function to work the way I think you want it to work - and I'm only guessing at that because, as mentioned, no comments to explain the intention - you would first need to test letters.size()... and only then check letters.at(0).size() and letters.at(1).size().

But there are a couple of other bugs in the function.

First, you should take the parameter by const reference, not non-const reference. You're not changing the input.

Second, MIN_SIZE shouldn't be an int. Vector's size() returns the vector's size_type, which will be unsigned, so you will be comparing signed and unsigned types... which is a big no-no.

Third, and most concerning: you are testing the size of each row as letters.at(N).size() > MIN_SIZE. That means that a 2×2 matrix will fail. Because 2 > 2 is not true. I think you really meant to use >=.

The "fixed" function might look like this:

bool must_be_2x2(std::vector<std::vector<std::string>> const& letters)
{
    constexpr std::vector<std::vector<std::string>>::size_type MIN_SIZE = 2;
    // or for less typing:
    // constexpr decltype(letters.size()) MIN_SIZE = 2;

    if (letters.size() >= MIN_SIZE && letters.at(0).size() >= MIN_SIZE && letters.at(1).size() >= MIN_SIZE)
    {
        return true;
    }

    return false;
}

But as I said, this still smells, because if you are dealing with matrices, vectors of vectors is a terrible structure. It's bloated, it's slow, and it's extra work because you have to maintain that each row is the same size.

When you need a multidimensional matrix in C++, the best solution is almost always to use a flat array or vector, and calculate the offsets yourself. You could wrap it in a class for easier use. To give the basic idea:

template <typename T>
class matrix2d
{
public:
    matrix2d(std::size_t rows, std::size_t cols) :
        _elements(rows * cols),
        _rows{rows},
        _cols{cols}
    {}

    auto element(std::size_t row, std::size_t col) -> T&
    {
        return _elements[_calculate_offset(row, col)];
    }

    auto rows() const noexcept { return _rows; }
    auto cols() const noexcept { return _cols; }

private:
    auto _calculate_offset(std::size_t row, std::size_t col) noexcept
    {
        return (row * _cols) + col;
    }

    std::vector<T> _elements;
    std::size_t _rows;
    std::size_t _cols;
};

With a matrix class like this (obviously filled out with all the useful methods you'll need), you should see significant performance gains. And your code can be much simpler. The bottom line is: don't use vectors of vectors - they're almost always the wrong choice.

std::string matrix_vector_to_string(std::vector<std::vector<std::string>>& matrix)

This function "works"... but is highly inefficient.

First, again, you should take the parameter by const reference.

But the real issue is that you are repeatedly concatenating strings. Each time you do this, you could be triggering a new memory allocation, copying the whole string, then a deallocation.

Instead, it might be worthwhile to figure out in advance how much memory in total you're going to need. For that you'll need two loops:

std::string matrix_vector_to_string(std::vector<std::vector<std::string>> const& matrix)
{
    auto size = std::string::size_type{0};
    for (auto&& row : matrix)
        for (auto&& elem : row)
            size += elem.size();

    std::string str;
    str.reserve(size);
    for (auto&& row : matrix)
        for (auto&& elem : row)
            str += elem;

    return str;
}

On to the next function.

bool alphabet_only(std::vector<std::vector<std::string>>& letters)

Now, this function - like the previous function - "works", but it is extremely inefficient. First you construct a string of all the strings in the matrix concatenated, and then check that everything in that is a letter. But... why? Why create the concatenated string? Why not just check the letters in the matrix?

bool alphabet_only(std::vector<std::vector<std::string>> const& letters) noexcept
{
    for (auto&& row : letters)
    {
        for (auto&& elem : row)
        {
            for (auto c : elem)
            {
                if (!std::isalpha(static_cast<unsigned char>(c)))
                    return false;
            }
        }
    }

    return true;
}

On to the next function:

bool equal_length(std::vector<std::vector<std::string>>& letters)

This function's name isn't exactly clear. What it's doing is verifying that every row of the matrix is the same length. The only reason this is necessary at all is because you're using a vector of vectors.

bool is_vowel(std::string element) noexcept

This function has a lot of problems.

First of all, the parameter should probably be passed by const reference, not by value.

Second, it can't really be noexcept. Inside the function you construct an array of 5 strings. The string constructors are not noexcept. (One would hope that the string uses the small-string optimization. But one shouldn't rely on it like this.)

Which leads to the question of why you're dealing with strings at all. As far as I can tell, you're dealing with only ASCII characters. You don't need strings for this. This function could take a char, and do the test using a static array<char, 5>. That would be noexcept, and a lot faster.

std::string find_vowel_square(std::vector<std::vector<std::string>>& letters)

Once again, this "works", but is not particularly efficient. It's a brute force search, which is bad enough, but what's particularly bad is that it's a brute force search over a vector of vector of strings. I don't think you could have chosen a more inefficient data structure if you'd tried.

Changing to a better data structure alone - like a vector<char> (possibly wrapped in a matrix class) instead of vector<vector<string>> - should net you significant benefits. In the worst case scenario, with a large enough data set that it won't all in cache, and a string without SSO, you could be looking at a speed-up of several thousand times.

But changing to a more efficient algorithm would be the biggest gain (especially because doing that would automatically mean changing to a better data structure). You don't need to read the entire matrix in to search for sub-matrices. In fact, you don't really need to store any part of the matrix at all.

All you need to do is create a vector of flags (call it flags) of the size of one matrix row. Then you read the first matrix row, and for each element that is a vowel, set the corresponding flag in the flag vector. Then for each subsequent row i, start by setting another flag (not one in the vector, call it previous_is_vowel_column) to false, then for each character j, if it is a vowel and flag[j] is true and previous_is_vowel_column is true... you're done. The result is to_string(i - 1) + '-' + to_string(j - 1). Otherwise, you set to previous_is_vowel_column to true if the current character is a vowel and flag[j] is true, and set flag[j] to true if the current character is a vowel, and move on. If you get to the end without a success, then you return the fail message.


Printing a calendar for a month based on user input

First improvement

  don't repeat yourself,  the dry principle

You have many elif statements that can be easily rewritten using a dictionary.

My final program has none at all. I rewrote your lst (also badly named) into a dictionary like this:

weekdays = {'Su':0,'M':1,'T':2,'W':3,'Th':4,'F':5,'Sa':6}

Now weekdays is used on 2 different locations to replace the long elif structure.

First elif block. Notice they all increment by 4. So I can use the value of the dictionary like this: weekdays[first_weekday]*4

Second elif block. Here you can use the same dictionary. Notice how weekdays[first_weekday] + current_day becomes a multitude of 7.

Second Improvement

You should rename the variables in your program to understand what they do. For example n should be renamed to number_of_days

A good way to follow are the PEP8 guidelines

Final Program

As you can see, this program not only is shorter but also far more readable

# I omitted comments because the names speak for themselves
number_of_days = int(input('Enter number of days in month: '))
first_weekday = input('First weekday of the month: ')

# Using a dictionary over a list is the biggest improvement in my opinion
weekdays = {'Su': 0, 'M': 1, 'T': 2, 'W': 3, 'Th': 4, 'F': 5, 'Sa': 6}
print('{:>3}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}'
      .format('Su', 'M', 'T', 'W', 'Th', 'F', 'Sa'))

# First elif block
print (weekdays[first_weekday]*4*' ' + '{:>3}'.format(1), end=' ')
for current_day in range(1, number_of_days+1):
    # Second elif block
    if (weekdays[first_weekday] + current_day) % 7 == 0:
        print ()
    print ('{:>3}'.format(current_day ), end=' ')


Computation of Prefix Free Codes with many repeated weight values in reduced space

1. Comments on your code

The Python style guide (PEP8) recommends using 4 spaces for each indentation step, and lowercase_words_with_underscores for variable names and function names. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers if you do.
In answer to your question in comments, assert statements are fine. It's usually a good sign when code includes them, because it shows that the programmer has thought about what needs to be true at each step of the algorithm.
The assertEqual calls, on the other hand, are not quite in the right place. It's a good sign to see test cases. However, it's not a good idea to intermix the test suite with the code like this, because it means that every time your program gets run or your module gets loaded, the test suite gets run. That's harmless here because the test cases are so short, but if the test suite took a lot of time to run, you'd normally prefer not to run it every time.

So I would suggest reorganizing the test code so that it uses the facilities in the unittest module. Which includes its own assertEqual method, saving you the need to write your own. See below for how you might do this.
The docstring of sourceOfFirstOfTwo seems confused. Python doesn't have "pointers" and it's best not to think in terms of pointers, but in terms of values. You should have written:

"""Given two lists of 4-tuples, return the one with the smallest first element."""

but in fact this doesn't completely describe the behaviour of the function because it doesn't say what happens if one of the lists is empty.
A confused or complicated docstring is often an indication that a function would profit from being simplified or generalized, and that's definitely the case here. The first thing to note is that sequences test true if they are non-empty, and false if they are empty, so the initial tests can be rewritten:

assert(leaves or graphs)
if not leaves:
    return graphs
elif not graphs:
    return leaves

Next, Python already compares tuples element-wise:

>>> sorted([(2,3), (1,4), (2,1)])
[(1, 4), (2, 1), (2, 3)]

so there is no need to split up your 4-tuples into their components. Instead you can write:

if leaves[0] < graphs[0]:
    return leaves
else:
    return graphs

which can be simplified to:

return min(leaves, graphs)

since lists compare element-wise too. But now that we've made these simplifications, there's nothing in this function that needs to know about leaves and graphs. Really, it's a function that takes two sequences, discards empty ones, and returns the smaller among the remaining ones. But you can see that there's nothing special about the number two here. So I would generalize this function in order to further simplify it, like this (just one line!):

def min_non_empty(*sequences):
    """Return the smallest of the non-empty sequences.
    Raise ValueError if all sequences are empty.

        >>> min_non_empty([1,2],[2,3],[])
        [1, 2]
        >>> min_non_empty([1,2],[1],[])
        [1]
        >>> min_non_empty([], [])
        Traceback (most recent call last):
        ...
        ValueError: min() arg is an empty sequence

    """
    return min(s for s in sequences if s)

Notice how I've used the docstring to provide examples of how the function can be called. Python's doctest module is capable of running these mini-tests and checking their output. (This feature doesn't substitute for a proper test suite, but it's a useful way to check examples in documentation.)

Note also that there's no need for an assertion any more because min raises ValueError if you don't give it any arguments.

But having done all that, I don't think we actually need this function at all. See below.
A data structure with more than a couple of elements becomes unwieldy to manipulate if you represent it as a tuple. You have to refer to its elements by index (like x[1]) in which case it is not clear what that element means, or else you have to break it down into its components.

It would be better to refer to the elements of your data structure by name. You could do this by creating a class, but the simplest thing to do here is to use a named tuple:

Graph = namedtuple('Graph', 'weight frequency left right'.split())

Instead of using 0 as a placeholder meaning "no left/right child", it's conventional in Python to use None. That way there's no risk of confusing it for a weight or a frequency.
Your Meld function lacks a docstring. What does it do and how to call it?
Your Meld algorithm isn't the same as the one in your blog. (The original paper is hidden behind a paywall and IEEE want to charge me $31 just to read it, so I am basing this on your blog instead.) The differences are as follows: (i) you separate the graphs into two lists, leaves and graphs, whereas Moffat and Turpin just maintain a single list A; (ii) you set first to be the smaller of the initial elements of leaves and graphs, whereas Moffat and Turpin set t to be the first element of A; (iii) similarly for second and u.

This causes some of the prefix trees to come out in a different order. For example, you have

>>> Meld([(1,2,0,0),(3,1,0,0)])
(5, 1, (2, 1, (1, 2, 0, 0), (1, 2, 0, 0)), (3, 1, 0, 0))

but I believe that Moffat and Turpin's algorithm would go through these steps:

A = [(1, 2), (3, 1)]
A = [(3, 1), (2, 1, (1, 2), (1, 2))]
A = [(5, 1, (3, 1), (2, 1, (1, 2), (1, 2)))]

I don't know if this difference is significant, but I thought I ought to mention it.

Update: you noted in comments that the reason for this difference is that the description of Moffat and Turpin's algorithm in your blog was incomplete in that the list A needs to be maintained in sorted order (or rather, it needs to be possible to efficiently fetch the smallest element from the list).

Maintaining a priority queue can be done efficiently in Python using the heapq module. I've revised my code below to show how to do this.
In the course of the algorithm you need to manipulate the list graphs by adding items at the right and removing items from the left. The latter operation is not efficient for ordinary Python lists: if you look at the TimeComplexity page on the Python Wiki you'll see that deleting an item from a list is O(n).

In order to modify a sequence at both ends efficiently, you need to use some other data structure. In many cases you could use the double-ended queue class collections.deque, but here since you need to be able to efficiently fetch the smallest item in the sequence, the heapq module is the one to use.
The meld function is not very useful by itself. As you comment in your blog post, any actual user will need a function that converts the list of weights into the (weight, frequency) pairs (collections.Counter would be a convenient and efficient tool to do this in Python), and a function that processes the resulting prefix tree into the codes. You'd probably want to add these functions to your code.

2. Rewrite

Putting all this together, here's how I'd write this code:

from collections import namedtuple
from heapq import heapify, heappush, heappop
from unittest import TestCase

Graph = namedtuple('Graph', 'weight frequency left right'.split())

def meld(graphs):
    """Given a non-empty list 'graphs' of Graph objects, return a
    minimum-redundancy prefix tree constructed using the algorithm of
    Moffat and Turpin (1998).

    """
    heapify(graphs)
    while True:
        t = graphs[0]
        if t.frequency > 1:
            if t.frequency % 2 == 0:
                heappop(graphs)
            else:
                graphs[0] = Graph(t.weight, 1, t.left, t.right)
            heappush(graphs, Graph(2 * t.weight, t.frequency // 2, t, t))
        elif len(graphs) > 1:
            assert(t.frequency == 1)
            heappop(graphs)
            u = graphs[0]
            if u.frequency == 1:
                heappop(graphs)
            else:
                graphs[0] = Graph(u.weight, u.frequency - 1, u.left, u.right)
            heappush(graphs, Graph(t.weight + u.weight, 1, t, u))
        else:
            assert(len(graphs) == 1 and t.frequency == 1)
            return t

class MeldTest(TestCase):
    def test(self):
        t = Graph(1, 1, None, None)
        self.assertEqual(meld([t]), t)

        u = Graph(1, 2, None, None)
        self.assertEqual(meld([u]), Graph(2, 1, u, u))

        v = Graph(1, 4, None, None)
        w = Graph(2, 2, v, v)
        self.assertEqual(meld([v]), Graph(4, 1, w, w))

        x = Graph(3, 1, None, None)
        self.assertEqual(meld([u, x]), Graph(5, 1, Graph(2, 1, u, u), x))

Notes:

There turned out to be no need for the sourceOfFirstOfTwo function.
The unit tests have been moved to a unittest.TestCase class. You can run all the unit tests from the command line like this:

$ python -munittest mymodule.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


Filter by a transformed list, then untransform the result

Exercise 1

If you have a lambda (or any function) of type (a,b)->c, instead of writting it like this (\x->...), you can write it like this (\(x,y)->...). It will remove the need of calling fst like in your skip function. You should change the name skip too, because it already exist in the prelude and it's kinda unclear because they have different meaning. I would call it something like skipEvery

Exercise 2

as is a keyword in Haskell, used for module importation. It will compile if you use it as a variable, but if you a text editor with syntax highlighting, it will be weird

  My instincts say that I could implement both of these something like
  this:

localMaxima' :: Integral a => [a] -> [a]
localMaxima' xs = filterBy isLocalMaximum sliding3 xs

Your instinct wasn't wrong, but there is an alternative to filterBy, which is mapMaybe. The resulting code would be something like this

whenMaybe p x = if p x then Just x else Nothing
localMaxima' = mapMaybe (whenMaybe isLocalMaximum) . sliding3

You should use zip instead of zipWith (,), because both operations are equivalent


There are not much to review, so to answer your questions:

It's a good extension if you can see it useful in more than one place.
It makes sense.
I can't see anything else to consider - a null check on the predicate maybe?
If the exception thrown by the predicate when @this is null is good enough for you, don't bother further.

I don't see why the restriction where T: class is necessary

If you always want to generate a string containing a list of properties (or another predefined format), you could change the signature to:

public static string ToString<T>(this T @this, params Func<T, object>[] getters)
{
  return string.Join(", ", getters.Select(g => g(@this)));
}

called as:

handler.GetUserById(id)?.ToString(p => p.LastName, p => p.FirstName)

so that you don't have to format the input when calling the extension.