Loop to streamline pandas dataframe to_sql

As far as I can see the only thing changing is the URL to the DB file.

You can just define a dictionary for this:

DB_URL = {"df1": "sqlite:///abc_Fares.db",
          "df2": "sqlite:///defg_Fares.db",
          ...}

I would also define the titles of the dataframes as a list:

titles = ["Truck Services", ...]

Which you can the easily use:

engine = create_engine(DB_URL[df_id])
connection = engine.connect()
for df, title in zip(dataframe_source, titles):
    df.to_sql(title, engine, if_exists="append")
connection.close()

Note that this calls to_sql directly on the dataframes, so no need for pandas.DataFrame(df, ...).

Also note that zip will stop after the shorter iterable is exhausted. So if the list of titles only contains four titles, the fifth dataframe will not be written to the DB.

Final code:

DB_URL = {"df1": "sqlite:///abc_Fares.db",
          "df2": "sqlite:///defg_Fares.db",
          ...}

def _format_data_frame(dataframe_source, df_id):
    """Format the dataframe source that is retrieved from 'my_function()' and put into SQL"""
    column_rename = {"Fare Per Ride (cent)": "Card",
                     "Unnamed: 2": "Cash",
                     "Card Fare Per Ride (cent)": "Card",
                     "Card Fare (cent)": "Card",
                     "Description": "Distance"}

    titles = ["Truck Services", "Feeder Services", "Express Services", "Other Services"]
    engine = create_engine(DB_URL[df_id])
    connection = engine.connect()
    # Since zip stops after the shorter iterable is exhausted, this
    # leaves the fifth df out
    for df, title in zip(dataframe_source, titles):
        if "Unnamed: 2" in df.columns:
            df.drop("Unnamed: 2", axis=1, inplace=True)
        df.rename(columns=column_rename, inplace=True)
        df.to_sql(title, engine, if_exists="append")
    connection.close()

Note that I also made the if "xxx" in each_dataframe.columns faster by storing the columns once per dataframe in a set, for which membership testing is \$\mathcal{O}(1)\$.

I also made the column renaming a lot easier. The dataframe will ignore all keys in the translation dictionary for which no columns exist, so we can use one common dictionary.

You should also include your imports, right now it is not clear where create_engine comes from. You should have a look if they implemented contextmanagers, so you could do:

with engine.connect() as connection:
    for df, title in zip(dataframe_source, titles):
            df.to_sql(title, engine, if_exists="append")

Where the connection.close() is done automatically.


Calculate mean and standard error of a generator in Python

I'd want to address the generator, to begin. :param generator: accepts no parameters and returns a vector is false. The generator returns a number (with floating point or not). This is pretty confusing. When I read the code at first, I thought the generator would be an iterable that returns numbers (like range(0,10) for example).

In that case you wouldn't need to pass both the parameters num_of_iterations and generators. Otherwise, I don't think the parameter should be named generator or maybe your documentation should be stronger.

Next thing, you shouldn't initialize sum = sumSquares = None this way. They are numbers, initialize them at zero, that would give you the opportunity to remove your if/else.

sum = sumSquares = 0
for i in range(num_of_iterations):
    x_i = generator()
    sum += x_i
    sumSquares = (x_i*x_i)

Apart from that, the coding style is a little off. Sometimes you use camelCase and sometimes snake_case.

If we were to have an iterator instead of the generator, you could do something like this :

def mean_and_stderr(iterator) -> (float,float):
    sum = sumSquares = 0
    for x in iterator:
        sum = x
        sumSquares = (x*x)

    mean = sum / num_of_iterations
    variance = sumSquares / num_of_iterations - (mean*mean)
    stderr = np.sqrt(variance) / num_of_iterations
    return (mean,stderr)


Is this a good way to track current site being reported on?

As you pointed out, relying on cookies means that the user can choose someone else's site. That means you should not use cookies at all, not even in addition to the session. If you choose to use cookies anyway, you have to validate that the current user actually has access to the selected site before returning any data (or even worse, before performing some action), which your code already does. You also have to be very careful that there isn't any code path that doesn't perform the validation.

Because of this, I think you should store the data in session only. If you need more persistent storage, use your database, not cookies.

Some points about your code:

return -1;

You shouldn't use “magic” values like -1 to indicate “no value”. Instead, change the return type to int? and return null of no site is selected.

Convert.ToInt32(…)
value.ToString()

This may not work well unless you're 100 % sure that all servers running this code will be on the same culture. You should probably use InvariantCulture here.

Also, if the cookie contains garbage, I think your code should return “no value” not throw an exception.


If you're trying to make a shell-like utility to encrypt and decrypt strings the cmd module is exactly what you want.

In order to add argument lists to each command you could use the argparse module similarly to the following.

def do_decrypt(self, arg):
    parser = argparse.ArgumentParser(prog='decrypt')
    parser.add_argument('--filename', type=file, help='The file to decrypt')
    parser.add_argument('--shift', type=int, default=13, help='The amount to shift')
    try:
        args = parser.parse_args([arg])
    except SystemExit:
        print('The previous command was not understood')

    text = del_punc(args.file)
    shift = -1*args.shift
    decrypted = cypher(text, shift)
    ...

Some people may complain that the SystemExit exception shouldn't be caught you could also create a class that subclasses argparser.ArgumentParser and overloads the argparser.ArgumentParser.error function


Should I include a view for each message?

I would strongly recommend you to go for the include solution. You will probably take a small performance hit, but that should not outweigh the benefits of having code that is much easier to maintain. Whenever you have to duplicate code, you are doing something wrong.

Also, if you find performance really important, may I suggest not sending the rendered (sub)view trough ajax. It would be much better to send just the data as JSON over the wire. It will be much smaller, and the server does not need to take time to render anything. You can then parse the JSON in your js to render the view there. There are templating languages for js that you could use, there is even a js version of twig (I haven't used it yet, so I don't know if it is any good, but I like the idea...)


I made some changes to your code, here's the description:

Indentation correction;
Removal of possible spaces in user input;
Change of While stat ==. True for While stat. It's the same thing;
PEP8 (and good practices) use 1 blank space after a comma and 2 line breaks before and after the functions;
You can also simplify the import of packages by specifying exactly what you are going to use: I did it in the code below;
Finally, the documentation always provides for an empty line break at the end of the code.

from time import time, sleep
from random import randint

logo = '''
  _____    __          _______  __  __
 |  __ \   \ \        / /  __ \|  \/  |
 | |__) |   \ \  /\  / /| |__) | \  / |
 |  ___/ | | \ \/  \/ / |  ___/| |\/| |
 | |   | |_| |\  /\  /  | |    | |  | |
 |_|    \__, | \/  \/   |_|    |_|  |_|
         __/ |
        |___/
'''
print(logo)
print(" ")
difficulty = input("Enter difficulty level (easy/hard): ").strip
if difficulty == "easy":
    openPlz = open('easywordbank.txt', 'r')
    readPlz = openPlz.read()
    wordBank = readPlz.split()
elif difficulty == "hard":
    openPlz = open('hardwordbank.txt', 'r')
    readPlz = openPlz.read()
    wordBank = readPlz.split()

open2 = open('highscore.txt', 'r+')
open2lst = open2.readlines()

stat = True
strike = 0
score = 0

def gameMain(wordBank):
    """
    Primary game loop. Returns a lst:
    #lst[0] = added points, lst[1] = added strikes
    :param wordBank:
    :return:
    """
    lst = [0, 0]
    start = time()
    wordQuiz = wordBank[randint(0,(len(wordBank)-1))]
    wordType = input('Enter the word, '+ wordQuiz + ' : ')
    if wordType == wordQuiz and time()-start < 3:
        lst[0] += 1
    elif time()-start >= 3:
        print('STRIKE! Too Slow! ')
        lst[1] += 1
    else:
        print('STRIKE! Watch your spelling. Be careful with strikes!')
        lst[1] += 1
    return lst

def highScore(name, score, highScoreLst, zFile):
    for line in highScoreLst:
        if score >= int(line[-3:-1]):
            highScoreLst.insert(highScoreLst.index(line), name+'-'+str(score)+'\n')
            highScoreLst.pop()
            zFile.seek(0, 0)
            zFile.writelines(highScoreLst)
            break

def rsg():
    print('Ready?')
    sleep(1)
    print('Set?')
    sleep(1)
    print('Go!')
    sleep(1)

name = input('Enter a username for this session: ')
print("Type the word then press enter in under 3 seconds!")
sleep(2)
rsg()

# MainState
while stat:
    lst = gameMain(wordBank)
    score += lst[0]
    strike += lst[1]
    if strike == 3:
        sleep(.5)
        print('Game Over! The game has ended..!\n')
        sleep(2)
        print('Your Typing & Accuracy Score: ' + str(score))
        highScore(name, score, open2lst, open2)
        sleep(2)
        break
print('\nHighscores for PyWPM:')
sleep(2)
for line in open2lst:
    print(line, end='')
    sleep(1.5)
sleep(5)

openPlz.close()
open2.close()


Some quick formatting tips:

You use whitespace sparingly. In the example code, there is a lot of room for more whitespace that makes the code more readable. Something like:

if (year % 400 == 0) {
    isLeapYear = true;
}

It makes the code more easier to read.

Also, and this is not a recommendation but just an option you may want to consider, but you can move the if-else to a new line. I've always found that easier to read, and I've noticed that some (not all) teachers of mine tend to find that good formatting.

So for example:

if(year%400==0) {
    isLeapYear=true;
}else{
    isLeapYear=false;
}

This code can be rewritten as:

if(year%400==0) {
    isLeapYear=true;
}
else{
    isLeapYear=false;
}

**As an aside, upon receiving further advice from co-users on CodeReview in the comments, it is better to use curly braces, even if they are solely for one command in an if-statement, as it will help in detecting the scope of the if-statement with more ease.


RAII pattern for downgradable ReadWriteLock

You didn't give a terrible amount of code to be reviewed, and I am not really proficient in concurrency and the like but I still got a few points I want to make.

But enough of introduction let's jump into the code:

public class RWLockWrapper implements AutoCloseable {

Wonderful, concise and clear. RWLockWrapper is a beatiful name for that class. You could have spelled it out, but that is definitely not much improvement in clarity.

I also like the design choice of implementing AutoCloseable. This makes your wrapper easy and obvious to use.

One big thing that's missing here: Documentation! I strongly suggest you write a little JavaDoc for this. It doesn't even need to be much, it should just explain the class in short and inform the user about the caveats of using it.

private final ReadWriteLock rwl;
private Lock current;

oh sweet joy! You made your ReadWriteLock read-only. I like that design choice for two reasons: You make clear that the Wrapper is usable for only one and exactly one Lock at a time, and additionally you cleanly make it impossible to do any different.

The name could be better, but it's a short class, so it's definitely not very detrimental to have a name like rwl.

As an aside: current could probably use a better name, but for the love of {higher entity of choice} I can't find a better one...

//RAII
public RWLockWrapper(ReadWriteLock rwl) {
    this.rwl = rwl;
    this.current = rwl.writeLock();
    this.current.lock();
}

The first thing that I really find not acceptable in your code is that comment.

It's utterly useless, and for me (who doesn't use locks all that much) uninformative and confusing. Again I strongly recommend you document what you are doing here.

As a no-experience user, I'd have some expectations to your class, and that you write-lock things, is definitely not the first thing I'd think :(

JavaDoc can really help a lot.

Additional minor nitpicks: I personally put a space between the name and the opening parens, I feel I can read that better.

public RWLockWrapper (ReadWriteLock rwl) {

Furthermore you are overqualifying current with this., which I don't like. I personally prefer to not use this wherever possible, but you may decide to do differntly so.

public void downgrade() {
    final Lock read = rwl.readLock();
    read.lock();
    try {
       current.unlock();
    } finally {
       current = lock;
    }
}

not much to say here. Again I'd prefer a little more whitespace, again missing documentation. Also you may want to mention in possible documentation, that the state of the Lock will always be locked read after calling this method.

Moving swiftly on. Where's the upgrade ()????

Confusion ensues

What, there is no upgrade?? I think you get it.
When you expose some downgrade (), I expect to also be able to upgrade ().

I don't really understand why you don't expose that method. I suspect you have no real need for it. I feel that upgrade/downgrade is a pair just like add/remove, create/destroy and similar.

That aside, moving swiftly on.

@Override
public void close() {
    current.unlock();
}

Hmmm.... Okay for the sake of the argument we assume, that calling unlock() will not throw any exceptions...

No. There is always the possibility for an execption to be thrown, even more so, when you don't really secure yourself against it...

But that aside, hypothetical question: What would happen if someone did the following

    RWLockWrapper myCoolLock = new RWLockWrapper(lockForTotallyImportantAndCriticalThing);
    //... do some important stuff.
}

Oh crap. Oh crap... Everything broke!!

I think you see what I am getting at. Given the case someone uses your wrapper wrongly, things can go wrong easily.

I suggest you consider adding:

@Override
public void finalize () {
    current.unlock();
}

Why that? To make sure, that your Lock does not stay locked when you can never unlock it again, because you lost it in a tangled mess of bits and bytes.

This should provide additional security to the wrapper even against non-proficient, blue-eyed or just plain {insert favourite insult, doubting intelligence} programmers.


At the danger of repeating myself (not to you, but generally regarding swing code):

Don't learn swing. Swing has been EOL'd for over a year now and has been officially superseded by JavaFX. If you want to learn GUI programming for thick clients in java: Go with JavaFX
Somebody has to have a tutorial that does this wrong ... UpdateVideos extends JFrame implements ActionListener is one of those lines that should make you shudder. It's a generally accepted wisdom that to write SOLID code, one should use Composition over Inheritance. This means that instead of saying "UpdateVideos is a JFrame" you should say: "UpdateVideos has a JFrame".
This is one of the things that every swing program seems to have and I find it terrifying: setVisible(true); in the constructor... This is a violation of two things. First: The principle of single responsibility (SRP), the S in SOLID. A constructor is responsible for getting the object it initializes into a usable, valid state. This does explicitly not entail making the JFrame inside the object (or the JFrame object itself) visible. Second: The principle of least surprise. Let's say you go to a coffee shop and order a coffee... would you expect the the coffee you get to pour itself down your throat? Sure you'll want to drink it sooner or later, but on your own terms. It's not the coffee's (or the JFrame's) responsibility to make sure that you drink (or show) it, but yours.

After getting this out of the way, let's talk about your code: Aside from the two coding issues I already mentioned above your code is pretty clean. The only thing that really bothers me is how many magic numbers you use.

There is a minor optimization in stars. Consider the following code:

private String stars(int rating) {
    final char[] stars = new char[rating];
    Arrays.fill(stars, '*');
    return new String(stars);
}

This avoids the overhead of concatenating Strings and instead uses a char[] to basically build the string without an explicit for-loop. This is just a marginal benefit though and you might want to keep your method structure, but use a StringBuilder instead to increase performance.


Nesting versus GOTO: which is better to avoid?

A different way is to let these pairs be represented by a class, which itself has a static factory method that will return null on failure.

public final class Pair {
    private String key;
    private String value;

    public Pair(key, value) {
        // TODO: Add proper argument checking/throw exceptions.

        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() [
        return value;
    }

    /**
     * Returns the string representation which looks like @{code key=value}.
     */
    @Override
    public String toString() {
        return key + "=" + value;
    }
}

And the static factory method:

/**
 * Constructs a Pair from the given string,
 * returns null if the string is misformed or
 * the string was null.
 *
 * A well formed input looks like {@code key=value} and
 * does not start with a {@code #} as that indicates comments.
 */
public static Pair fromString(String str) {
    // We do not accept nulls and empty strings.
    if (str == null || str.empty()) {
        return null;
    }

    // TODO: Figure out if trimming of str would be a good idea.

    // Skip comments.
    if (str.startsWith("#")) {
        return null;
    }

    String[] splitted = str.split("=");

    // We also do not accept anything else.
    if (splitted.length != 2) {
        return null;
    }

    // TODO: Are you accepting zero-length keys/values?

    return new Pair(splitted[0], splitted[1]);
}

It basically looks the same as your loop, with two important differences:

It's a method of its own, easily reusable, easily testable.
It has documentation what the input should look like.

Now to your loop:

for (String line : lines) {
    Pair pair = Pair.fromString(line);
    if (pair != null && !values.containsKey(pair.getKey())) {
        // TODO
    }
}

That does not only shorten the code inside the loop, but will in the end make it more readable because you're now using pair.getValue() instead of pair[1].

Based on the context of this I would suggest other names, though, like StringPair, Setting, SettingsPair or ConfigEntry.

Here is your loop with the log statements (assuming that the LOGGER has an overload that works similar to Logger.log(...)):

for (String line : lines) {
    Pair pair = Pair.fromString(line);
    if (pair != null) {
        if (!values.containsKey(pair.getKey()) {
            // TODO
        } else {
            LOGGER.debug("Pair is already assigned: {0}", pair);
        }
    } else {
        LOGGER.error("Skipping line: {0}", line);
    }
}

There are no fine-grained error messages there because it should be obvious from the input why the fromString function could not create the Pair.

Though we're back at two if-statemens with else branches, readability is a lot better.

This does violate Item 43 from Effective Java (2nd Edition) which goes like this:

  Return empty arrays or collections, not nulls

But why did I than suggest this approach? Effective Java states that it is better to throw fine grained exceptions rather then return null to ease dealing with the method. This is true for any sort of method, but it is not what this approach is supposed to do. We don't care what kind of problem there is, we just want an object that is usable for our program logic or move on, discarding fine grained errors in the process.

If you use this approach you need to keep some things in mind:

Don't use a constructor for this purpose but a static factory method.
Document the behavior and purpose of the static factory method thoroughly.
It should be obvious when seeing the input what the function returns.
Know when to use this and when to use exception handling (be aware why this is not a generic all-in-one solution to everything).
If this is inside a library/public API, always provide a way that does throw fine grained exceptions.

In case you're parsing ini or settings file with this which do not require "special" treatment, the answer from AJMansfield is correct.

  Do not roll your own version if java.util.Properties works for it.


First of all NEVER rescue ExceptionError. If you want a to rescue from any runtime exception, just omit exception class, otherwise you might catch SignalException which happens upon ruby process received some signal (e.g. SIGTERM) and instead of behave correctly you will silently skip that.

So, your rescue part should look actually like this:

begin
  # ...
rescue SocketError, Redis::CannotConnectError => e
  raise Puppet::Error, "connection to redis server failed - #{e}" unless default
  debug "Connection to redis failed with #{e} - Returning default value of #{default}"
  default
end

Now your main block can be also improved:

begin
  Redis.new(:url => url).get(key) || default
rescue
  # ...
end

Notice that redis returns either String or Nil, e.g.:

Redis.current.set(:x, 123)
Redis.current.get(:x) # => "123"

Redis.current.set(:x, false)
Redis.current.get(:x) # => "false"

So, summing all above together, you can form that into a method:

def redis_get(key, url:, default: nil)
  Redis.new(:url => url).get(key) || default
rescue SocketError, Redis::CannotConnectError => e
  raise Puppet::Error, "connection to redis server failed - #{e}" unless default
  debug "Connection to redis failed with #{e}; Return default: #{default}"
  default
end


Changing the foreground and background colors of substrings based on ANSI escape codes

You can do it a little more generic but I'm afraid you still have to test each.

I don't know if your case is always changing to green or not.
If not I suggest the following enum :

/**
 *
 * @author chillworld
 */
public enum ColorMapperEnum {
    GREEN("[30;42m",Color.GREEN) ,
    RED("[31;42m",Color.RED) ,
    BLACK("[32;42m", Color.BLACK) ,
    BLUE("[33;42m", Color.BLUE); // and so on

    private String textToFind;
    private Color targetColor;

    private ColorMapperEnum(String textToFind, Color targetColor) {
        this.textToFind = textToFind;
        this.targetColor = targetColor;
    }

    public String getTextToFind() {
        return textToFind;
    }

    public Color getTargetColor() {
        return targetColor;
    }
}

Now you can do a whole lot more generic in your java code :

for (ColorMapperEnum colorMapper : ColorMapperEnum.values()) {
    if(string.contains(colorMapper.getTextToFind()){
        index = string.indexOf(colorMapper.getTextToFind());
        string = string.replaceAll("\\" + colorMapper.getTextToFind(), "");
        backgroundColor = colorMapper.getTextToFind();
    }
 }

I did use the same naming as yo but I advice to take better naming.
String string => very bad, for what stands it?

Now I don't know if there could be a case that multiple conditions are true and what there must be done when multiple conditions are true.

An enum values() has always the same result in the same order.
Use that in your advantage when tackling that problem.


I'm not an expert, but I this line caught my eye:

volatile int m_acquireCount, m_releaseCount;

m_acquireCount and m_releaseCount will be part of the same cache line!

Therefor I expect no performance advantages compared to the simpler AtomicIncrement/AtomicDecrement on one variable.


Since your code is not huge and it seems clean so far, my suggestion will focus on your question about the best way to share controller data.

You could try the bindToController option when creating the modal, so it shares the same scope as the parent controller

In this post, you will find further information with an example.


A Class to Supply an Open Database Connection during the life of a Web Request

As far as I know, in ADO.NET the connection pooling is enabled by default, and if you don't need to pool connections, you'll have to explicitly disable pooling.

So, for your implementation, everything seems okay to me, but DbConnectionManager seems to be specific for handling the connection! so, BuildCommand method will be odd in this class!

I would prefer to rename it to something covers all exposed operations and keep everything simpler.

for GetOpenSqlConnection() this could be unnessary, since you can do it in the property level.

What I suggest is to make DbConnection & ConnectionString static, so you ensure you only have a single instance of SqlConnection. and create two constructors one takes SqlConnection, and the other one takes connectionString. you would have something like this :

public class DbConnectionManager : IDbConnectionManager
{
    // make it static to have a single instance
    private static SqlConnection DbConnection
    {
        get => DbConnection is null ? new SqlConnection(ConnectionString) : DbConnection;
        set => DbConnection = value;
    }

    // store the connectionString of SqlConnection, for connection backup.
    private static string ConnectionString { get; set; } = DbConnection.ConnectionString;

    public DbConnectionManager(string connectionString)
        : this(new SqlConnection(connectionString)) { }

    public DbConnectionManager(SqlConnection dbConnection)
    {
        DbConnection = dbConnection;
        ConnectionString = dbConnection.ConnectionString;
    }
}

in both constructors, they're initiating a new DbConnection and the ConnectionString is just backup, in case your actual DbConnection is lost, you can re-initiate it with the connectionString that you've stored.

doing that, it'll eleminate the need of :

private SqlConnection GetOpenSqlConnection()
{
    if (ReferenceEquals(DbConnection, null))
    {
        DbConnection = new SqlConnection(ConnectionString);
    }

    if (DbConnection.State != ConnectionState.Open)
    {
        DbConnection.Open();
    }

    return DbConnection;
}

for :

public IDbCommand BuildCommand(DbParameter[] parameters, string query)
{
    if (parameters == null) throw new ArgumentNullException(nameof(parameters));
    if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException(nameof(query));

    var command = new SqlCommand { Connection = GetOpenSqlConnection() };
    command.Parameters.AddRange(parameters);
    command.CommandText = query;

    return command;
}

Since there is no actual execution is going here, opening a connection here is not needed, because you built the command and return the instance back to execute it somewhere else. this may requires you to create two public methods for opening and closing connection before you call the execute methods such as command.ExecuteNonQuery().

What I would do is maybe make this method private, and create public methods for each SQL execution type such as ExecuteNonQuery and ExecuteScalar and ExecuteReader, with the same arguments of BuildCommand has, and all will be from within the same class.
Something like this :

public void ExecuteNonQuery(DbParameter[] parameters, string query)
{
    var command = BuildCommand(parameters, query);

    if (DbConnection.State != ConnectionState.Open)
        DbConnection.Open();

    command.ExecuteNonQuery();
}

The best approach for that will be creating a static property of SqlCommand then you initiate it, use it across the class, dispose it whenever you're done.

another question got in my mind is this :

if (parameters == null) throw new ArgumentNullException(nameof(parameters));

why you made parameters required? suppose you need to execute a query with no parameters such as SELECT * FROM table, then, you would have to adjust the current implementation or create new method for that. So, keeping it optional will come in handy.


Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:

Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.
Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.
Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.
If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).
Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.


Calculate the sum of interior angles of a polygon

The most serious problem I see here is failing to check the return value from scanf().  Never ignore that - it's the only way we have to determine whether conversions were successful.

A less serious issue is that we we're using a main() that takes command-line arguments, but never use them.  Prefer instead the no-argument version:

int main(void)

The copying of the shape's name isn't useful - we can just pass the pointer directly to printf():

        printf("The sum of the interior angles of a %s is %i\n",
               names[numSides - 3],
               getSumInteriorAngles(numSides));

We could even choose which to print by using a suitable pointer:

const char* names[] = {
    "a triangle",
    "a quadrilateral",
    "a pentagon",
    "a hexagon",
    "a heptagon",
    "an octagon",
    "a nonagon",
    "a decagon",
    "a hendecagon",
    "a dodecagon"
};

// ...

const char *name = "this polygon";
if (numSides <= 12) {
    name = names[numSides - 3];
}

printf("The sum of the interior angles of %s is %i\n",
       name, getSumInteriorAngles(numSides));

This also stops the code printing the ungrammatical "a octagon". :-)


Find the smallest distance between any two given words in a string

After staring at your code for some time,

You are using Hungarian notation, that is not a JavaScript practice

Related to that, strArr probably should have been arrStr if the code was consistent

It seems odd that you would return 0 when either word is not present, 0 would indicate that the words are neighbours. I would return -1 in that case.
You seem to track too much state in acc, you can get away with just tracking the last matched word, the location of the last matched word and what the best distance has been thus far
There are no comments whatsoever, I think your code could have used some

This is my functional approach:

const s = "dog cat hello cat dog dog hello cat dog world dog hello";

function smallestWordDistance(s, w1, w2) {

  function analyze(acc, word, index) {

    if (word == w1 || word == w2) {

      if (acc.word && acc.word != word) {
        const distance = index - acc.index - 1;
        acc.out = acc.out == -1 ? distance : Math.min(acc.out, distance);
      }
      acc.index = index;
      acc.word = word;
    }
    return acc;
  }

  return s.split(' ').reduce(analyze, { out: -1 }).out;
}

console.log(smallestWordDistance(s, "hello", "world"));


Efficiently concatenate substrings of long list of strings

The Performance Tips section at python.org has comments about doing repeated string concatenation which you may find here:

https://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation

Specifically, it suggests using "".join(listOfStrings) instead of repeatedly appending to an accumulator with +=.

So I would try something like this, using re.finditer() to find all of the comments, and place the non-comment parts into a list:

import re

def removeComments(s):
  chunks = []
  offset = 0
  for m in re.finditer("--.*\n", s):
    chunks.append( s[offset: m.start(0)] )
    offset = m.end(0)-1
  chunks.append( s[offset:] )
  return "".join(chunks)

s = """
line 1
line 2  -- comment 2
line 3
line 4 -- comment 4
line 5
line 6 -- comment 6
line 7
"""
print removeComments(s)

An advantage of this approach over splitting each line is that if there are large chunks of your program which do not have any comments they will transferred to the chunks list in one piece instead of as separate lines.

Update

I would also try using a regexp replace approach - it could be even faster:

def removeComments(s):
  return re.sub('(?m)--.*$', '', s)


Well, there's a potentially more efficient way:

Read the whole file into a byte-array (It's not even a measly 64K), thus avoiding any conversion overhead and most object-allocations, extract the start-indices of all the names, and sort them.

Is it equally nice? Probably not. And it will only speed it up by a constant factor, because more just isn't there to be had.
Anyway, measure it because while going down a level gives opportunities for optimization, it's easy to get it wrong.
If you don't want to go quite that far, here's an easy one: Strip the trailing " from the last name, and you can drop the test whether you actually have a letter in getValueOfName.
Getting to your constants name, that's atrocious. Because, you know, using a named constant for that at all is so bad.
You can simply use a character-literal: 'A'-1
You fail to close the file in readAllNames if newing the BufferedReader fails. Admittedly that's unlikely in such a small program, but anyway.
Also, why do you catch IOException there, but then return null which immediately causes a NPE in turn in main?


Here's a toy program to illustrate the separation of user input collection from the string matching that determines which calc to use, as we discussed in the comments.  Note that the class NamedCalculations has no knowledge of IO with the user.  All the IO is encapsulated in CmdLineCalculator.

When I find a match, I just evaluate it with the argument pi.  In your real application, you'd need to do further process to gather the user's input for the argument.

Also note how if we decide we want to change which calculations we support (one of the most likely changes for the application), it becomes a 1 line change, and the user input processing code doesn't need to be touched.

class NamedCalculations

  # a hash of named calcs
  # eg, {cos: Math.method(:cos), sin: Math.method(:sin) }
  def initialize(calc_definitions)
    @calc_definitions = calc_definitions
    @calc_names = @calc_definitions.keys.map(&:to_s)
  end

  def method_for(calc_name)
    calc_name = calc_name.to_sym
    raise "Invalid Calculation Name" unless @calc_definitions.key? calc_name
    @calc_definitions[calc_name]
  end

  def exact_match?(input)
    @calc_names.any? {|name| input == name}
  end

  def partial_match?(input)
    @calc_names.any? {|name| name.include? input}
  end

end

class CmdLineCalculator

  def initialize(named_calcs)
    @named_calcs = named_calcs
    @input = ''
  end

  def start
    begin
      system("stty raw -echo")
      collect_user_input while not calc_complete?
      show_answer
    ensure
      system("stty -raw echo")
    end
  end

  private

  def collect_user_input
    @input += next_input_char
    validate_input
    echo_last_char
  end

  def validate_input
    raise "Invalid Calculation" unless @named_calcs.partial_match? @input
  end

  def next_input_char
    STDIN.getc
  end

  def echo_last_char
    STDOUT.putc @input[-1]
  end

  def calc_complete?
    @named_calcs.exact_match? @input
  end

  def show_answer
    selected_method = @named_calcs.method_for(@input)
    value_at_pi = selected_method.call(Math::PI)
    STDOUT.puts "\nThe #{@input}(pi) = #{value_at_pi}"
  end

end

my_calcs = {cos: Math.method(:cos), sin: Math.method(:sin) }
client = CmdLineCalculator.new(NamedCalculations.new(my_calcs))
client.start


Compare length of iterator with as few `next` calls as possible. How can I deduplicate this code?

To know the answer to your comparison to \$N\$, you need to attempt at least:

\$N\$ next calls if you test with \$\lt\$ (succeeding will result to False) or \$\ge\$ (succeeding will result to True);
\$N+1\$ next calls in all 4 other cases.

Obviously, if the iterator length is fewer than \$N\$ there will be less calls.

So, in order to simplify things, you could extract the first \$N+1\$ elements of the iterator and count them to compare this count to \$N\$:

extracting can be simplified with itertools.islice
counting can be done using either

enumerate and dumping the content into a 1-length collections.deque

from itertools import islice
from collections import deque

def compare_length(iterable, n, operation):
    chunck = islice(iterable, max(0, n+1))
    try:
        (length, _) = deque(enumerate(chunk, 1), maxlen=1)
    except ValueError:
        length = 0
    return operation(length, n)

sum

from itertools import islice

def compare_length(iterable, n, operation):
    chunck = islice(iterable, max(0, n+1))
    length = sum(1 for _ in chunck)
    return operation(length, n)

The former should be more efficient, the latter more readable. As suggested in the question, this function takes the operation to perform as its third argument and compares min(<iterable length>, n+1) to n. This is sufficient in most cases.

If you truly want to reduce the amount of next calls needed for \$\lt\$ and \$\ge\$, you can keep your class approach and factorize the min(<iterable length>, n) part into an helper method:

from itertools import islice

class ILengthComparator:
    def __init__(self, iterable):
        self._iterable = iterable

    def _length_up_to(self, n):
        return sum(1 for _ in islice(self._iterable, max(0, n)))

    def __eq__(self, n):
        return self._length_up_to(n+1) == n

    def __ne__(self, n):
        return self._length_up_to(n+1) != n

    def __lt__(self, n):
        return self._length_up_to(n) < n

    def __le__(self, n):
        return self._length_up_to(n+1) <= n

    def __gt__(self, n):
        return self._length_up_to(n+1) > n

    def __ge__(self, n):
        return self._length_up_to(n) >= n

Lastly, if you want to avoid consuming the iterator while performing those tests, you can check itertools.tee.


Namespace Usage

I'd put all of this into some namespace, so it won't accidentally collide with other usage of the names it defines.

I'd probably also work even a little harder to do something to hide your node and Default templates. For example, node doesn't need to be visible to the outside world, so it would probably be better off defined inside of lru.

Prefer Initialization to Assignment

A constructor like this:

template<class K, class V>
inline node<K, V>::node(K key, V value) {
    this->key = key;
    this->value = value;
}

...is typically better written something like this instead:

template <class K, class V>
inline node<K, V>::node(K key, V value)
    : key(key)
    , value(value)
{}

In some cases, you must us initialization (like this) instead of assignment. In this case, it's not mandatory, but I still consider it preferable.

Consider passing by reference

Passing your keys and values by value generally requires copying. You might want to consider whether it's worth passing by reference instead. This generally accomplishes little (or nothing) if the type being passed is "small", but can improve speed substantially if the type is large.

Encapsulate knowledge of a type's internals in that type

Right now, your lru class "knows" (depends upon) the internals of the node class. I'd generally prefer if only node knew about its internals. For one possibility, you might pass a next and prev to the ctor, and let it put those values into the node itself:

template <class K, class V>
inline node<K, V>::node(K key, V value, node *prev = nullptr, node *next = nullptr)
    : key(key)
    , value(value)
    , prev(prev)
    , next(next)
{}

In this case, your code like this:

node<K, V>* temp = new node<K, V>(key, value);
temp->prev = nullptr;
temp->next = head;

...would become something like:

node<K, V> *temp = new node<K, V>(key, value, nullptr, head);

Consider other Data Structures

Although a doubly-linked list does work for the task at hand, it's often fairly wasteful, using a couple of pointers per node in addition to the data you actually care about storing.

I'd consider using a singly linked list instead. Although it may not immediately be obviously how you can do this, I'm reasonably certain you can.

Consider pre-allocating your storage

Given that the total maximum number of objects is fixed when you create the cache, I'd also consider pre-allocating storage for both the objects and the linked-list nodes when you create the cache. An allocator for a fixed-size set of fixed-size blocks can be really trivial, which can improve speed considerably over using a couple of allocations on the free store for every item you insert in the cache.


Counting all the vowels in a passage of text

Change to lower once: text.lower() instead of t.lower() inside loop.
Use t in vowels to check if the character is vowels.
vowels = {...} can be replaced with dict.fromkeys('aeiou', 0) (See dict.fromkeys)

Caution: Use this only if the value is immutable.

>>> dict.fromkeys('aeiou', 0)
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}

vowels = dict.fromkeys('aeiou', 0)

for t in text.lower():  # Change to lower once.
    if t in vowels:
        vowels[t] += 1

print vowels

Alternatively, you can use try ... except KeyError ...:

for t in text.lower():  # Change to lower once.
    try:
        vowels[t] += 1
    except KeyError:  # Ignore consonants.
        pass

Or using battery included, collections.Counter:

from collections import Counter
vowels = Counter(c for c in text.lower() if c in 'aeiou')
# => Counter({'e': 54, 'a': 41, 'o': 40, 'i': 37, 'u': 14})


Sieve of Eratosthenes and twin prime finder

Implementation

// Mark multiples of each prime as non-prime
for (int i = 2; i<max; i++) {
    if (arePrimes[i]) {
        for (int m = 2; i * m < max; m++) {
            arePrimes[i*m] = false;
        }
    }
}

Pretty close to the perfect implementation.

However...

Consider the Transitive relation of the multiplication operation: 5 times 2 is 10. 2 times 5 is 10. It doesn't matter in which order you multiply things.

So when you multiply, say, 3 by 2, you're just multiplying 2 by 3 again. And the same goes for 5 by 2, 7 by 2, 11 by 2... but also 5 by 3, 7 by 3, 7 by 5, etc.

What you'd do in this case is start m off at the value of i. This solves the issue where you're multiplying 2 with 3 and 3 with 2, thus checking the same thing twice.

There's another issue: Now that we're effectively checking (i * i) < max in the inner loop on the first iteration, it doesn't make sense for the outer loop to check for on i < max. Instead, you'd want to check for (i * i) < max there as well.

// Mark multiples of each prime as non-prime
for (int i = 2; i * i < max; i++) {
    if (arePrimes[i]) {
        for (int m = i; i * m < max; m++) {
            arePrimes[i*m] = false;
        }
    }
}

I was also a bit worried about getMax willing to accept negative numbers, but Java will throw a java.lang.NegativeArraySizeException, and as such, the error should be pretty clear. For use in a larger application, you might want to handle the exception, rather than the program forcibly exiting.

Documentation

You should use Javadoc style comments. Simple //comments before each function generally don't get picked up by IDE's. By making use of Javadoc, you can provide descriptions of what a method does and what the meaning of each parameter is. Like that, not only will other programmers easily be able to search for information in a method's documentation, it can also be automated - like an IDE showing a tooltip for each method parameter as you type them.


EventList a generic list implementation that raises events when items are added and removed

Bug

public void Insert(int index, T item)
{
    _list.Insert(index, item);
    RaiseEvent(ItemRemoved, item, index);
}

I don't think that you want to raise an ItemRemoved event in the case of inserting an item.

In general I like your implementation. It is leightweight and is doing exactly what it should.

But for sure I have something to critizise:

The name EventList<T> which reads like a list of events instead of a list with events. Because there is already a ObservableCollection<T> maybe an ObservableList<T> would be a better name.
You implement IList<T> but have the underlaying list as a List<T> instead of an IList<T> like private readonly IList<T> _list;.
The RemoveAt() could be simplified by calling the Remove() method like so

public void RemoveAt(int index)
{
    Remove(_list[index]);
}

 See @RomanReiner's answer here
IMO the raising of multiple ItemRemoved events inside the Clear() method isn't that good because you are raising the event before the item is removed. You should either have an additional event ItemsCleared or you should raise the ItemRemoved events after the clearing of that list.


Parse a specified arithmetic type from string

I'd prefer to use a dictionary for this.

private delegate bool TryParseDelegate<T>(string text, out T value);

private static readonly Dictionary<Type, object> TryParsers = new Dictionary<Type, object>
{
    { typeof(int), (TryParseDelegate<int>)int.TryParse },
    { typeof(float), (TryParseDelegate<float>)float.TryParse },
    { typeof(double), (TryParseDelegate<double>)double.TryParse }
};

The TryParse method:

public static bool TryParse<T>(string value, out T returnValue)
{
    // Check if we have a parse method for T in the dictionary.
    object parserObj;
    if (TryParsers.TryGetValue(typeof(T), out parserObj))
    {
        TryParseDelegate<T> parser = (TryParseDelegate<T>)parserObj;
        return parser(value, out returnValue);
    }
    // If no, fallback to IConvertible.
    if (typeof(IConvertible).IsAssignableFrom(typeof(T)))
    {
        try
        {
            returnValue = (T)Convert.ChangeType(value, typeof(T));
            return true;
        }
        catch { }
    }
    // No luck.
    returnValue = default(T);
    return false;
}

This approach support exensibility.
For example, imagine we have a class A:

public class A
{
    public static readonly A Zero = new A("Zero");
    public static readonly A One = new A("One");

    public readonly string Text;

    private A(string text)
    {
        Text = text;
    }

    public static bool TryParse(string text, out A value)
    {
        switch (text.ToLower())
        {
            case "zero":
                value = Zero;
                break;
            case "one":
                value = One;
                break;
            default:
                value = null;
                return false;
        }
        return true;
    }

    public override string ToString()
    {
        return Text;
    }
}

Then the only thing you have to do is to append an item to the dictionary:

{ typeof(A), (TryParseDelegate<A>)A.TryParse }

Let's test it:

int i;
double d;
A a;

if (TryParse("123", out i))
    Console.WriteLine($"i={i}"); // Prints i=123
if (TryParse("123.456", out d))
    Console.WriteLine($"d={d}"); // Prints d=123.456
if (TryParse("ONE", out a))
    Console.WriteLine($"a={a}"); // Prints a=One


power should probably be using Math.pow().  I'm picturing how slow your code would be at calculating 1.00000015000000.  Or how inaccurate it'll be when someone wants to raise to a non-integer power.  If those are not intended to be allowed, then passing doubles all over the place seems odd.  But it'd be better to check beforehand and throw an error than return a blatantly incorrect result, in my opinion.
You never set done to true, and thus have an infinite loop; take out the flag and say while (true) or for (;;), so that that's apparent.  Don't add the flag back til you're also adding the code that sets it.
The fact that you use objects doesn't make your code object-oriented.  How you use them is what makes the difference.  In this case, you're using classes as namespaces for functions, which is not very object-oriented at all.

In your case, Maths is entirely useless; everything it does would be better done in your own code.  This is an example of gratuitous use of objects.  If you wanted to practice your OOP, you might want to think about how you'd get rid of that switch statement.  Hint:

public interface BinaryOperation {
    public double resultFor(double left, double right);
}

class Multiplication implements BinaryOperation {
    public double resultFor(double left, double right) {
        return left * right;
    }
}

class Addition implements BinaryOperation {
    public double resultFor(double left, double right) {
        return left + right;
    }
}

private Map<Character, BinaryOperation> operations;

...

operations.put('*', new Multiplication());
operations.put('+', new Addition());

...

BinaryOperation op = operations.get(operator);
if (op != null) {
    answer = op.resultFor(inputA, inputB);
}
else {
    System.out.println("Error: Unknown operator");
]


Name the method SendAsync since it is meant to be used asynchronously. Since this is in a web app, all awaited calls should chain to .ConfigureAwait(false). Also, since you're async, use await writer.WriteAsync rather than writer.Write. A few more Streams need to be wrapped in using statements. Don't swallow exceptions -- Logging them is all right. Method does not seem to access any instance data, so it could be static and therefore the class it is in can be as well. Here is a rewrite:

    public static async Task SendAsync()
    {
        var request = WebRequest.Create("url") as HttpWebRequest;

        if (request == null)
        {
            return;
        }

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        request.Headers["authorization"] = "token";

        var byteArray = Encoding.UTF8.GetBytes("{"
                                                  + "\"app_id\": \"appId\","
                                                  + "\"extra_parameter\": \"value\"}");

        string responseContent = null;

        try
        {
            using (var writer = await request.GetRequestStreamAsync().ConfigureAwait(false))
            {
                await writer.WriteAsync(byteArray, 0, byteArray.Length).ConfigureAwait(false);
            }

            using (var response = await request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse)
            {
                if (response != null)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                responseContent = await reader.ReadToEndAsync().ConfigureAwait(false);
                            }
                        }
                    }
                }
            }
        }
        catch (WebException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            if (ex.Response != null)
            {
                using (var responseStream = ex.Response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            System.Diagnostics.Debug.WriteLine(await reader.ReadToEndAsync().ConfigureAwait(false));
                        }
                    }
                }
            }

            throw;
        }

        System.Diagnostics.Debug.WriteLine(responseContent ?? string.Empty);
    }


Simplify multiple conditions using a switch

Whenever multiple conditions depend only on the value of a single variable,
consider using a switch instead to simplify:

switch (ans) {
    case 1:
        Quadratic.CalcQuad();
        break;
    case 2:
        CompInt.CalcInt();
        break;
    default:
        System.out.println("That was not an option.");
}

Naming

The common convention is to use camelCase for function names.
The method names CalcQuad and CalcInt violate that.

It also seems that the class names could be better.
If you spell out their purpose, the names won't be much longer but a lot more intuitive and unambiguous, for example:

Quadratic -> QuadraticCalculator
CompInt -> CompoundInterestCalculator

And then the methods that do the calculation can be simply calculate in both classes, without including the type of calculation, which is already included in the class name.

Alternatively, you could use a single Calculator class with calculateQuadratic and calculateCompoundInterest methods.


How to write save block code like this more elegant in Ruby?

You want instance methods, not class methods.  With the current code, you would get:

hello = Creator.create { puts "Hello" }
goodbye = Creator.create { puts "Goodbye" }
hello.for(1)   # Prints "Goodbye"

Assuming you don't want block to be changed afterwards, I would change attr_accessor to attr_reader.  I don't see much reason to even expose a reader, though — it seems that doing so would only lead to mischief.

class Creator
  # For compatibility with the old API
  def self.create(&block)
    return self.new(&block)
  end

  def initialize(&block)
    @block = block
  end

  def for(number)
    number.times { @block.call }
  end
end

This is just a syntactic sugar wrapper for blocks.  Perhaps a more generic name than Creator might be appropriate.  It might also be simpler to call number.times { block.call } directly.

Standard indentation for Ruby is two spaces.


Python script using distutils to copy files on a Mac

The code looks OK. A few specific improvements can be made.

Readability

import os
import distutils.core

Learn about PEP8, you should have two empty lines between imports and the rest of the code. More generally, you should give more structure to your code to make it more readable. Empty lines are one way to achieve that. For example, one empty line before each comment could be nice.

# Create a local site for the mount to reside
directory = "/Users/username/share"
if not os.path.exists(directory): os.makedirs(directory)

PEP8 comment: prefer indenting ifs to make clear they are ifs.

"Security"

# Mount the Windows smb share
os.system("mount_smbfs //service.account:password@server.domain.com/share ~/share")

Don't store account and password in your source file. You could move them to a configuration file (that would not be tracked if you used git or svn) or retrieve them from the environment (but then they would show up in your shell logs).

Don't Repeat Yourself

# set source and destination
fromDirectory1 = "/Volumes/Macintosh HD/folder1/folder2/folder3"
fromDirectory2 = "/Volumes/Macintosh HD/folder4/folder5/folder6"
fromDirectory3 = "/Volumes/Macintosh HD2/folder1/folder2"
fromDirectory4 = "/Volumes/Macintosh HD2/folder1/folder3/folder4"
toDirectory1 = "/Users/username/share/folder3"
toDirectory2 = "/Users/username/share/folder6"
toDirectory3 = "/Users/username/share/folder2"
toDirectory4 = "/Users/username/share/folder4"

Variables name var1, var2 and so on indicate that you should use a list of pairs or a dictionary!

directories = [
    ("/Volumes/Macintosh HD/folder1/folder2/folder3", "/Users/username/share/folder3"),
    ("/Volumes/Macintosh HD/folder4/folder5/folder6", "/Users/username/share/folder6"),
]

#Do the copying
for from, to in directories:
    distutils.dir_util.copy_tree(from, to)

#Unmount the share
os.system("umount ~/share")

A note about the 80-char limit: in this case, the directories list is more readable if you don't enforce the rule.

Recovering from failures

What happens when mounting works but not copying? You should still try to unmount your folder.

try:
    # mount
    # copy
finally:
    # umount

You can also decide to catch exceptions if you know what to do about them.


Simplify my class mapping common class properties between model and viewmodel classes

Providing

var dogVms = new List<MonthViewModel>();

is meant to actually be

var dogVms = new List<DogViewModel>();

Then to use LINQ you could do

List<DogViewModel> dogVms = (from dog in dogs select (DogViewModel)dog).ToList();


Maximum product of 3 integers in an int array

Minor edge case
It's possible that the product of three integers will overflow.  For example, three positive integers may produce a negative product and cause your function to return the other product instead.  Since your function returns an int, it's not clear what you are supposed to do if that happens.  Perhaps you are guaranteed that the values are small enough not to overflow?
Otherwise the function looks correct and easy to understand.


Extract a character at particular place in a string

According to MSDN, this function is already implemented:

' Code from MSDN
'
Dim myString As String = "ABCDE"
Dim myChar As Char
' The value of myChar is "D".
myChar = myString.Chars(3)

A review of your code

Please indent your code.
I would choose another, more meaningful name for your function: getCharAt or getByteFromString. It is now clear that the function operates on a string.
I would use the clearer parameter name str instead of s.
"Compress":

place = place + 1
getbyte = Mid(s, place, 1)

' change to
getbyte = Mid(s, place + 1, 1)

The first version is definitely not wrong or ugly, but why use an extra line if we could express the same logic in the same clear manner?
You could use If to shorten your code:

Private Function getbyte(str As String, ByVal place As Integer) As String
  getbyte = If(place < Len(str), Mid(str, place + 1, 1), "")
End Function


Universal OpenGL object RAII wrapper class

Ensuring you have distinct types
You said this in the comments:

I thought that use of templates instead of a common base class would better emphasize that these objects shouldn't be mixed together (now they are completely distinct types).

Two classes that derive from the same base class are also two distinct types. Furthermore, you can make the constructor of the base class protected, so you cannot instantiate a bare base class, and you can use protected or private inheritance to ensure you cannot get a pointer to the base class from a derived class. For example:
class base {
protected:
    base() = default;
};

class derived: base {
    ...
};

derived foo;      // OK
base bar;         // Error: constructor is protected
base *baz = &foo; // Error: base is inaccessible

The problem with template specialization
Your construction using template specialization has a flaw. The problem is that all member functions you might ever want to use in specializations need to be present in the default template. This is why you have:
template <GLenum T>
class gl_object
{
    ...
    inline gl_object( );
    inline explicit gl_object( GLenum target );
    ...
};

The second constructor that takes the target parameter is only used for gl_object<GL_TEXTURE>, and in fact you must have a target for the texture in order to call glCreateTextures(). The problem is now that I can do the following:
gl_object<GL_BUFFER> buffer(GL_TEXTURE_2D);
gl_object<GL_TEXTURE> texture;

The above statements will compile without errors (but perhaps with a warning), because you promised both constructors would exist. Only the linker will give an error, because there is no implementation of those constructors. But in a large project it might be hard to track down this issue.
You won't have this problem with derived classes, since you have full control over which public member functions (including constructors) each derived class has.
Alternatives without templates
There are two ways to implement this without templates. Either you say that, for example, a gl_texture "is a" gl_object, and use class inheritance, or you say that a gl_texture "has a" gl_name (the OpenGL term for the GLuint identifier given to objects), and use composition. In the first case, you'd structure your code as:
class gl_object {
protected:
    GLuint m_id;

    gl_object() = default;

    // delete copy constructors
    // add move semantics
    // access the ID
};

class gl_buffer: gl_object {
public:
    gl_buffer() {
        glCreateBuffers(1, &m_id);
    }
    ...

    // Enable the default constructor and assignment operator:
    gl_buffer(gl_buffer &&other) = default;
    gl_buffer &operator=(gl_buffer &&other) = default;
};

In the second case, you would write:
class gl_name {
private:
    GLuint m_id;

public:
    // delete copy constructors
    // add move semantics
    // access the ID

    GLuint &get() {
        return m_id;
    }
};

class gl_buffer {
private:
    gl_name m_id;

public:
    gl_buffer() {
        glCreateBuffers(1, &m_id.get());
    }
    ...

    // Enable the default constructor and assignment operator:
    gl_buffer(gl_buffer &&other) = default;
    gl_buffer &operator=(gl_buffer &&other) = default;
};

In the second case, since you deleted the copy constructors for gl_name, classes that use that as a member variable will also no longer be default copy constructable.
The main drawback of either two cases is that you need to implement the move constructors and move assignment operators in each derived class. In this case the default move constructor and move assignment operator would have worked just fine, but they have been implicitly deleted. To re-enable them, just explicitly add the default move constructor and move assignemnt operator.


Function that uses an exception to check if user exists

I would suggest working the other way around. Expect that a user does not exist and only return true if a user is found.

private function UserExists($userId)
{
    $userExists = false;

    try
    {
        $user = new User($userId);
        if($user !== null)
            $userExists = true;
    }
    catch (Exception $e)
    {
        //handle exception
    }

    return $userExists;
}

You can drive this further and ease things by not using a variable to return, like this:

private function UserExists($userId)
{
    try
    {
        return new User($userId) !== null;
    }
    catch (Exception $e)
    {
        return false;
    }
}


In Python you can compare multiple values the following way:

if (user, comp) in {(0, 2), (1, 0), (2, 1)} :
    print('You win against the computer\n')
elif user == comp :
    print('You tie against the computer\n')
else :
    print('You lose against the computer\n')


Incorrect indention

All of the methods in a class need to be indented such that they are inside the class definition. (this is based on the original version of the code you posted.

Instead of this:

 class StopWatch(Frame):
   """ Implements a stop watch frame widget. """
   def __init__(self, parent=None, **kw): ...

def makeWidgets(self): ...
def _update(self): ...
def _setTime(self, elap): ...
def Start(self): ...
def Stop(self): ...
def Reset(self): ...
def clock_in(self): ...
def clock_out(self): ...

You need to do this:

class StopWatch(Frame):
   """ Implements a stop watch frame widget. """
    def __init__(self, parent=None, **kw): ...

    def makeWidgets(self): ...
    def _update(self): ...
    def _setTime(self, elap): ...
    def Start(self): ...
    def Stop(self): ...
    def Reset(self): ...
    def clock_in(self): ...
    def clock_out(self): ...

Follow PEP8 Guidelines

PEP8 gives guidelines that every python program should follow. Specifically in your case, function names need to begin with a lowercase character.

StringVar is unnecessary overhead

In most cases, using StringVar adds overhead with no real value. While this is more of a personal preference, I see no reason to use it. StringVar objects are good if you want the exact same value displayed in two or more widgets, or if you're wanting to trace changes. Otherwise they are superfluous.

Instead of self.timestr, you can directly alter the widget value. So, instead of saving a reference to the StringVar, save a reference to the widget:

def makeWidgets(self):
    ...
    self.time_label = Label(self, textvariable=self.timestr)
    ...

def _setTime(self, elap):
    ...
    self.time_label.configure(text='%02d:%02d:%02d' % (minutes, seconds, hseconds))
    ...

Be consistent with private methods

By convention, private methods (methods that are only used internally) are named with a leading underscore. You do this with _update and _setTime, but you didn't do it with makeWidgets. You should try to be consistent: if a function is only used internally, name it with a leading underscore.

Don't hard-code the filename

Your program would be a bit more portable if you didn't hard-code the filename. Right now you have the filename hard-coded in the clock_in and clock_out functions.

Instead, make it a parameter when you instantiate the class, or make it global.

For example:

def clock_in(self):
    ...
    with open(self.filename, "a") as savedb:
    ...

def clock_out(self):
    ...
    with open(self.filename, "a") as savedb:
    ...
sw = StopWatch(root, filename=r"C:\Users\Desktop\ClockIn.csv")

Separate widget creation from widget layout

In my experience, separating widget creation makes the code easier to visualize and easier to maintain.

Instead of this:

Button(root, text='Clock In', command=lambda :[sw.Start(), sw.clock_in()]).pack(side=LEFT)
Button(root, text='Clock Out', command=lambda :[sw.Start(), sw.clock_out()]).pack(side=LEFT)
Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
Button(root, text='Quit', command=root.quit).pack(side=LEFT)

... do this:

clock_in_button = Button(...)
clock_out_button = Button(...)
reset_button = Button(...)
quit_button = Button(...)

clock_in_button.pack(side=LEFT)
clock_out_button.pack(side=LEFT)
reset_button.pack(side=LEFT)
quit_button.pack(side=LEFT)

This makes it much more clear to see at a glance that all for buttons are aligned to the left. When it's all blocked together it's much harder to see.

Incorrect use of tkinter

You're importing tkinter with import tkinter as tk but then trying to use tk classes without the tk. prefix.

The import is good, but you need to fix all of the code that is creating widgets. For example, tk.Button(...) instead of just `Button(...).


Avoid wildcard imports

You should use import tkinter as tk instead of from tkinter import Tk, Canvas. This is a PEP8 recommendation where you can find the reason of this. Of course, in this case, you have to prefix your widgets with tk. For instance: my_button = tk.Button(...)

Remove useless comments

To be honest, most of your comments (docstrings, to be exact) can be removed. Let us take an example:

def double_click(self, event):
    '''  set flag when there is a double click '''
    self.double_click_flag = True

The docstring is just noisy. It does not bring any additional information when I read self.double_click_flag = True. That comment just repeats what the instruction already tells me. Avoid repeating yourself, even through comments.

The same is true when it comes to inline comments. Example:

self.aw.bind('<Button-1>', self.clicked)  # bind left mouse click

Use the main guard

Sometimes we want to run some code only if the program was used by itself and not when it was imported from another module, for this reason it is good to use if __name__ == "__main__":

def main():
    root = tk.Tk()
    window = tk.Canvas(root, width=400, height=400, bg='grey')
    mouse = MouseControl(window)
    window.place(x=0, y=0)
    window.mainloop()

if __name__ == "__main__":
    main()

Simplify the handlers

I find your handlers having unnecessary code. Simply take advantage of the button events themselves and get rid of all those unnecessary flags which are rather cumbersome in case you want to add more code in the future (because they play the role of global variables, which thing we do not like in programming).

Taking in consideration what has been said so far, here is your code cleaned:

import tkinter as tk

class MouseControl:
    def __init__(self, canvas):
        self.canvas = canvas
        self.canvas.bind('<Button-1>', self.clicked)
        self.canvas.bind('<Double-1>', self.double_click)
        self.canvas.bind('<ButtonRelease-1>', self.button_released)
        self.canvas.bind('<B1-Motion>', self.moved)

    def clicked(self, event):
        print('single mouse click event at ({}, {})'.format(event.x, event.y))

    def double_click(self, event):
        print('double mouse click event')

    def button_released(self, event):
        print('button released')

    def moved(self, event):
        print('mouse position is at ({:03}. {:03})'.format(event.x, event.y), end='\r')

def main():
    root = tk.Tk()
    window = tk.Canvas(root, width=400, height=400, bg='grey')
    mouse = MouseControl(window)
    window.place(x=0, y=0)
    window.mainloop()

if __name__ == "__main__":
    main()


Computers do numbers!

Compared to manipulating numbers, strings are very slow and use a lot of memory relative to what is being done.

To test if it is a perfect integer

const isPerfectInt = num => {
    var sum = (num | 0) % 10;
    while (num > 0) { sum += (num = num / 10 | 0) % 10 }
    return sum === 10;
}

Improved cache

You are caching results in your answer and you only cache what you are looking for. However while you are searching you find all the perfect values below the one you are looking for. This negates most the advantage you get from caching calculations.

If you keep all calculated perfect numbers you can then use that last calculated value as a starting point. That way you will never test the same value twice.

const cache = [0,19];  // set up first value. Saves some messing about
const getNthPerfectNumber = n => {
    if (cache[n]) { return cache[n] }

    // Start from the last number tested plus one.
    var idx = cache.length - 1, num = cache[idx] + 1;
    while (idx < n) {
        if (isPerfectInt(num)) { cache[++idx] = num }
        num++;
    }
    return num - 1;
};


Better way to manipulate this string in sequence?

You could create a StringProcessor interface:

public interface StringProcessor {

    String process(String input);
}

public class BoldProcessor implements StringProcessor {

    public String process(final String input) {
        ...
    }
}

and create a List from the available implementations:

final List<StringProcessor> processors = new ArrayList<StringProcessor>();
processors.add(new ItalicProcessor());
processors.add(new BoldProcessor());
...

and use it:

String result = input;
for (final StringProcessor processor: processors) {
    result = processor.process(result);
}
return result;


Select fields from a form by ID or Xpath and fill its value

You use a lot of absolute xpaths. It's a bad practice, since those are costly to maintain and looks bad. Try to modify them to relative xpath's or preferably css selectors.
Instead of implicit wait, use explicit wait and wait until certain conditions are met. Or if you test ajax based application - try waiting for ajax requests to complete.
Seems that your application might have quite some dropdowns. Create extention
someElement.SelectByText(string text)or static method Select.ByText(someText).FromElement(someElements) and initialize SelectElement there. It mostly good to abstract yourself from any lib.
Check out PageFactory pattern - maybe you will like it. It's another way of finding elements - more readable and convenient.
I don't advocate to use page object pattern since I think it is an anti pattern in any object oriented language, but for starter - try it.
Why is your method static?


Optimizing execution time of merging images

The best way to gain speed is to keep the resulting images, and use them again if the same images are needed. This will eliminate the merging on the second run altogther.

Since you don't give any clue as to what end you're doing this, I cannot start to guess how useful my suggestion is...

Your question would be better if we knew:

What your images look like, how big are they? (You've added this in, thanks)
Where do they come from?
What do you use the images for?

If you describe the situation in which you use your code, instead of just an isolated bit of code, then people can be much more creative in their answers. It is obvious there's not much we can improve in the plain and simple PHP code you show, so any solution would probably be found in the way you use the code.

Now that you've added some extra information to your question, it's easier to help you.

I assume, from what you say, that you're using the code only once, just after you've uploaded a new picture in your CMS, and you need to merge something into it.

The answer can be pretty short: Computers don't have unlimited processing power, so complex operations, like this, will take a long time.

There are some tips I can give:

Don't merge 16 times when you receive the image, but merge (once) when one on the 16 images is requested. This reduces the merger time to less than half a second per image.
Reduce the size of the images before merging. Images of 500 x 500 pixels will merge four times as fast as images of 1000 x 1000 pixels.
Use a background process to do the merging: https://florian.ec/articles/running-background-processes-in-php (use with care and only if there's really no other solution, which almost always does exists).


How to make this query better (e.g. avoid repeating subquery in a query)?

The query title is

Questions answered by more than 3 50k users

But that doesn't describe what the query actually does. The query selects questions with three answers given by three distinct top n rated users. They happen to have more than 50k rep on that site, but that's a mere coincidence.
That can also be done by this query, containing only 1 subquery to get the top rated users:
SELECT Q.Id AS [Post Link], Q.AnswerCount
FROM Posts Q
WHERE Q.AnswerCount = 3
AND
(
  SELECT COUNT( DISTINCT A.OwnerUserId)
  FROM Posts A
  WHERE A.ParentId = Q.Id
  AND A.OwnerUserId IN
  (
    SELECT TOP ##TopN## Id
    FROM Users
    ORDER BY Reputation DESC
  )
) = 3

For the record, the query doing what the title says would be
SELECT Q.Id AS [Post Link], Q.AnswerCount
FROM Posts Q
WHERE Q.AnswerCount >= 3
AND
(
  SELECT COUNT(DISTINCT A.OwnerUserId)
  FROM Posts A
  JOIN Users U ON A.OwnerUserId = U.Id
  WHERE A.ParentId = Q.Id
  AND U.Reputation >= 50000
) = Q.AnswerCount

Assuming that the intention was to get questions with answers from 50k users exclusively.


Find the probability of picking a prime number in a range

Your question contains 2 pieces of code which makes it hard to review.

Issue specific to the C++ code

Your are using ++i in your code despite having handled the even numbers explicitely before. It should be i+=2 like in your Java code.

Issue in both implementations

Instead of maintaining an ans boolean value, you can simply return false whenever you know that the number can't be prime.

You write your loop like this for(int i = 3; i<(Math.sqrt(n)+1);i=i+2) which is likely to compute the square root at each iteration. The compiler may be able to optimize this out but just in case, it is probably better to store it in a variable beforehand.

Different algorithm

To know whether many numbers are primes, a convenient and efficient algorithm is to use The Sieve of Eratosthenes to build a table to check primes.

You could build it one and for all to get the primes up to the maximum r value.

Going further, you could also build (once) a table giving for each number n the number of primes numbers smaller or equal to n. Then, for each input (a, b), the frequency is something along the lines of ( primes_up_to(b) - primes_up_to(a) / (b - a).


Groups/Communities in Facebook snap dataset using networkx in python

After searching and researching to find the solution to this question i came up with this answer:

To find/detect communities in facebook snap dataset:

import networkx as nx
import matplotlib.pyplot as plt
import community

'''Exploratory Data Analysis'''
g = nx.read_edgelist('facebook_combined.txt', create_using=nx.Graph(), nodetype=int)
print nx.info(g)

'''Simple Graph'''
# sp = nx.spring_layout(g)
# nx.draw_networkx(g, pos=sp, with_labels=False, node_size=35)
# # plt.axes("off")
# plt.show()

'''Graph with communities dectection'''
spring_pos = nx.spring_layout(g)
parts = community.best_partition(g)
values = [parts.get(node) for node in g.nodes()]

plt.axis("off")
nx.draw_networkx(g, pos=spring_pos, cmap=plt.get_cmap("jet"), node_color=values, node_size=35, with_labels=False)
plt.show()

this will give the following output:


Gather all IP addresses of a host as a vector

I agree with you that the copying of data from s6_addr seems cumbersome.  I would instead just cast without copying:
auto& bytearray = reinterpret_cast<std::array<unsigned char,16>&>(ipv6socket->sin6_addr.s6_addr);

(If we had needed to copy, we could change auto& to plain auto).
Apart from this, the variable ipv6base is never used, so should just be removed.


My approach for something like this would be to have the two (sub-)forms wrapped in a grouping element such as a fieldset and just loop over all fields in one and match them with the other. Quick incomplete, untested example:

<form>
  <fieldset id="shipping-address">
    <input name="shipping-firstname">
    <input name="shipping-lastname">
  </fieldset>
  <fieldset id="billing-address">
    <input name="billing-firstname">
    <input name="billing-lastname">
  </fieldset>
</form>

<script>
  $("shipping-address input").each(function() {
    var shippingInput = $(this);
    var billingInputName = "billing" + shippingInput.attr("name").slice(8);
    $("#billing-address [name=" + billingInputName + "]").val(shippingInput.val());
  });
</script>


Get AD Users' Latest Last Logon Dates across Multiple DCs

Aliases

You're used to my reviews by now so you're probably tired of me saying this, but avoid aliases and abbreviations (% vs ForEach-Object, Select vs Select-Object, -expand vs -ExpandProperty, sort vs Sort-Object, etc.).

Backticks ` as line continuation

Try to avoid shortening lines with backtick where possible. The backticks are hard to see / easy to miss.

Note that you can end a line with a pipe | or an operator and continue on the next line without the backtick, which I think is a much more flexible solution:

Get-ADObject -Filter { whatever } |
Sort-Object BySomething |
Select-Object Thing1,Thing2,Thing3 |
Where-Object {
    $_.A -eq 5 -and
    $_.Z -like '*what*' -and
    $_.BoolProp
} |
Format-Table

As an added bonus, it doesn't confuse the syntax highlighting on these sites!

Domain Controller Discovery

When finding a domain controller in a certain region, you might consider filtering on Site. Nothing wrong with going by your naming convention, although it's more likely for that to change, or for a short pattern like ES* to match something else; I'm sure you've considered that and your pattern is fine, just offering another suggestion.

I also like to add -Discover, -ForceDiscover, and -Service ADWS to ensure that you are finding DCs that are available and usable with PowerShell. Combined:

$DCs = Get-ADDomainController -Discover -ForceDiscover -SiteName Spain -Service ADWS | Select-Object -Expand Name

Logon Dates

You're probably already familiar with the logon date attributes in AD, but I'll summarize:

LastLogon — Updated every time a user logs on, but only on the domain controller that authenticated the user. This value is not replicated.
LastLogonTimestamp — This value is replicated, but to avoid heavy replication traffic it's not updated every time, so you sacrifice accuracy (it could be as much as 2 weeks off by default), but you only have to query a single DC to get the value. This value is also annoying to turn into an actual date.
LastLogonDate — This is not actually in AD. It's provided by the PowerShell cmdlets, and it's a real [DateTime] object that has the same value as LastLogonTimestamp, which makes it really convenient to use and filter on.

So, depending on how accurate you really need this process to be, you might avoid querying all the DCs in the first place and just take LastLogonDate as being "Close Enough" for your purposes. It would simplify things greatly if that's acceptable.

The thing is, this also reveals a problem in your script. You are already using LastLogonDate, you're just querying it from every DC instead of using LastLogon. As long as replication is working correctly, that value will always be the same, so querying multiple DCs is unnecessary.

If you want the precision, you need to use LogonDate (and do the appropriate conversions like in the technet script you linked to). This is probably why Group-Object is not often used. Because it's not so trivial to treat this attribute directly as a [DateTime].

Search-ADAccount

I'm not sure I understand the aversion to using Search-ADAccount. The object returned is still an AD account object, and it includes the LastLogonDate property so you can return that.

After re-reading it I understand; you're not filtering on any specific date in this script. So you're returning all users and their dates.

Simplification

Based on what I wrote above, I might suggest a more simple solution (I know this isn't SO but, it's basically a one-liner...):

$DC = Get-ADDomainController -Discover -ForceDiscover -SiteName Spain -Service ADWS | Select-Object -Expand Name -First 1
Get-ADUser -SearchBase $SearchBase -Filter { Enabled -eq $true } -Properties LastLogonDate -Server $DC |
Sort-Object SamAccountName |
Select-Object SamAccountName,Name,LastLogonDate

I would even add that because the attribute is replicated, there's no need to query a Spanish DC; you can leave out the whole discovery part and just let Get-ADUser use the logon server, or use discovery but don't limit it to a site. It should in theory be more efficient to simply query the closest DC to where the script is running.


You should read up on arrays :

    Console.Write("Minor error 1: ")
    minorerror1(counter) = Console.ReadLine
    Console.Write("Minor error 2: ")
    minorerror2(counter) = Console.ReadLine
    Console.Write("Minor error 3: ")
    minorerror3(counter) = Console.ReadLine
    Console.Write("Minor error 4: ")
    minorerror4(counter) = Console.ReadLine
    Console.Write("Minor error 5: ")
    minorerror5(counter) = Console.ReadLine

This should be a loop which writes to an array of strings.

Proposed reading : MSDN link on arrays


Bug

poperr leaves a null on the stack if errorstack is null. Better:

/poperr {
    errorstack null ne {
        errorstack aload pop  /errorstack exch store
        exec put
    } if
}

This leaves the stack clean and makes extra calls to poperr harmless. If desireable, some action could be put in the else case but since this code is mucking about with error handlers, it is unclear whether signalling an error is correct here.


Other answers are great, but this is really re-inventing the wheel. What you are looking for is the observer pattern. .NET has great in-built capabilities with observer through System.Observer<T> and System.Observable<T>. You can also get the library Rx-Main through NuGet to gain the ability to compose these, LINQ-style, into operations that can be filtered or exploded or modified as you see fit.

In .NET's Observable<T>, the Observable<T> produces values once it is subscribed to (unless it is a hot observable - that's out of scope of this answer). It will then send an OnComplete 'message' to the subscribed Observer<T> when it has finished. It also has the ability to send an OnError(Exception) notification to the Observer, but only if the exception occurs during the subscription. Exceptions during observation are not implicitly caught.

Before we get onto that, it's worth nothing that you also have Task<T>. It's really worth realizing what you are trying to do here. I feel that putting a Completed event on your class is a code smell as it's breaking encapsulation, and you should really bind the completion to the lifecycle of the method invocation (i.e, make it a return). Semantically speaking, if your method will only produce one result (i.e, "I've finished"), then you should return a Task (or Task<T>). This lets users use async/await.

If your method is going to have a sequence of results before finishing (i.e, it's got an IEnumerable perhaps?) then you should return an IObservable<T>.

Here's how I would lay it out in both cases.

public class TutorialController
{
    public async Task DoLongOperation()
    {
        return Task.Run(() => ....);
    }
}

Task.Factory.StartNew(controller.DoLongOperation()).ContinueWith(() => ...);

Replace the ellipsis with the rest of your DoLongOperation method's code. If your DoLongOperation needs to return a single result, change the return to a Task<T>. By the way, you should only use Task.Run if your long operation is CPU-bound or partially IO/CPU bound.

If your DoLongOperation returns multiple results - for example, it's getting a list of things from an external resource such as a web resource - you should instead return IObservable<T>. With ReactiveExtensions, the asynchronous composition is very useful and makes IObservable<T> better than Task<IEnumerable<T>> in this case.

public class TutorialController
{
    public IObservable<T> DoLongOperation()
    {

        return Observable.Create(() => ...);
    }
}

var results = Observable.Subscribe(p => OnNext(p), e => OnException(e), () => OnCompleted());

IObservable<T> leaves the a/synchronous nature of the call up to the caller, so you don't need async on this method.

If you provide the rest of your code for your DoLongOperation I can help convert it to IObservable. But really, the code you have right now seems like a hugeeee code smell. For one, it's mutable, and it's DEFINITELY not thread safe.

By the way one guarantee this code gives you over say @Memleak's answer is that you can invoke Subscribe on a completed Observable and no exceptions will be thrown there is no opportunity for side-effects, which is key in asynchrony. This is infinitely better than having two separate units of functionality in a single function based on whether something has already been Disposed/Completed or not. This adheres to the idea that disposables should fail silently if they have already been disposed of.

As @Jeroen rightly mentioned in chat, .NET events are an implementation of the observer pattern. But Rx's IObservable / TPL's Task allows you to compose asynchronous events and has a notion of completeness - .NET events do not. This is more useful for your use case.


Fast nth prime in Python using trial division

Division is a comparatively expensive operation, and it accounts for the lion's share of the time taken by trial division. Hence there are two major routes for improving efficiency:

reduce the cost of divisions by replacing them with multiplications
reduce the number of divisions by filtering candidates efficiently

Replacing divisions as a means of divisibility testing (i.e. x % p == 0) with multiplicatoin (x * MINV <= QMAX) gives a seven-fold speed increase in C++, but in Python it will be a lot less because of the interpreter overhead.

'Filtering candidates' means eliminating multiples of small primes during enumeration of the candidates that will be subjected to trial division. The most famous variant is skipping multiples of two (a.k.a. 'odds-only' or 'mod 2 wheel'), but also fairly well known - often under almost superstitious guises - is the mod 6 wheel that steps in the rhythm 4,2,4,2,... A further savings comes from the fact that the small primes skipped during enumeration can also be skipped during trial division. That is, when candidates are stepped mod 6 then the trial division would start with the prime 5, not 2.

Benchmarks, detailed explanations - and links to even more detailed explanations including papers - are in my answer to

Prime sieve implementation (using trial division) in C++

Code in that topic is in C++ and C#, but the principles and techniques apply to any language.


CMakeLists and Clang sanitization options for an ncurses program

I am not familiar with the Clang sanitization command-line options so I can't give any feedback about those,
but regarding the CMake code I would suggest the following CMakeLists.txt file

cmake_minimum_required(VERSION 3.13)
project(FirstProject C)

find_package(Curses REQUIRED)

add_executable(${CMAKE_PROJECT_NAME} main.c)

target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_INCLUDE_DIR})
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_LIBRARIES})

if(NOT CMAKE_C_COMPILER_ID STREQUAL "Clang")
  message(WARNING "Use the Clang compiler instead. "
                  "FirstProject officially supports Clang "
                  "(although other compilers might work).")
endif()

target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99)
target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE
  $<$<C_COMPILER_ID:Clang>:
    -Weverything
    -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi
    -flto
    -fvisibility=default>)
target_link_options(${CMAKE_PROJECT_NAME} PRIVATE
  $<$<C_COMPILER_ID:Clang>:
    -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi
    -flto>)

Some comments

Avoid using FILE(GLOB) to specify source code files

Avoid using FILE(GLOB), instead specify the source code files explicitly either by

add_executable(${CMAKE_PROJECT_NAME} main.c)

or

add_executable(${CMAKE_PROJECT_NAME})
target_sources(${CMAKE_PROJECT_NAME} PRIVATE main.c)

Śee also https://stackoverflow.com/questions/32411963/why-is-cmake-file-glob-evil

Use target_* commands

Avoid

using include_directories()
setting CMAKE_C_FLAGS directly

Instead use

target_compile_features()
target_compile_options()
target_include_directories()
target_link_libraries()
target_link_options()

The FindCurses module does not yet support imported targets as of today (2 January 2019, CMake 3.13.2) so it needs to
be used in the old style

target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_INCLUDE_DIR})
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${CURSES_LIBRARIES})

In the future (when support has been added to CMake for imported targets in FindCurses) the two lines should be replaced by the line:

target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE Curses::Curses)

Instead of setting the CMake variable CMAKE_C_STANDARD

set(CMAKE_C_STANDARD 99)

is good practice to use  target_compile_features() instead

 target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99)

In this very case it makes no practical difference  but for a
 C++ header-only library, such compile features could be specified in the INTERFACE

 add_library(myheaderonly INTERFACE)
 target_compile_features(headeronlylib INTERFACE cxx_std_11)

to provide usage requirements for consumers of the library (see also https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html)

The target_link_options() line was added to be able to build the executable. (I am not sure it is correct).

Use generator expressions

The generator expression

$<$<C_COMPILER_ID:Clang>:-Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default>

is expanded to

-Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default

when the Clang compiler is used, but for other compilers it is expanded to nothing.

Avoid setting CMAKE_C_COMPILER

Instead of setting the CMake variable CMAKE_C_COMPILER, give a WARNING or a FATAL_ERROR whenever a  non-supported C compiler is used.

if(NOT CMAKE_C_COMPILER_ID STREQUAL "Clang")
  message(WARNING "Use the Clang compiler instead. FirstProject officially supports Clang (although other compilers might work).")
endif()

(WARNING could be replaced by FATAL_ERROR to prevent the use of any other C compiler than Clang)

To compile the project, specify the C compiler with the environment variable CC

mkdir /tmp/build
cd /tmp/build
CC=clang cmake -G Ninja ~/FirstProject
ninja -v

Use the ninja command-line flag -v  if you want to see the actual commands being run.


This will not be faster (which would require you move away from ggplot) but could give you ideas about writing better/cleaner code. The code first:

field_vec_plot <- function(fun, xmin = -1,
                                xmax =  1,
                                ymin = -1,
                                ymax =  1,
                                density = 10) {

  data <- expand.grid(x = seq(xmin, xmax, length.out = density),
                      y = seq(ymin, ymax, length.out = density))

  data <- within(data, {
     dydx = fun(x, y)
     dx   = sqrt((1 / density) / (1 + dydx ^ 2))
     dy   = dx * dydx
  })

  library(ggplot2)
  library(grid) # for arrow()
  xmar <- (xmax - xmin) / density # margin for x
  ymar <- (ymax - ymin) / density # margin for y
  ggplot(data = data, aes(x = x, y = y)) +
    geom_point(size = 1) +
    geom_segment(aes(xend = x + dx, yend = y + dy),
                 arrow = arrow(length = unit(0.1, "cm"))) +
    xlim(xmin - xmar, xmax + xmar) +
    ylim(ymin - ymar, ymax + ymar)
}

f_prime <- function(x, y) x ^ 2 / (1 - x ^ 2 - y ^ 2)
field_vec_plot(f_prime, xmin = -4, xmax = 4,
                        ymin = -4, ymax = 4,
                        density = 40)

Some of the recommendations:

Always write a function (with appropriate inputs and outputs)
expand.grid already returns a data.frame
mapply was not needed since f_prime is vectorized. This will be faster but it is probably a drop in the sea compared to plotting.
The use of within to add dependent columns interactively (no need to write data$ over and over and your code is much more readable.)
Make your code (especially the one you posted here) source the packages it requires. I had to look where arrow() was coming from
Do not write code that throws warnings. Read the message carefully and find what the problem is. In this case, it was warning when trying to plot arrows outside the plotting area. Hence I added some margins xmar and ymar to the plotting area.
Personal preference: put some space after commas and on each side of = and binary operators. Also use linebreaks so your lines are never too long and add spaces to make things align when you get a chance.
I have removed your comments because they were not using the R syntax (need # and not //) but that's an easy fix. Yes, comments are good and having a lot of them was great.

Disclaimer: I am not 100% confident that your 1 / density nor my definitions of xmar and ymar are correct, given what you are trying to achieve. Try this for example:

field_vec_plot(f_prime, xmin = -1, xmax = 1, ymin = -1, ymax = 1, density = 10)

where the arrows seem a little too long...


CodeEval solutions to find trailing strings

I suggest a functional answer for this problem (In ruby but should easily be translatable into Java):

def endswith(text, appendix)
    text.last(appendix.length) == appendix
end

I did not benchmark but this approach is likely to be faster as you are only using using 2 functions and a comparison instead of all the loops and ifs that you used.


Your question was a little confusing. But I will try and summarize it before I go into my solution:

You have a struct that you are unpacking and during that process you get the number of IPs 'they' have and the length of those IPs (either 4 or 16)
You want to get all of their IPs dynamically based on that length and number of IPs.

Based on my hopefully correct summary above, you can do this simply with a for loop:

num_their_ips = struct.unpack(">b", payload[10])
len_their_ips = struct.unpack(">b", payload[12])

byte_string = '>{}'.format('b'*len_their_ips[0])
their_ips = []
for count in range(num_their_ips[0]):
    start = 13 + (count*len_their_ips[0])
    end = start + len_their_ips[0]

    ip = struct.unpack(byte_string, payload[start:end])
    print 'IP #{}: {}'.format(count+1, ip)

    their_ips.append(ip)

Now a quick note on your naming conventions. Pythonic convention is to use_underscores in variable names. This is especially needed in your code because your variable names are quite hard to distinguish, as was evident in how much 'trouble' I had converting your names below:

our_op_ip, no_their_ip, their_or_ip_v, their_or_addr_len, their_first_ip, their_second_ip

I would also suggest making your names more descriptive. Right now they feel wordy and are a little confusing. Take no_their_ips as an example: does that mean they don't have any IPs, or is it a shortening of 'number'?

Now, I may be being a tad too purposefully dense. However, this is the way people could look at your code; they may not know what some of the acronyms and abbreviations mean. Writing code with descriptive variable names helps improve the readability of your program.